text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in_android/google_sign_in_android.dart'; import 'package:google_sign_in_android/src/messages.g.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'google_sign_in_android_test.mocks.dart'; final GoogleSignInUserData _user = GoogleSignInUserData( email: '[email protected]', id: '8162538176523816253123', photoUrl: 'https://lh5.googleusercontent.com/photo.jpg', displayName: 'John Doe', idToken: '123', serverAuthCode: '789', ); final GoogleSignInTokenData _token = GoogleSignInTokenData( accessToken: '456', ); @GenerateMocks(<Type>[GoogleSignInApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); late GoogleSignInAndroid googleSignIn; late MockGoogleSignInApi api; setUp(() { api = MockGoogleSignInApi(); googleSignIn = GoogleSignInAndroid(api: api); }); test('registered instance', () { GoogleSignInAndroid.registerWith(); expect(GoogleSignInPlatform.instance, isA<GoogleSignInAndroid>()); }); test('signInSilently transforms platform data to GoogleSignInUserData', () async { when(api.signInSilently()).thenAnswer((_) async => UserData( email: _user.email, id: _user.id, photoUrl: _user.photoUrl, displayName: _user.displayName, idToken: _user.idToken, serverAuthCode: _user.serverAuthCode, )); final dynamic response = await googleSignIn.signInSilently(); expect(response, _user); }); test('signInSilently Exceptions -> throws', () async { when(api.signInSilently()) .thenAnswer((_) async => throw PlatformException(code: 'fail')); expect(googleSignIn.signInSilently(), throwsA(isInstanceOf<PlatformException>())); }); test('signIn transforms platform data to GoogleSignInUserData', () async { when(api.signIn()).thenAnswer((_) async => UserData( email: _user.email, id: _user.id, photoUrl: _user.photoUrl, displayName: _user.displayName, idToken: _user.idToken, serverAuthCode: _user.serverAuthCode, )); final dynamic response = await googleSignIn.signIn(); expect(response, _user); }); test('signIn Exceptions -> throws', () async { when(api.signIn()) .thenAnswer((_) async => throw PlatformException(code: 'fail')); expect(googleSignIn.signIn(), throwsA(isInstanceOf<PlatformException>())); }); test('getTokens transforms platform data to GoogleSignInTokenData', () async { const bool recoverAuth = false; when(api.getAccessToken(_user.email, recoverAuth)) .thenAnswer((_) async => _token.accessToken!); final GoogleSignInTokenData response = await googleSignIn.getTokens( email: _user.email, shouldRecoverAuth: recoverAuth); expect(response, _token); }); test('getTokens will not pass null for shouldRecoverAuth', () async { when(api.getAccessToken(_user.email, true)) .thenAnswer((_) async => _token.accessToken!); final GoogleSignInTokenData response = await googleSignIn.getTokens( email: _user.email, shouldRecoverAuth: null); expect(response, _token); }); test('initWithParams passes arguments', () async { const SignInInitParameters initParams = SignInInitParameters( hostedDomain: 'example.com', scopes: <String>['two', 'scopes'], signInOption: SignInOption.games, clientId: 'fakeClientId', ); await googleSignIn.init( hostedDomain: initParams.hostedDomain, scopes: initParams.scopes, signInOption: initParams.signInOption, clientId: initParams.clientId, ); final VerificationResult result = verify(api.init(captureAny)); final InitParams passedParams = result.captured[0] as InitParams; expect(passedParams.hostedDomain, initParams.hostedDomain); expect(passedParams.scopes, initParams.scopes); expect(passedParams.signInType, SignInType.games); expect(passedParams.clientId, initParams.clientId); // These should use whatever the SignInInitParameters defaults are. expect(passedParams.serverClientId, initParams.serverClientId); expect(passedParams.forceCodeForRefreshToken, initParams.forceCodeForRefreshToken); }); test('initWithParams passes arguments', () async { const SignInInitParameters initParams = SignInInitParameters( hostedDomain: 'example.com', scopes: <String>['two', 'scopes'], signInOption: SignInOption.games, clientId: 'fakeClientId', serverClientId: 'fakeServerClientId', forceCodeForRefreshToken: true, ); await googleSignIn.initWithParams(initParams); final VerificationResult result = verify(api.init(captureAny)); final InitParams passedParams = result.captured[0] as InitParams; expect(passedParams.hostedDomain, initParams.hostedDomain); expect(passedParams.scopes, initParams.scopes); expect(passedParams.signInType, SignInType.games); expect(passedParams.clientId, initParams.clientId); expect(passedParams.serverClientId, initParams.serverClientId); expect(passedParams.forceCodeForRefreshToken, initParams.forceCodeForRefreshToken); }); test('clearAuthCache passes arguments', () async { const String token = 'abc'; await googleSignIn.clearAuthCache(token: token); verify(api.clearAuthCache(token)); }); test('requestScopens passes arguments', () async { const List<String> scopes = <String>['newScope', 'anotherScope']; when(api.requestScopes(scopes)).thenAnswer((_) async => true); final bool response = await googleSignIn.requestScopes(scopes); expect(response, true); }); test('signOut calls through', () async { await googleSignIn.signOut(); verify(api.signOut()); }); test('disconnect calls through', () async { await googleSignIn.disconnect(); verify(api.disconnect()); }); test('isSignedIn passes true response', () async { when(api.isSignedIn()).thenAnswer((_) async => true); expect(await googleSignIn.isSignedIn(), true); }); test('isSignedIn passes false response', () async { when(api.isSignedIn()).thenAnswer((_) async => false); expect(await googleSignIn.isSignedIn(), false); }); }
packages/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart", "repo_id": "packages", "token_count": 2366 }
971
// 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 <TargetConditionals.h> #if TARGET_OS_OSX @import FlutterMacOS; #else @import Flutter; #endif @import XCTest; @import google_sign_in_ios; @import google_sign_in_ios.Test; @import GoogleSignIn; // OCMock library doesn't generate a valid modulemap. #import <OCMock/OCMock.h> @interface FLTGoogleSignInPluginTest : XCTestCase @property(strong, nonatomic) NSObject<FlutterBinaryMessenger> *mockBinaryMessenger; @property(strong, nonatomic) NSObject<FlutterPluginRegistrar> *mockPluginRegistrar; @property(strong, nonatomic) FLTGoogleSignInPlugin *plugin; @property(strong, nonatomic) id mockSignIn; @property(strong, nonatomic) NSDictionary<NSString *, id> *googleServiceInfo; @end @implementation FLTGoogleSignInPluginTest - (void)setUp { [super setUp]; self.mockBinaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); self.mockPluginRegistrar = OCMProtocolMock(@protocol(FlutterPluginRegistrar)); id mockSignIn = OCMClassMock([GIDSignIn class]); self.mockSignIn = mockSignIn; OCMStub(self.mockPluginRegistrar.messenger).andReturn(self.mockBinaryMessenger); self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:mockSignIn registrar:self.mockPluginRegistrar]; [FLTGoogleSignInPlugin registerWithRegistrar:self.mockPluginRegistrar]; NSString *plistPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"GoogleService-Info" ofType:@"plist"]; if (plistPath) { self.googleServiceInfo = [[NSDictionary alloc] initWithContentsOfFile:plistPath]; } } - (void)testSignOut { FlutterError *error; [self.plugin signOutWithError:&error]; OCMVerify([self.mockSignIn signOut]); XCTAssertNil(error); } - (void)testDisconnect { [(GIDSignIn *)[self.mockSignIn stub] disconnectWithCompletion:[OCMArg invokeBlockWithArgs:[NSNull null], nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"]; [self.plugin disconnectWithCompletion:^(FlutterError *error) { XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testDisconnectIgnoresError { NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeHasNoAuthInKeychain userInfo:nil]; [(GIDSignIn *)[self.mockSignIn stub] disconnectWithCompletion:[OCMArg invokeBlockWithArgs:sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"]; [self.plugin disconnectWithCompletion:^(FlutterError *error) { XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } #pragma mark - Init - (void)testInitNoClientIdNoError { // Init plugin without GoogleService-Info.plist. self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:self.mockSignIn registrar:self.mockPluginRegistrar googleServiceProperties:nil]; // init call does not provide a clientId. FSIInitParams *params = [FSIInitParams makeWithScopes:@[] hostedDomain:nil clientId:nil serverClientId:nil]; FlutterError *error; [self.plugin initializeSignInWithParameters:params error:&error]; XCTAssertNil(error); } - (void)testInitGoogleServiceInfoPlist { self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:self.mockSignIn registrar:self.mockPluginRegistrar googleServiceProperties:self.googleServiceInfo]; FSIInitParams *params = [FSIInitParams makeWithScopes:@[] hostedDomain:@"example.com" clientId:nil serverClientId:nil]; FlutterError *initializationError; [self.plugin initializeSignInWithParameters:params error:&initializationError]; XCTAssertNil(initializationError); // Initialization values used in the next sign in request. [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *error){ }]; OCMVerify([self configureMock:self.mockSignIn forSignInWithHint:nil additionalScopes:OCMOCK_ANY completion:OCMOCK_ANY]); XCTAssertEqualObjects(self.plugin.configuration.hostedDomain, @"example.com"); // Set in example app GoogleService-Info.plist. XCTAssertEqualObjects( self.plugin.configuration.clientID, @"479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com"); XCTAssertEqualObjects(self.plugin.configuration.serverClientID, @"YOUR_SERVER_CLIENT_ID"); } - (void)testInitDynamicClientIdNullDomain { // Init plugin without GoogleService-Info.plist. self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:self.mockSignIn registrar:self.mockPluginRegistrar googleServiceProperties:nil]; FSIInitParams *params = [FSIInitParams makeWithScopes:@[] hostedDomain:nil clientId:@"mockClientId" serverClientId:nil]; FlutterError *initializationError; [self.plugin initializeSignInWithParameters:params error:&initializationError]; XCTAssertNil(initializationError); // Initialization values used in the next sign in request. [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *error){ }]; OCMVerify([self configureMock:self.mockSignIn forSignInWithHint:nil additionalScopes:OCMOCK_ANY completion:OCMOCK_ANY]); XCTAssertEqualObjects(self.plugin.configuration.hostedDomain, nil); XCTAssertEqualObjects(self.plugin.configuration.clientID, @"mockClientId"); XCTAssertEqualObjects(self.plugin.configuration.serverClientID, nil); } - (void)testInitDynamicServerClientIdNullDomain { self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:self.mockSignIn registrar:self.mockPluginRegistrar googleServiceProperties:self.googleServiceInfo]; FSIInitParams *params = [FSIInitParams makeWithScopes:@[] hostedDomain:nil clientId:nil serverClientId:@"mockServerClientId"]; FlutterError *initializationError; [self.plugin initializeSignInWithParameters:params error:&initializationError]; XCTAssertNil(initializationError); // Initialization values used in the next sign in request. [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *error){ }]; OCMVerify([self configureMock:self.mockSignIn forSignInWithHint:nil additionalScopes:OCMOCK_ANY completion:OCMOCK_ANY]); XCTAssertEqualObjects(self.plugin.configuration.hostedDomain, nil); // Set in example app GoogleService-Info.plist. XCTAssertEqualObjects( self.plugin.configuration.clientID, @"479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com"); XCTAssertEqualObjects(self.plugin.configuration.serverClientID, @"mockServerClientId"); } - (void)testInitInfoPlist { FSIInitParams *params = [FSIInitParams makeWithScopes:@[ @"scope1" ] hostedDomain:@"example.com" clientId:nil serverClientId:nil]; FlutterError *error; self.plugin = [[FLTGoogleSignInPlugin alloc] initWithRegistrar:self.mockPluginRegistrar]; [self.plugin initializeSignInWithParameters:params error:&error]; XCTAssertNil(error); XCTAssertNil(self.plugin.configuration); XCTAssertNotNil(self.plugin.requestedScopes); // Set in example app Info.plist. XCTAssertEqualObjects( self.plugin.signIn.configuration.clientID, @"479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com"); XCTAssertEqualObjects(self.plugin.signIn.configuration.serverClientID, @"YOUR_SERVER_CLIENT_ID"); } #pragma mark - Is signed in - (void)testIsNotSignedIn { OCMStub([self.mockSignIn hasPreviousSignIn]).andReturn(NO); FlutterError *error; NSNumber *result = [self.plugin isSignedInWithError:&error]; XCTAssertNil(error); XCTAssertFalse(result.boolValue); } - (void)testIsSignedIn { OCMStub([self.mockSignIn hasPreviousSignIn]).andReturn(YES); FlutterError *error; NSNumber *result = [self.plugin isSignedInWithError:&error]; XCTAssertNil(error); XCTAssertTrue(result.boolValue); } #pragma mark - Sign in silently - (void)testSignInSilently { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([mockUser userID]).andReturn(@"mockID"); [[self.mockSignIn stub] restorePreviousSignInWithCompletion:[OCMArg invokeBlockWithArgs:mockUser, [NSNull null], nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin signInSilentlyWithCompletion:^(FSIUserData *user, FlutterError *error) { XCTAssertNil(error); XCTAssertNotNil(user); XCTAssertNil(user.displayName); XCTAssertNil(user.email); XCTAssertEqualObjects(user.userId, @"mockID"); XCTAssertNil(user.photoUrl); XCTAssertNil(user.serverAuthCode); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testSignInSilentlyWithError { NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeHasNoAuthInKeychain userInfo:nil]; [[self.mockSignIn stub] restorePreviousSignInWithCompletion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin signInSilentlyWithCompletion:^(FSIUserData *user, FlutterError *error) { XCTAssertNil(user); XCTAssertEqualObjects(error.code, @"sign_in_required"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } #pragma mark - Sign in - (void)testSignIn { self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:self.mockSignIn registrar:self.mockPluginRegistrar googleServiceProperties:self.googleServiceInfo]; id mockUser = OCMClassMock([GIDGoogleUser class]); id mockUserProfile = OCMClassMock([GIDProfileData class]); OCMStub([mockUserProfile name]).andReturn(@"mockDisplay"); OCMStub([mockUserProfile email]).andReturn(@"[email protected]"); OCMStub([mockUserProfile hasImage]).andReturn(YES); OCMStub([mockUserProfile imageURLWithDimension:1337]) .andReturn([NSURL URLWithString:@"https://example.com/profile.png"]); OCMStub([mockUser profile]).andReturn(mockUserProfile); OCMStub([mockUser userID]).andReturn(@"mockID"); id mockSignInResult = OCMClassMock([GIDSignInResult class]); OCMStub([mockSignInResult user]).andReturn(mockUser); OCMStub([mockSignInResult serverAuthCode]).andReturn(@"mockAuthCode"); [self configureMock:[self.mockSignIn expect] forSignInWithHint:nil additionalScopes:@[] completion:[OCMArg invokeBlockWithArgs:mockSignInResult, [NSNull null], nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *error) { XCTAssertNil(error); XCTAssertEqualObjects(user.displayName, @"mockDisplay"); XCTAssertEqualObjects(user.email, @"[email protected]"); XCTAssertEqualObjects(user.userId, @"mockID"); XCTAssertEqualObjects(user.photoUrl, @"https://example.com/profile.png"); XCTAssertEqualObjects(user.serverAuthCode, @"mockAuthCode"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; // Set in example app GoogleService-Info.plist. XCTAssertEqualObjects( self.plugin.configuration.clientID, @"479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com"); OCMVerifyAll(self.mockSignIn); } - (void)testSignInWithInitializedScopes { FlutterError *initializationError; [self.plugin initializeSignInWithParameters:[FSIInitParams makeWithScopes:@[ @"initial1", @"initial2" ] hostedDomain:nil clientId:nil serverClientId:nil] error:&initializationError]; id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([mockUser userID]).andReturn(@"mockID"); id mockSignInResult = OCMClassMock([GIDSignInResult class]); OCMStub([mockSignInResult user]).andReturn(mockUser); [self configureMock:[self.mockSignIn expect] forSignInWithHint:nil additionalScopes:[OCMArg checkWithBlock:^BOOL(NSArray<NSString *> *scopes) { return [[NSSet setWithArray:scopes] isEqualToSet:[NSSet setWithObjects:@"initial1", @"initial2", nil]]; }] completion:[OCMArg invokeBlockWithArgs:mockSignInResult, [NSNull null], nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *error) { XCTAssertNil(error); XCTAssertEqualObjects(user.userId, @"mockID"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; OCMVerifyAll(self.mockSignIn); } - (void)testSignInAlreadyGranted { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([mockUser userID]).andReturn(@"mockID"); id mockSignInResult = OCMClassMock([GIDSignInResult class]); OCMStub([mockSignInResult user]).andReturn(mockUser); [self configureMock:[self.mockSignIn stub] forSignInWithHint:nil additionalScopes:OCMOCK_ANY completion:[OCMArg invokeBlockWithArgs:mockSignInResult, [NSNull null], nil]]; NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeScopesAlreadyGranted userInfo:nil]; [self configureMock:mockUser forAddScopes:OCMOCK_ANY completion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *error) { XCTAssertNil(error); XCTAssertEqualObjects(user.userId, @"mockID"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testSignInError { NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeCanceled userInfo:nil]; [self configureMock:[self.mockSignIn stub] forSignInWithHint:nil additionalScopes:OCMOCK_ANY completion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *error) { XCTAssertNil(user); XCTAssertEqualObjects(error.code, @"sign_in_canceled"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testSignInException { OCMExpect([self configureMock:self.mockSignIn forSignInWithHint:OCMOCK_ANY additionalScopes:OCMOCK_ANY completion:OCMOCK_ANY]) .andThrow([NSException exceptionWithName:@"MockName" reason:@"MockReason" userInfo:nil]); __block FlutterError *error; XCTAssertThrows( [self.plugin signInWithCompletion:^(FSIUserData *user, FlutterError *signInError) { XCTAssertNil(user); error = signInError; }]); XCTAssertEqualObjects(error.code, @"google_sign_in"); XCTAssertEqualObjects(error.message, @"MockReason"); XCTAssertEqualObjects(error.details, @"MockName"); } #pragma mark - Get tokens - (void)testGetTokens { id mockUser = OCMClassMock([GIDGoogleUser class]); id mockUserResponse = OCMClassMock([GIDGoogleUser class]); id mockIdToken = OCMClassMock([GIDToken class]); OCMStub([mockIdToken tokenString]).andReturn(@"mockIdToken"); OCMStub([mockUserResponse idToken]).andReturn(mockIdToken); id mockAccessToken = OCMClassMock([GIDToken class]); OCMStub([mockAccessToken tokenString]).andReturn(@"mockAccessToken"); OCMStub([mockUserResponse accessToken]).andReturn(mockAccessToken); [[mockUser stub] refreshTokensIfNeededWithCompletion:[OCMArg invokeBlockWithArgs:mockUserResponse, [NSNull null], nil]]; OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin getAccessTokenWithCompletion:^(FSITokenData *token, FlutterError *error) { XCTAssertNil(error); XCTAssertEqualObjects(token.idToken, @"mockIdToken"); XCTAssertEqualObjects(token.accessToken, @"mockAccessToken"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testGetTokensNoAuthKeychainError { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeHasNoAuthInKeychain userInfo:nil]; [[mockUser stub] refreshTokensIfNeededWithCompletion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin getAccessTokenWithCompletion:^(FSITokenData *token, FlutterError *error) { XCTAssertNil(token); XCTAssertEqualObjects(error.code, @"sign_in_required"); XCTAssertEqualObjects(error.message, kGIDSignInErrorDomain); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testGetTokensCancelledError { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeCanceled userInfo:nil]; [[mockUser stub] refreshTokensIfNeededWithCompletion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin getAccessTokenWithCompletion:^(FSITokenData *token, FlutterError *error) { XCTAssertNil(token); XCTAssertEqualObjects(error.code, @"sign_in_canceled"); XCTAssertEqualObjects(error.message, kGIDSignInErrorDomain); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testGetTokensURLError { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSError *sdkError = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:nil]; [[mockUser stub] refreshTokensIfNeededWithCompletion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin getAccessTokenWithCompletion:^(FSITokenData *token, FlutterError *error) { XCTAssertNil(token); XCTAssertEqualObjects(error.code, @"network_error"); XCTAssertEqualObjects(error.message, NSURLErrorDomain); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testGetTokensUnknownError { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSError *sdkError = [NSError errorWithDomain:@"BogusDomain" code:42 userInfo:nil]; [[mockUser stub] refreshTokensIfNeededWithCompletion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin getAccessTokenWithCompletion:^(FSITokenData *token, FlutterError *error) { XCTAssertNil(token); XCTAssertEqualObjects(error.code, @"sign_in_failed"); XCTAssertEqualObjects(error.message, @"BogusDomain"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } #pragma mark - Request scopes - (void)testRequestScopesResultErrorIfNotSignedIn { XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin requestScopes:@[ @"mockScope1" ] completion:^(NSNumber *success, FlutterError *error) { XCTAssertNil(success); XCTAssertEqualObjects(error.code, @"sign_in_required"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testRequestScopesIfNoMissingScope { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeScopesAlreadyGranted userInfo:nil]; [self configureMock:[mockUser stub] forAddScopes:@[ @"mockScope1" ] completion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin requestScopes:@[ @"mockScope1" ] completion:^(NSNumber *success, FlutterError *error) { XCTAssertNil(error); XCTAssertTrue(success.boolValue); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testRequestScopesResultErrorIfMismatchingUser { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSError *sdkError = [NSError errorWithDomain:kGIDSignInErrorDomain code:kGIDSignInErrorCodeMismatchWithCurrentUser userInfo:nil]; [self configureMock:[mockUser stub] forAddScopes:@[ @"mockScope1" ] completion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin requestScopes:@[ @"mockScope1" ] completion:^(NSNumber *success, FlutterError *error) { XCTAssertNil(success); XCTAssertEqualObjects(error.code, @"mismatch_user"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testRequestScopesWithUnknownError { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSError *sdkError = [NSError errorWithDomain:@"BogusDomain" code:42 userInfo:nil]; [self configureMock:[mockUser stub] forAddScopes:@[ @"mockScope1" ] completion:[OCMArg invokeBlockWithArgs:[NSNull null], sdkError, nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin requestScopes:@[ @"mockScope1" ] completion:^(NSNumber *success, FlutterError *error) { XCTAssertNil(error); XCTAssertFalse(success.boolValue); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testRequestScopesException { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); OCMExpect([self configureMock:mockUser forAddScopes:@[] completion:OCMOCK_ANY]) .andThrow([NSException exceptionWithName:@"MockName" reason:@"MockReason" userInfo:nil]); [self.plugin requestScopes:@[] completion:^(NSNumber *success, FlutterError *error) { XCTAssertNil(success); XCTAssertEqualObjects(error.code, @"request_scopes"); XCTAssertEqualObjects(error.message, @"MockReason"); XCTAssertEqualObjects(error.details, @"MockName"); }]; } - (void)testRequestScopesReturnsFalseIfOnlySubsetGranted { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSArray<NSString *> *requestedScopes = @[ @"mockScope1", @"mockScope2" ]; // Only grant one of the two requested scopes. id mockSignInResult = OCMClassMock([GIDSignInResult class]); OCMStub([mockUser grantedScopes]).andReturn(@[ @"mockScope1" ]); OCMStub([mockSignInResult user]).andReturn(mockUser); [self configureMock:[mockUser stub] forAddScopes:requestedScopes completion:[OCMArg invokeBlockWithArgs:mockSignInResult, [NSNull null], nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin requestScopes:requestedScopes completion:^(NSNumber *success, FlutterError *error) { XCTAssertNil(error); XCTAssertFalse(success.boolValue); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } - (void)testRequestsInitializedScopes { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); FSIInitParams *params = [FSIInitParams makeWithScopes:@[ @"initial1", @"initial2" ] hostedDomain:nil clientId:nil serverClientId:nil]; FlutterError *initializationError; [self.plugin initializeSignInWithParameters:params error:&initializationError]; XCTAssertNil(initializationError); // Include one of the initially requested scopes. NSArray<NSString *> *addedScopes = @[ @"initial1", @"addScope1", @"addScope2" ]; [self.plugin requestScopes:addedScopes completion:^(NSNumber *success, FlutterError *error){ }]; // All four scopes are requested. [self configureMock:[mockUser verify] forAddScopes:[OCMArg checkWithBlock:^BOOL(NSArray<NSString *> *scopes) { return [[NSSet setWithArray:scopes] isEqualToSet:[NSSet setWithObjects:@"initial1", @"initial2", @"addScope1", @"addScope2", nil]]; }] completion:OCMOCK_ANY]; } - (void)testRequestScopesReturnsTrueIfGranted { id mockUser = OCMClassMock([GIDGoogleUser class]); OCMStub([self.mockSignIn currentUser]).andReturn(mockUser); NSArray<NSString *> *requestedScopes = @[ @"mockScope1", @"mockScope2" ]; // Grant both of the requested scopes. id mockSignInResult = OCMClassMock([GIDSignInResult class]); OCMStub([mockUser grantedScopes]).andReturn(requestedScopes); OCMStub([mockSignInResult user]).andReturn(mockUser); [self configureMock:[mockUser stub] forAddScopes:requestedScopes completion:[OCMArg invokeBlockWithArgs:mockSignInResult, [NSNull null], nil]]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion called"]; [self.plugin requestScopes:requestedScopes completion:^(NSNumber *success, FlutterError *error) { XCTAssertNil(error); XCTAssertTrue(success.boolValue); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:5.0 handler:nil]; } #pragma mark - Utils - (void)configureMock:(id)mock forAddScopes:(NSArray<NSString *> *)scopes completion:(nullable void (^)(GIDSignInResult *_Nullable signInResult, NSError *_Nullable error))completion { #if TARGET_OS_OSX [mock addScopes:scopes presentingWindow:OCMOCK_ANY completion:completion]; #else [mock addScopes:scopes presentingViewController:OCMOCK_ANY completion:completion]; #endif } - (void)configureMock:(id)mock forSignInWithHint:(NSString *)hint additionalScopes:(NSArray<NSString *> *)additionalScopes completion:(nullable void (^)(GIDSignInResult *_Nullable signInResult, NSError *_Nullable error))completion { #if TARGET_OS_OSX [mock signInWithPresentingWindow:OCMOCK_ANY hint:hint additionalScopes:additionalScopes completion:completion]; #else [mock signInWithPresentingViewController:[OCMArg isKindOfClass:[FlutterViewController class]] hint:hint additionalScopes:additionalScopes completion:completion]; #endif } @end
packages/packages/google_sign_in/google_sign_in_ios/darwin/Tests/GoogleSignInTests.m/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/darwin/Tests/GoogleSignInTests.m", "repo_id": "packages", "token_count": 13613 }
972
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import '../google_sign_in_platform_interface.dart'; import 'utils.dart'; /// An implementation of [GoogleSignInPlatform] that uses method channels. class MethodChannelGoogleSignIn extends GoogleSignInPlatform { /// This is only exposed for test purposes. It shouldn't be used by clients of /// the plugin as it may break or change at any time. @visibleForTesting MethodChannel channel = const MethodChannel('plugins.flutter.io/google_sign_in'); @override Future<void> init({ List<String> scopes = const <String>[], SignInOption signInOption = SignInOption.standard, String? hostedDomain, String? clientId, }) { return initWithParams(SignInInitParameters( scopes: scopes, signInOption: signInOption, hostedDomain: hostedDomain, clientId: clientId)); } @override Future<void> initWithParams(SignInInitParameters params) { return channel.invokeMethod<void>('init', <String, dynamic>{ 'signInOption': params.signInOption.toString(), 'scopes': params.scopes, 'hostedDomain': params.hostedDomain, 'clientId': params.clientId, 'serverClientId': params.serverClientId, 'forceCodeForRefreshToken': params.forceCodeForRefreshToken, }); } @override Future<GoogleSignInUserData?> signInSilently() { return channel .invokeMapMethod<String, dynamic>('signInSilently') .then(getUserDataFromMap); } @override Future<GoogleSignInUserData?> signIn() { return channel .invokeMapMethod<String, dynamic>('signIn') .then(getUserDataFromMap); } @override Future<GoogleSignInTokenData> getTokens( {required String email, bool? shouldRecoverAuth = true}) { return channel .invokeMapMethod<String, dynamic>('getTokens', <String, dynamic>{ 'email': email, 'shouldRecoverAuth': shouldRecoverAuth, }).then((Map<String, dynamic>? result) => getTokenDataFromMap(result!)); } @override Future<void> signOut() { return channel.invokeMapMethod<String, dynamic>('signOut'); } @override Future<void> disconnect() { return channel.invokeMapMethod<String, dynamic>('disconnect'); } @override Future<bool> isSignedIn() async { return (await channel.invokeMethod<bool>('isSignedIn'))!; } @override Future<void> clearAuthCache({required String token}) { return channel.invokeMethod<void>( 'clearAuthCache', <String, String?>{'token': token}, ); } @override Future<bool> requestScopes(List<String> scopes) async { return (await channel.invokeMethod<bool>( 'requestScopes', <String, List<String>>{'scopes': scopes}, ))!; } }
packages/packages/google_sign_in/google_sign_in_platform_interface/lib/src/method_channel_google_sign_in.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_platform_interface/lib/src/method_channel_google_sign_in.dart", "repo_id": "packages", "token_count": 1049 }
973
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; /// Converts a [data] object into a JS Object of type `T`. T jsifyAs<T>(Map<String, Object?> data) { return data.jsify() as T; }
packages/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jsify_as.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jsify_as.dart", "repo_id": "packages", "token_count": 103 }
974
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:google_identity_services_web/oauth2.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:http/http.dart' as http; /// Basic scopes for self-id const List<String> scopes = <String>[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', ]; /// People API to return my profile info... const String MY_PROFILE = 'https://content-people.googleapis.com/v1/people/me' '?sources=READ_SOURCE_TYPE_PROFILE' '&personFields=photos%2Cnames%2CemailAddresses'; /// Requests user data from the People API using the given [tokenResponse]. Future<GoogleSignInUserData?> requestUserData( TokenResponse tokenResponse, { @visibleForTesting http.Client? overrideClient, }) async { // Request my profile from the People API. final Map<String, Object?> person = await _doRequest( MY_PROFILE, tokenResponse, overrideClient: overrideClient, ); // Now transform the Person response into a GoogleSignInUserData. return extractUserData(person); } /// Extracts user data from a Person resource. /// /// See: https://developers.google.com/people/api/rest/v1/people#Person GoogleSignInUserData? extractUserData(Map<String, Object?> json) { final String? userId = _extractUserId(json); final String? email = _extractPrimaryField( json['emailAddresses'] as List<Object?>?, 'value', ); assert(userId != null); assert(email != null); return GoogleSignInUserData( id: userId!, email: email!, displayName: _extractPrimaryField( json['names'] as List<Object?>?, 'displayName', ), photoUrl: _extractPrimaryField( json['photos'] as List<Object?>?, 'url', ), // Synthetic user data doesn't contain an idToken! ); } /// Extracts the ID from a Person resource. /// /// The User ID looks like this: /// { /// 'resourceName': 'people/PERSON_ID', /// ... /// } String? _extractUserId(Map<String, Object?> profile) { final String? resourceName = profile['resourceName'] as String?; return resourceName?.split('/').last; } /// Extracts the [fieldName] marked as 'primary' from a list of [values]. /// /// Values can be one of: /// * `emailAddresses` /// * `names` /// * `photos` /// /// From a Person object. T? _extractPrimaryField<T>(List<Object?>? values, String fieldName) { if (values != null) { for (final Object? value in values) { if (value != null && value is Map<String, Object?>) { final bool isPrimary = _extractPath( value, path: <String>['metadata', 'primary'], defaultValue: false, ); if (isPrimary) { return value[fieldName] as T?; } } } } return null; } /// Attempts to get the property in [path] of type `T` from a deeply nested [source]. /// /// Returns [default] if the property is not found. T _extractPath<T>( Map<String, Object?> source, { required List<String> path, required T defaultValue, }) { final String valueKey = path.removeLast(); Object? data = source; for (final String key in path) { if (data != null && data is Map) { data = data[key]; } else { break; } } if (data != null && data is Map) { return (data[valueKey] ?? defaultValue) as T; } else { return defaultValue; } } /// Gets from [url] with an authorization header defined by [token]. /// /// Attempts to [jsonDecode] the result. Future<Map<String, Object?>> _doRequest( String url, TokenResponse token, { http.Client? overrideClient, }) async { final Uri uri = Uri.parse(url); final http.Client client = overrideClient ?? http.Client(); try { final http.Response response = await client.get(uri, headers: <String, String>{ 'Authorization': '${token.token_type} ${token.access_token}', }); if (response.statusCode != 200) { throw http.ClientException(response.body, uri); } return jsonDecode(response.body) as Map<String, Object?>; } finally { client.close(); } }
packages/packages/google_sign_in/google_sign_in_web/lib/src/people.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/lib/src/people.dart", "repo_id": "packages", "token_count": 1509 }
975
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/image_picker/image_picker/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/image_picker/image_picker/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
976
name: image_picker description: Flutter plugin for selecting images from the Android and iOS image library, and taking new pictures with the camera. repository: https://github.com/flutter/packages/tree/main/packages/image_picker/image_picker issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22 version: 1.0.7 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: platforms: android: default_package: image_picker_android ios: default_package: image_picker_ios linux: default_package: image_picker_linux macos: default_package: image_picker_macos web: default_package: image_picker_for_web windows: default_package: image_picker_windows dependencies: flutter: sdk: flutter image_picker_android: ^0.8.7 image_picker_for_web: ">=2.2.0 <4.0.0" image_picker_ios: ^0.8.8 image_picker_linux: ^0.2.1 image_picker_macos: ^0.2.1 image_picker_platform_interface: ^2.8.0 image_picker_windows: ^0.2.1 dev_dependencies: build_runner: ^2.1.10 cross_file: ^0.3.1+1 # Mockito generates a direct include. flutter_test: sdk: flutter mockito: 5.4.4 plugin_platform_interface: ^2.1.7 topics: - camera - image-picker - files - file-selection
packages/packages/image_picker/image_picker/pubspec.yaml/0
{ "file_path": "packages/packages/image_picker/image_picker/pubspec.yaml", "repo_id": "packages", "token_count": 574 }
977
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', dartTestOut: 'test/test_api.g.dart', javaOut: 'android/src/main/java/io/flutter/plugins/imagepicker/Messages.java', javaOptions: JavaOptions( package: 'io.flutter.plugins.imagepicker', ), copyrightHeader: 'pigeons/copyright.txt', )) class GeneralOptions { GeneralOptions(this.allowMultiple, this.usePhotoPicker); bool allowMultiple; bool usePhotoPicker; } /// Options for image selection and output. class ImageSelectionOptions { ImageSelectionOptions({this.maxWidth, this.maxHeight, required this.quality}); /// If set, the max width that the image should be resized to fit in. double? maxWidth; /// If set, the max height that the image should be resized to fit in. double? maxHeight; /// The quality of the output image, from 0-100. /// /// 100 indicates original quality. int quality; } class MediaSelectionOptions { MediaSelectionOptions({ required this.imageSelectionOptions, }); ImageSelectionOptions imageSelectionOptions; } /// Options for image selection and output. class VideoSelectionOptions { VideoSelectionOptions({this.maxDurationSeconds}); /// The maximum desired length for the video, in seconds. int? maxDurationSeconds; } // Corresponds to `CameraDevice` from the platform interface package. enum SourceCamera { rear, front } // Corresponds to `ImageSource` from the platform interface package. enum SourceType { camera, gallery } /// Specification for the source of an image or video selection. class SourceSpecification { SourceSpecification(this.type, this.camera); SourceType type; SourceCamera? camera; } /// An error that occurred during lost result retrieval. /// /// The data here maps to the `PlatformException` that will be created from it. class CacheRetrievalError { CacheRetrievalError({required this.code, this.message}); final String code; final String? message; } // Corresponds to `RetrieveType` from the platform interface package. enum CacheRetrievalType { image, video } /// The result of retrieving cached results from a previous run. class CacheRetrievalResult { CacheRetrievalResult( {required this.type, this.error, this.paths = const <String>[]}); /// The type of the retrieved data. final CacheRetrievalType type; /// The error from the last selection, if any. final CacheRetrievalError? error; /// The results from the last selection, if any. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 final List<String?> paths; } @HostApi(dartHostTestHandler: 'TestHostImagePickerApi') abstract class ImagePickerApi { /// Selects images and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 @TaskQueue(type: TaskQueueType.serialBackgroundThread) @async List<String?> pickImages( SourceSpecification source, ImageSelectionOptions options, GeneralOptions generalOptions, ); /// Selects video and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 @TaskQueue(type: TaskQueueType.serialBackgroundThread) @async List<String?> pickVideos( SourceSpecification source, VideoSelectionOptions options, GeneralOptions generalOptions, ); /// Selects images and videos and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 @async List<String?> pickMedia( MediaSelectionOptions mediaSelectionOptions, GeneralOptions generalOptions, ); /// Returns results from a previous app session, if any. @TaskQueue(type: TaskQueueType.serialBackgroundThread) CacheRetrievalResult? retrieveLostResults(); }
packages/packages/image_picker/image_picker_android/pigeons/messages.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_android/pigeons/messages.dart", "repo_id": "packages", "token_count": 1191 }
978
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:js_interop'; import 'dart:math'; import 'dart:ui'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'package:web/helpers.dart'; import 'package:web/web.dart' as web; import 'image_resizer_utils.dart'; /// Helper class that resizes images. class ImageResizer { /// Resizes the image if needed. /// /// (Does not support gif images) Future<XFile> resizeImageIfNeeded( XFile file, double? maxWidth, double? maxHeight, int? imageQuality, ) async { if (!imageResizeNeeded(maxWidth, maxHeight, imageQuality) || file.mimeType == 'image/gif') { // Implement maxWidth and maxHeight for image/gif return file; } try { final web.HTMLImageElement imageElement = await loadImage(file.path); final web.HTMLCanvasElement canvas = resizeImageElement(imageElement, maxWidth, maxHeight); final XFile resizedImage = await writeCanvasToFile(file, canvas, imageQuality); web.URL.revokeObjectURL(file.path); return resizedImage; } catch (e) { return file; } } /// Loads the `blobUrl` into a [web.HTMLImageElement]. Future<web.HTMLImageElement> loadImage(String blobUrl) { final Completer<web.HTMLImageElement> imageLoadCompleter = Completer<web.HTMLImageElement>(); final web.HTMLImageElement imageElement = web.HTMLImageElement(); imageElement // ignore: unsafe_html ..src = blobUrl ..onLoad.listen((web.Event event) { imageLoadCompleter.complete(imageElement); }) ..onError.listen((web.Event event) { const String exception = 'Error while loading image.'; imageElement.remove(); imageLoadCompleter.completeError(exception); }); return imageLoadCompleter.future; } /// Resizing the image in a canvas to fit the [maxWidth], [maxHeight] constraints. web.HTMLCanvasElement resizeImageElement( web.HTMLImageElement source, double? maxWidth, double? maxHeight, ) { final Size newImageSize = calculateSizeOfDownScaledImage( Size(source.width.toDouble(), source.height.toDouble()), maxWidth, maxHeight); final web.HTMLCanvasElement canvas = web.HTMLCanvasElement() ..width = newImageSize.width.toInt() ..height = newImageSize.height.toInt(); final web.CanvasRenderingContext2D context = canvas.context2D; if (maxHeight == null && maxWidth == null) { context.drawImage(source, 0, 0); } else { context.drawImageScaled( source, 0, 0, canvas.width.toDouble(), canvas.height.toDouble()); } return canvas; } /// Converts a canvas element to [XFile]. /// /// [imageQuality] is only supported for jpeg and webp images. Future<XFile> writeCanvasToFile( XFile originalFile, web.HTMLCanvasElement canvas, int? imageQuality, ) async { final double calculatedImageQuality = (min(imageQuality ?? 100, 100)) / 100.0; final Completer<XFile> completer = Completer<XFile>(); final web.BlobCallback blobCallback = (web.Blob blob) { completer.complete(XFile(web.URL.createObjectURL(blob), mimeType: originalFile.mimeType, name: 'scaled_${originalFile.name}', lastModified: DateTime.now(), length: blob.size)); }.toJS; canvas.toBlob( blobCallback, originalFile.mimeType ?? '', calculatedImageQuality.toJS); return completer.future; } }
packages/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart", "repo_id": "packages", "token_count": 1384 }
979
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "ImagePickerTestImages.h" @implementation ImagePickerTestImages + (NSData *)JPGTestData { NSBundle *bundle = [NSBundle bundleForClass:self]; NSURL *url = [bundle URLForResource:@"jpgImage" withExtension:@"jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; if (!data.length) { // When the tests are run outside the example project (podspec lint) the image may not be // embedded in the test bundle. Fall back to the base64 string representation of the jpg. data = [[NSData alloc] initWithBase64EncodedString: @"/9j/4AAQSkZJRgABAQAASABIAAD/" @"4QCMRXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABA" @"AIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAAAygAw" @"AEAAAAAQAAAAcAAAAA/8AAEQgABwAMAwERAAIRAQMRAf/" @"EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//" @"EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBka" @"JSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio" @"6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/" @"EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//" @"EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEX" @"GBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZm" @"qKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/" @"bAEMAAgICAgICAwICAwUDAwMFBgUFBQUGCAYGBgYGCAoICAgICAgKCgoKCgoKCgwMDAwMDA4ODg4ODw8PDw8P" @"Dw8PD//" @"bAEMBAgMDBAQEBwQEBxALCQsQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" @"EBAQEP/dAAQAAv/aAAwDAQACEQMRAD8A9S8ZfsFeG/sH/IUboe7V/JHgR4t4v+2/4XVdj908aPHLG/2P/" @"B6PsfO5/YL8O7m/4mjdT3av966fi1ivZw/ddF2P8VZ+OeN9pP8Ac9X2P//Z" options:0]; } return data; } + (NSData *)JPGTallTestData { NSBundle *bundle = [NSBundle bundleForClass:self]; NSURL *url = [bundle URLForResource:@"jpgImageTall" withExtension:@"jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; if (!data.length) { // When the tests are run outside the example project (podspec lint) the image may not be // embedded in the test bundle. Fall back to the base64 string representation of the jpg. data = [[NSData alloc] initWithBase64EncodedString: @"/9j/4AAQSkZJRgABAQAAAAAAAAD/" @"2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQE" @"w8QEBD/" @"2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE" @"BAQEBD/wAARCAAHAAQDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAABP/" @"EAB0QAAECBwAAAAAAAAAAAAAAAAIABgQIFiVBQlH/xAAUAQEAAAAAAAAAAAAAAAAAAAAH/" @"8QAHBEAAQQDAQAAAAAAAAAAAAAABAAHI1EIFlIX/9oADAMBAAIRAxEAPwA76kLbdSxV/" @"PGxcTHjm7hXngUfVWgp+n0N3suLmqX/2Q==" options:0]; } return data; } + (NSData *)PNGTestData { NSBundle *bundle = [NSBundle bundleForClass:self]; NSURL *url = [bundle URLForResource:@"pngImage" withExtension:@"png"]; NSData *data = [NSData dataWithContentsOfURL:url]; if (!data.length) { // When the tests are run outside the example project (podspec lint) the image may not be // embedded in the test bundle. Fall back to the base64 string representation of the png. data = [[NSData alloc] initWithBase64EncodedString: @"iVBORw0KGgoAAAANSUhEUgAAAAwAAAAHEAIAAADjQOcwAAAABGdBTUEAALGPC/" @"xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAhGVYSWZNTQAqAAAACAA" @"FARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAA" @"AAAAAEgAAAABAAAASAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAADKADAAQAAAABAAAABwAAAACX5qZPA" @"AAACXBIWXMAAAsTAAALEwEAmpwYAAACx2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bW" @"xuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWx" @"uczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRm" @"OkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvY" @"mUuY29tL3RpZmYvMS4wLyIKICAgICAgICAgICAgeG1sbnM6ZXhpZj0iaHR0cDovL25zLmFkb2JlLmNvbS9leG" @"lmLzEuMC8iPgogICAgICAgICA8dGlmZjpZUmVzb2x1dGlvbj43MjwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICA" @"gICAgPHRpZmY6UmVzb2x1dGlvblVuaXQ+" @"MjwvdGlmZjpSZXNvbHV0aW9uVW5pdD4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+" @"NzI8L3RpZmY6WFJlc29sdXRpb24+" @"CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+" @"CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4xMjwvZXhpZjpQaXhlbFhEaW1lbnNpb24+" @"CiAgICAgICAgIDxleGlmOkNvbG9yU3BhY2U+" @"MTwvZXhpZjpDb2xvclNwYWNlPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+" @"NzwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+" @"CjwveDp4bXBtZXRhPgqm8GvmAAAAUElEQVQYGWP4/58BCJDJV6sYGERD9wPFHRimhjIwZK3KAopMDXUAqtv/" @"XxQoAlKBquf/fyaQEDUACwOD2W0qGeSlSiWDPFWoZBB1vEa1wAYAWgsa+7/A1uQAAAAASUVORK5CYII=" options:0]; } return data; } + (NSData *)GIFTestData { NSBundle *bundle = [NSBundle bundleForClass:self]; NSURL *url = [bundle URLForResource:@"gifImage" withExtension:@"gif"]; NSData *data = [NSData dataWithContentsOfURL:url]; if (!data.length) { // When the tests are run outside the example project (podspec lint) the image may not be // embedded in the test bundle. Fall back to the base64 string representation of the gif. data = [[NSData alloc] initWithBase64EncodedString: @"R0lGODlhDAAHAPAAAOpCNQAAACH5BABkAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAADAAHAAACCISP" "qcvtD1UBACH5BABkAAAALAAAAAAMAAcAhuc/JPA/K+49Ne4+PvA7MrhYHoB+A4N9BYh+BYZ+E4xyG496HZJ" "8F5J4GaRtE6tsH7tWIr9SK7xVKJl3IKpvI7lrKc1FLc5PLNJILsdTJMFVJsZWJshWIM9XIshWJNBWLd1SK9" "BUMNFRNOlAI+9CMuNJMetHPnuCAF66F1u8FVu7GV27HGytG3utGH6rHGK1G3WxFWeuIHqlIG60IGi4JTnTDz" "jZDy/VEy/eFTnVEDzXFxflABfjBRPmBRbnBxPrABvpARntAxLuCBXuCQTyAAb1BgvwACnmDSPpDSLjECPpED" "HhFFDLGIeAFoiBFoqCF4uCHYWnHJGVJqSNJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAdWgAIXCjE3PTtAPDUuByQfCzQ4Qj9BPjktBgAcC" "StJRURGQzYwJyMdDDM6SkhHS0xRCAEgD1IsKikoLzJTDgQlEBQNT05NUBMVBQMmGCEZHhsaEhEiFoEAIfkEAG" "QAAAAsAAAAAAwABwCFB+8ACewACu0ACe4ACO8AC+4ACu8ADOwAD+wAEOYAEekAA/EABfAAB/IAAfUAA/UAAP" "cAAfcAAvYAA/cBBPQABfUABvQAB/UBBvYBCfAACPEAC/AACvIACvMBAPgAAPkAAPgBAPkBAvgBAPoAAPoBA" "PsBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAABkfAAadjeUxEEYnk8QBoLhUHCASJJCWLyiTiIZFG3lAoO4F4SiUwScywYCQQ8" "ScEEokCG06D8pA4mBUWCQoIBwIGGQQGBgUFQQA7" options:0]; } return data; } @end
packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImagePickerTestImages.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImagePickerTestImages.m", "repo_id": "packages", "token_count": 4458 }
980
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. export 'camera_delegate.dart'; export 'camera_device.dart'; export 'image_options.dart'; export 'image_source.dart'; export 'lost_data_response.dart'; export 'media_options.dart'; export 'media_selection_type.dart'; export 'multi_image_picker_options.dart'; export 'picked_file/picked_file.dart'; export 'retrieve_type.dart'; /// Denotes that an image is being picked. const String kTypeImage = 'image'; /// Denotes that a video is being picked. const String kTypeVideo = 'video'; /// Denotes that either a video or image is being picked. const String kTypeMedia = 'media';
packages/packages/image_picker/image_picker_platform_interface/lib/src/types/types.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/types.dart", "repo_id": "packages", "token_count": 226 }
981
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'package:image_picker_windows/image_picker_windows.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'image_picker_windows_test.mocks.dart'; @GenerateMocks(<Type>[FileSelectorPlatform]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Returns the captured type groups from a mock call result, assuming that // exactly one call was made and only the type groups were captured. List<XTypeGroup> capturedTypeGroups(VerificationResult result) { return result.captured.single as List<XTypeGroup>; } group('ImagePickerWindows', () { late ImagePickerWindows plugin; late MockFileSelectorPlatform mockFileSelectorPlatform; setUp(() { plugin = ImagePickerWindows(); mockFileSelectorPlatform = MockFileSelectorPlatform(); when(mockFileSelectorPlatform.openFile( acceptedTypeGroups: anyNamed('acceptedTypeGroups'))) .thenAnswer((_) async => null); when(mockFileSelectorPlatform.openFiles( acceptedTypeGroups: anyNamed('acceptedTypeGroups'))) .thenAnswer((_) async => List<XFile>.empty()); ImagePickerWindows.fileSelector = mockFileSelectorPlatform; }); test('registered instance', () { ImagePickerWindows.registerWith(); expect(ImagePickerPlatform.instance, isA<ImagePickerWindows>()); }); group('images', () { test('pickImage passes the accepted type groups correctly', () async { await plugin.pickImage(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); test('getImage passes the accepted type groups correctly', () async { await plugin.getImage(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); test('getMultiImage passes the accepted type groups correctly', () async { await plugin.getMultiImage(); final VerificationResult result = verify( mockFileSelectorPlatform.openFiles( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); test( 'getImageFromSource throws StateError when source is camera with no delegate', () async { await expectLater(plugin.getImageFromSource(source: ImageSource.camera), throwsStateError); }); test('getMultiImage passes the accepted type groups correctly', () async { await plugin.getMultiImage(); final VerificationResult result = verify( mockFileSelectorPlatform.openFiles( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); }); group('videos', () { test('pickVideo passes the accepted type groups correctly', () async { await plugin.pickVideo(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.videoFormats); }); test('getVideo passes the accepted type groups correctly', () async { await plugin.getVideo(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.videoFormats); }); test('getVideo calls delegate when source is camera', () async { const String fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); expect((await plugin.getVideo(source: ImageSource.camera))!.path, fakePath); }); test('getVideo throws StateError when source is camera with no delegate', () async { await expectLater( plugin.getVideo(source: ImageSource.camera), throwsStateError); }); }); group('media', () { test('getMedia passes the accepted type groups correctly', () async { await plugin.getMedia(options: const MediaOptions(allowMultiple: true)); final VerificationResult result = verify( mockFileSelectorPlatform.openFiles( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, <String>[ ...ImagePickerWindows.imageFormats, ...ImagePickerWindows.videoFormats ]); }); test('multiple media handles an empty path response gracefully', () async { expect( await plugin.getMedia( options: const MediaOptions( allowMultiple: true, ), ), <String>[]); }); test('single media handles an empty path response gracefully', () async { expect( await plugin.getMedia( options: const MediaOptions( allowMultiple: false, ), ), <String>[]); }); }); }); } class FakeCameraDelegate extends ImagePickerCameraDelegate { FakeCameraDelegate({this.result}); XFile? result; @override Future<XFile?> takePhoto( {ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions()}) async { return result; } @override Future<XFile?> takeVideo( {ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions()}) async { return result; } }
packages/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart", "repo_id": "packages", "token_count": 2556 }
982
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.inapppurchase"> </manifest>
packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 47 }
983
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'billing_config_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** BillingConfigWrapper _$BillingConfigWrapperFromJson(Map json) => BillingConfigWrapper( responseCode: const BillingResponseConverter() .fromJson(json['responseCode'] as int?), debugMessage: json['debugMessage'] as String? ?? '', countryCode: json['countryCode'] as String? ?? '', );
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.g.dart", "repo_id": "packages", "token_count": 168 }
984
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import '../billing_client_wrappers.dart'; import '../in_app_purchase_android.dart'; /// [IAPError.code] code for failed purchases. const String kPurchaseErrorCode = 'purchase_error'; /// [IAPError.code] code used when a consuming a purchased item fails. const String kConsumptionFailedErrorCode = 'consume_purchase_failed'; /// [IAPError.code] code used when a query for previous transaction has failed. const String kRestoredPurchaseErrorCode = 'restore_transactions_failed'; /// Indicates store front is Google Play const String kIAPSource = 'google_play'; /// An [InAppPurchasePlatform] that wraps Android BillingClient. /// /// This translates various `BillingClient` calls and responses into the /// generic plugin API. class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { InAppPurchaseAndroidPlatform._() { // Register [InAppPurchaseAndroidPlatformAddition]. InAppPurchasePlatformAddition.instance = InAppPurchaseAndroidPlatformAddition(billingClientManager); billingClientManager.purchasesUpdatedStream .asyncMap(_getPurchaseDetailsFromResult) .listen(_purchaseUpdatedController.add); } /// Registers this class as the default instance of [InAppPurchasePlatform]. static void registerPlatform() { // Register the platform instance with the plugin platform // interface. InAppPurchasePlatform.instance = InAppPurchaseAndroidPlatform._(); } final StreamController<List<PurchaseDetails>> _purchaseUpdatedController = StreamController<List<PurchaseDetails>>.broadcast(); @override late final Stream<List<PurchaseDetails>> purchaseStream = _purchaseUpdatedController.stream; /// The [BillingClient] that's abstracted by [GooglePlayConnection]. /// /// This field should not be used out of test code. @visibleForTesting final BillingClientManager billingClientManager = BillingClientManager(); static final Set<String> _productIdsToConsume = <String>{}; @override Future<bool> isAvailable() async { return billingClientManager .runWithClientNonRetryable((BillingClient client) => client.isReady()); } /// Performs a network query for the details of products available. @override Future<ProductDetailsResponse> queryProductDetails( Set<String> identifiers, ) async { List<ProductDetailsResponseWrapper>? productResponses; PlatformException? exception; try { productResponses = await Future.wait( <Future<ProductDetailsResponseWrapper>>[ billingClientManager.runWithClient( (BillingClient client) => client.queryProductDetails( productList: identifiers .map((String productId) => ProductWrapper( productId: productId, productType: ProductType.inapp)) .toList(), ), ), billingClientManager.runWithClient( (BillingClient client) => client.queryProductDetails( productList: identifiers .map((String productId) => ProductWrapper( productId: productId, productType: ProductType.subs)) .toList(), ), ), ], ); } on PlatformException catch (e) { exception = e; productResponses = <ProductDetailsResponseWrapper>[ ProductDetailsResponseWrapper( billingResult: BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: e.code), productDetailsList: const <ProductDetailsWrapper>[]), ProductDetailsResponseWrapper( billingResult: BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: e.code), productDetailsList: const <ProductDetailsWrapper>[]) ]; } final List<ProductDetails> productDetailsList = productResponses.expand((ProductDetailsResponseWrapper response) { return response.productDetailsList; }).expand((ProductDetailsWrapper productDetailWrapper) { return GooglePlayProductDetails.fromProductDetails(productDetailWrapper); }).toList(); final Set<String> successIDS = productDetailsList .map((ProductDetails productDetails) => productDetails.id) .toSet(); final List<String> notFoundIDS = identifiers.difference(successIDS).toList(); return ProductDetailsResponse( productDetails: productDetailsList, notFoundIDs: notFoundIDS, error: exception == null ? null : IAPError( source: kIAPSource, code: exception.code, message: exception.message ?? '', details: exception.details)); } @override Future<bool> buyNonConsumable({required PurchaseParam purchaseParam}) async { ChangeSubscriptionParam? changeSubscriptionParam; if (purchaseParam is GooglePlayPurchaseParam) { changeSubscriptionParam = purchaseParam.changeSubscriptionParam; } String? offerToken; if (purchaseParam.productDetails is GooglePlayProductDetails) { offerToken = (purchaseParam.productDetails as GooglePlayProductDetails).offerToken; } final BillingResultWrapper billingResultWrapper = await billingClientManager.runWithClient( (BillingClient client) => client.launchBillingFlow( product: purchaseParam.productDetails.id, offerToken: offerToken, accountId: purchaseParam.applicationUserName, oldProduct: changeSubscriptionParam?.oldPurchaseDetails.productID, purchaseToken: changeSubscriptionParam ?.oldPurchaseDetails.verificationData.serverVerificationData, prorationMode: changeSubscriptionParam?.prorationMode), ); return billingResultWrapper.responseCode == BillingResponse.ok; } @override Future<bool> buyConsumable( {required PurchaseParam purchaseParam, bool autoConsume = true}) { if (autoConsume) { _productIdsToConsume.add(purchaseParam.productDetails.id); } return buyNonConsumable(purchaseParam: purchaseParam); } @override Future<BillingResultWrapper> completePurchase( PurchaseDetails purchase) async { assert( purchase is GooglePlayPurchaseDetails, 'On Android, the `purchase` should always be of type `GooglePlayPurchaseDetails`.', ); final GooglePlayPurchaseDetails googlePurchase = purchase as GooglePlayPurchaseDetails; if (googlePurchase.billingClientPurchase.isAcknowledged) { return const BillingResultWrapper(responseCode: BillingResponse.ok); } return billingClientManager.runWithClient( (BillingClient client) => client.acknowledgePurchase( purchase.verificationData.serverVerificationData), ); } @override Future<void> restorePurchases({ String? applicationUserName, }) async { List<PurchasesResultWrapper> responses; responses = await Future.wait(<Future<PurchasesResultWrapper>>[ billingClientManager.runWithClient( (BillingClient client) => client.queryPurchases(ProductType.inapp), ), billingClientManager.runWithClient( (BillingClient client) => client.queryPurchases(ProductType.subs), ), ]); final Set<String> errorCodeSet = responses .where((PurchasesResultWrapper response) => response.responseCode != BillingResponse.ok) .map((PurchasesResultWrapper response) => response.responseCode.toString()) .toSet(); final String errorMessage = errorCodeSet.isNotEmpty ? errorCodeSet.join(', ') : ''; final List<PurchaseDetails> pastPurchases = responses .expand((PurchasesResultWrapper response) => response.purchasesList) .expand((PurchaseWrapper purchaseWrapper) => GooglePlayPurchaseDetails.fromPurchase(purchaseWrapper)) .map((GooglePlayPurchaseDetails details) => details..status = PurchaseStatus.restored) .toList(); if (errorMessage.isNotEmpty) { throw InAppPurchaseException( source: kIAPSource, code: kRestoredPurchaseErrorCode, message: errorMessage, ); } _purchaseUpdatedController.add(pastPurchases); } Future<PurchaseDetails> _maybeAutoConsumePurchase( PurchaseDetails purchaseDetails) async { if (!(purchaseDetails.status == PurchaseStatus.purchased && _productIdsToConsume.contains(purchaseDetails.productID))) { return purchaseDetails; } final BillingResultWrapper billingResult = await (InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition) .consumePurchase(purchaseDetails); final BillingResponse consumedResponse = billingResult.responseCode; if (consumedResponse != BillingResponse.ok) { purchaseDetails.status = PurchaseStatus.error; purchaseDetails.error = IAPError( source: kIAPSource, code: kConsumptionFailedErrorCode, message: consumedResponse.toString(), details: billingResult.debugMessage, ); } _productIdsToConsume.remove(purchaseDetails.productID); return purchaseDetails; } Future<List<PurchaseDetails>> _getPurchaseDetailsFromResult( PurchasesResultWrapper resultWrapper) async { IAPError? error; if (resultWrapper.responseCode != BillingResponse.ok) { error = IAPError( source: kIAPSource, code: kPurchaseErrorCode, message: resultWrapper.responseCode.toString(), details: resultWrapper.billingResult.debugMessage, ); } final List<Future<PurchaseDetails>> purchases = resultWrapper.purchasesList .expand((PurchaseWrapper purchase) => GooglePlayPurchaseDetails.fromPurchase(purchase)) .map((GooglePlayPurchaseDetails purchaseDetails) { purchaseDetails.error = error; if (resultWrapper.responseCode == BillingResponse.userCanceled) { purchaseDetails.status = PurchaseStatus.canceled; } return _maybeAutoConsumePurchase(purchaseDetails); }).toList(); if (purchases.isNotEmpty) { return Future.wait(purchases); } else { PurchaseStatus status = PurchaseStatus.error; if (resultWrapper.responseCode == BillingResponse.userCanceled) { status = PurchaseStatus.canceled; } else if (resultWrapper.responseCode == BillingResponse.ok) { status = PurchaseStatus.purchased; } return <PurchaseDetails>[ PurchaseDetails( purchaseID: '', productID: '', status: status, transactionDate: null, verificationData: PurchaseVerificationData( localVerificationData: '', serverVerificationData: '', source: kIAPSource, ), )..error = error ]; } } }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart", "repo_id": "packages", "token_count": 4052 }
985
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package: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', products: <String>['product'], purchaseToken: 'purchaseToken', isAutoRenewing: false, originalJson: '', developerPayload: 'dummy payload', isAcknowledged: true, purchaseState: PurchaseStateWrapper.purchased, obfuscatedAccountId: 'Account101', obfuscatedProfileId: 'Profile103', ); const PurchaseWrapper dummyMultipleProductsPurchase = PurchaseWrapper( orderId: 'orderId', packageName: 'packageName', purchaseTime: 0, signature: 'signature', products: <String>['product', 'product2'], purchaseToken: 'purchaseToken', isAutoRenewing: false, originalJson: '', developerPayload: 'dummy payload', isAcknowledged: true, purchaseState: PurchaseStateWrapper.purchased, ); const PurchaseWrapper dummyUnacknowledgedPurchase = PurchaseWrapper( orderId: 'orderId', packageName: 'packageName', purchaseTime: 0, signature: 'signature', products: <String>['product'], purchaseToken: 'purchaseToken', isAutoRenewing: false, originalJson: '', developerPayload: 'dummy payload', isAcknowledged: false, purchaseState: PurchaseStateWrapper.purchased, ); const PurchaseHistoryRecordWrapper dummyPurchaseHistoryRecord = PurchaseHistoryRecordWrapper( purchaseTime: 0, signature: 'signature', products: <String>['product'], purchaseToken: 'purchaseToken', originalJson: '', developerPayload: 'dummy payload', ); 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 List<GooglePlayPurchaseDetails> details = GooglePlayPurchaseDetails.fromPurchase(dummyMultipleProductsPurchase); expect(details[0].purchaseID, dummyMultipleProductsPurchase.orderId); expect(details[0].productID, dummyMultipleProductsPurchase.products[0]); expect(details[0].transactionDate, dummyMultipleProductsPurchase.purchaseTime.toString()); expect(details[0].verificationData, isNotNull); expect(details[0].verificationData.source, kIAPSource); expect(details[0].verificationData.localVerificationData, dummyMultipleProductsPurchase.originalJson); expect(details[0].verificationData.serverVerificationData, dummyMultipleProductsPurchase.purchaseToken); expect(details[0].billingClientPurchase, dummyMultipleProductsPurchase); expect(details[0].pendingCompletePurchase, false); expect(details[1].purchaseID, dummyMultipleProductsPurchase.orderId); expect(details[1].productID, dummyMultipleProductsPurchase.products[1]); expect(details[1].transactionDate, dummyMultipleProductsPurchase.purchaseTime.toString()); expect(details[1].verificationData, isNotNull); expect(details[1].verificationData.source, kIAPSource); expect(details[1].verificationData.localVerificationData, dummyMultipleProductsPurchase.originalJson); expect(details[1].verificationData.serverVerificationData, dummyMultipleProductsPurchase.purchaseToken); expect(details[1].billingClientPurchase, dummyMultipleProductsPurchase); expect(details[1].pendingCompletePurchase, false); }); test( 'fromPurchase() should return set pendingCompletePurchase to true for unacknowledged purchase', () { final GooglePlayPurchaseDetails details = GooglePlayPurchaseDetails.fromPurchase(dummyUnacknowledgedPurchase) .first; expect(details.purchaseID, dummyPurchase.orderId); expect(details.productID, dummyPurchase.products.first); 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, 'products': original.products, '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, 'products': original.products, '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, }; }
packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart", "repo_id": "packages", "token_count": 3417 }
986
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v16.0.4), do not edit directly. // See also: https://pub.dev/packages/pigeon #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSUInteger, SKPaymentTransactionStateMessage) { /// Indicates the transaction is being processed in App Store. /// /// You should update your UI to indicate that you are waiting for the /// transaction to update to another state. Never complete a transaction that /// is still in a purchasing state. SKPaymentTransactionStateMessagePurchasing = 0, /// The user's payment has been succesfully processed. /// /// You should provide the user the content that they purchased. SKPaymentTransactionStateMessagePurchased = 1, /// The transaction failed. /// /// Check the [PaymentTransactionWrapper.error] property from /// [PaymentTransactionWrapper] for details. SKPaymentTransactionStateMessageFailed = 2, /// This transaction is restoring content previously purchased by the user. /// /// The previous transaction information can be obtained in /// [PaymentTransactionWrapper.originalTransaction] from /// [PaymentTransactionWrapper]. SKPaymentTransactionStateMessageRestored = 3, /// The transaction is in the queue but pending external action. Wait for /// another callback to get the final state. /// /// You should update your UI to indicate that you are waiting for the /// transaction to update to another state. SKPaymentTransactionStateMessageDeferred = 4, /// Indicates the transaction is in an unspecified state. SKPaymentTransactionStateMessageUnspecified = 5, }; /// Wrapper for SKPaymentTransactionStateMessage to allow for nullability. @interface SKPaymentTransactionStateMessageBox : NSObject @property(nonatomic, assign) SKPaymentTransactionStateMessage value; - (instancetype)initWithValue:(SKPaymentTransactionStateMessage)value; @end typedef NS_ENUM(NSUInteger, SKProductDiscountTypeMessage) { /// A constant indicating the discount type is an introductory offer. SKProductDiscountTypeMessageIntroductory = 0, /// A constant indicating the discount type is a promotional offer. SKProductDiscountTypeMessageSubscription = 1, }; /// Wrapper for SKProductDiscountTypeMessage to allow for nullability. @interface SKProductDiscountTypeMessageBox : NSObject @property(nonatomic, assign) SKProductDiscountTypeMessage value; - (instancetype)initWithValue:(SKProductDiscountTypeMessage)value; @end typedef NS_ENUM(NSUInteger, SKProductDiscountPaymentModeMessage) { /// Allows user to pay the discounted price at each payment period. SKProductDiscountPaymentModeMessagePayAsYouGo = 0, /// Allows user to pay the discounted price upfront and receive the product for the rest of time /// that was paid for. SKProductDiscountPaymentModeMessagePayUpFront = 1, /// User pays nothing during the discounted period. SKProductDiscountPaymentModeMessageFreeTrial = 2, /// Unspecified mode. SKProductDiscountPaymentModeMessageUnspecified = 3, }; /// Wrapper for SKProductDiscountPaymentModeMessage to allow for nullability. @interface SKProductDiscountPaymentModeMessageBox : NSObject @property(nonatomic, assign) SKProductDiscountPaymentModeMessage value; - (instancetype)initWithValue:(SKProductDiscountPaymentModeMessage)value; @end typedef NS_ENUM(NSUInteger, SKSubscriptionPeriodUnitMessage) { SKSubscriptionPeriodUnitMessageDay = 0, SKSubscriptionPeriodUnitMessageWeek = 1, SKSubscriptionPeriodUnitMessageMonth = 2, SKSubscriptionPeriodUnitMessageYear = 3, }; /// Wrapper for SKSubscriptionPeriodUnitMessage to allow for nullability. @interface SKSubscriptionPeriodUnitMessageBox : NSObject @property(nonatomic, assign) SKSubscriptionPeriodUnitMessage value; - (instancetype)initWithValue:(SKSubscriptionPeriodUnitMessage)value; @end @class SKPaymentTransactionMessage; @class SKPaymentMessage; @class SKErrorMessage; @class SKPaymentDiscountMessage; @class SKStorefrontMessage; @class SKProductsResponseMessage; @class SKProductMessage; @class SKPriceLocaleMessage; @class SKProductDiscountMessage; @class SKProductSubscriptionPeriodMessage; @interface SKPaymentTransactionMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithPayment:(SKPaymentMessage *)payment transactionState:(SKPaymentTransactionStateMessage)transactionState originalTransaction:(nullable SKPaymentTransactionMessage *)originalTransaction transactionTimeStamp:(nullable NSNumber *)transactionTimeStamp transactionIdentifier:(nullable NSString *)transactionIdentifier error:(nullable SKErrorMessage *)error; @property(nonatomic, strong) SKPaymentMessage *payment; @property(nonatomic, assign) SKPaymentTransactionStateMessage transactionState; @property(nonatomic, strong, nullable) SKPaymentTransactionMessage *originalTransaction; @property(nonatomic, strong, nullable) NSNumber *transactionTimeStamp; @property(nonatomic, copy, nullable) NSString *transactionIdentifier; @property(nonatomic, strong, nullable) SKErrorMessage *error; @end @interface SKPaymentMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithProductIdentifier:(NSString *)productIdentifier applicationUsername:(nullable NSString *)applicationUsername requestData:(nullable NSString *)requestData quantity:(NSInteger)quantity simulatesAskToBuyInSandbox:(BOOL)simulatesAskToBuyInSandbox paymentDiscount:(nullable SKPaymentDiscountMessage *)paymentDiscount; @property(nonatomic, copy) NSString *productIdentifier; @property(nonatomic, copy, nullable) NSString *applicationUsername; @property(nonatomic, copy, nullable) NSString *requestData; @property(nonatomic, assign) NSInteger quantity; @property(nonatomic, assign) BOOL simulatesAskToBuyInSandbox; @property(nonatomic, strong, nullable) SKPaymentDiscountMessage *paymentDiscount; @end @interface SKErrorMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithCode:(NSInteger)code domain:(NSString *)domain userInfo:(nullable NSDictionary<NSString *, id> *)userInfo; @property(nonatomic, assign) NSInteger code; @property(nonatomic, copy) NSString *domain; @property(nonatomic, copy, nullable) NSDictionary<NSString *, id> *userInfo; @end @interface SKPaymentDiscountMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithIdentifier:(NSString *)identifier keyIdentifier:(NSString *)keyIdentifier nonce:(NSString *)nonce signature:(NSString *)signature timestamp:(NSInteger)timestamp; @property(nonatomic, copy) NSString *identifier; @property(nonatomic, copy) NSString *keyIdentifier; @property(nonatomic, copy) NSString *nonce; @property(nonatomic, copy) NSString *signature; @property(nonatomic, assign) NSInteger timestamp; @end @interface SKStorefrontMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithCountryCode:(NSString *)countryCode identifier:(NSString *)identifier; @property(nonatomic, copy) NSString *countryCode; @property(nonatomic, copy) NSString *identifier; @end @interface SKProductsResponseMessage : NSObject + (instancetype)makeWithProducts:(nullable NSArray<SKProductMessage *> *)products invalidProductIdentifiers:(nullable NSArray<NSString *> *)invalidProductIdentifiers; @property(nonatomic, copy, nullable) NSArray<SKProductMessage *> *products; @property(nonatomic, copy, nullable) NSArray<NSString *> *invalidProductIdentifiers; @end @interface SKProductMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithProductIdentifier:(NSString *)productIdentifier localizedTitle:(NSString *)localizedTitle localizedDescription:(NSString *)localizedDescription priceLocale:(SKPriceLocaleMessage *)priceLocale subscriptionGroupIdentifier:(nullable NSString *)subscriptionGroupIdentifier price:(NSString *)price subscriptionPeriod: (nullable SKProductSubscriptionPeriodMessage *)subscriptionPeriod introductoryPrice:(nullable SKProductDiscountMessage *)introductoryPrice discounts:(nullable NSArray<SKProductDiscountMessage *> *)discounts; @property(nonatomic, copy) NSString *productIdentifier; @property(nonatomic, copy) NSString *localizedTitle; @property(nonatomic, copy) NSString *localizedDescription; @property(nonatomic, strong) SKPriceLocaleMessage *priceLocale; @property(nonatomic, copy, nullable) NSString *subscriptionGroupIdentifier; @property(nonatomic, copy) NSString *price; @property(nonatomic, strong, nullable) SKProductSubscriptionPeriodMessage *subscriptionPeriod; @property(nonatomic, strong, nullable) SKProductDiscountMessage *introductoryPrice; @property(nonatomic, copy, nullable) NSArray<SKProductDiscountMessage *> *discounts; @end @interface SKPriceLocaleMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithCurrencySymbol:(NSString *)currencySymbol currencyCode:(NSString *)currencyCode countryCode:(NSString *)countryCode; /// The currency symbol for the locale, e.g. $ for US locale. @property(nonatomic, copy) NSString *currencySymbol; /// The currency code for the locale, e.g. USD for US locale. @property(nonatomic, copy) NSString *currencyCode; /// The country code for the locale, e.g. US for US locale. @property(nonatomic, copy) NSString *countryCode; @end @interface SKProductDiscountMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithPrice:(NSString *)price priceLocale:(SKPriceLocaleMessage *)priceLocale numberOfPeriods:(NSInteger)numberOfPeriods paymentMode:(SKProductDiscountPaymentModeMessage)paymentMode subscriptionPeriod:(SKProductSubscriptionPeriodMessage *)subscriptionPeriod identifier:(nullable NSString *)identifier type:(SKProductDiscountTypeMessage)type; @property(nonatomic, copy) NSString *price; @property(nonatomic, strong) SKPriceLocaleMessage *priceLocale; @property(nonatomic, assign) NSInteger numberOfPeriods; @property(nonatomic, assign) SKProductDiscountPaymentModeMessage paymentMode; @property(nonatomic, strong) SKProductSubscriptionPeriodMessage *subscriptionPeriod; @property(nonatomic, copy, nullable) NSString *identifier; @property(nonatomic, assign) SKProductDiscountTypeMessage type; @end @interface SKProductSubscriptionPeriodMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithNumberOfUnits:(NSInteger)numberOfUnits unit:(SKSubscriptionPeriodUnitMessage)unit; @property(nonatomic, assign) NSInteger numberOfUnits; @property(nonatomic, assign) SKSubscriptionPeriodUnitMessage unit; @end /// The codec used by InAppPurchaseAPI. NSObject<FlutterMessageCodec> *InAppPurchaseAPIGetCodec(void); @protocol InAppPurchaseAPI /// Returns if the current device is able to make payments /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)canMakePaymentsWithError:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSArray<SKPaymentTransactionMessage *> *)transactionsWithError: (FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable SKStorefrontMessage *)storefrontWithError:(FlutterError *_Nullable *_Nonnull)error; - (void)addPaymentPaymentMap:(NSDictionary<NSString *, id> *)paymentMap error:(FlutterError *_Nullable *_Nonnull)error; - (void)startProductRequestProductIdentifiers:(NSArray<NSString *> *)productIdentifiers completion:(void (^)(SKProductsResponseMessage *_Nullable, FlutterError *_Nullable))completion; - (void)finishTransactionFinishMap:(NSDictionary<NSString *, NSString *> *)finishMap error:(FlutterError *_Nullable *_Nonnull)error; - (void)restoreTransactionsApplicationUserName:(nullable NSString *)applicationUserName error:(FlutterError *_Nullable *_Nonnull)error; - (void)presentCodeRedemptionSheetWithError:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)retrieveReceiptDataWithError:(FlutterError *_Nullable *_Nonnull)error; - (void)refreshReceiptReceiptProperties:(nullable NSDictionary<NSString *, id> *)receiptProperties completion:(void (^)(FlutterError *_Nullable))completion; - (void)startObservingPaymentQueueWithError:(FlutterError *_Nullable *_Nonnull)error; - (void)stopObservingPaymentQueueWithError:(FlutterError *_Nullable *_Nonnull)error; - (void)registerPaymentQueueDelegateWithError:(FlutterError *_Nullable *_Nonnull)error; - (void)removePaymentQueueDelegateWithError:(FlutterError *_Nullable *_Nonnull)error; - (void)showPriceConsentIfNeededWithError:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpInAppPurchaseAPI(id<FlutterBinaryMessenger> binaryMessenger, NSObject<InAppPurchaseAPI> *_Nullable api); NS_ASSUME_NONNULL_END
packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/messages.g.h/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/messages.g.h", "repo_id": "packages", "token_count": 4858 }
987
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v16.0.4), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; PlatformException _createConnectionError(String channelName) { return PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel: "$channelName".', ); } List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } enum SKPaymentTransactionStateMessage { /// Indicates the transaction is being processed in App Store. /// /// You should update your UI to indicate that you are waiting for the /// transaction to update to another state. Never complete a transaction that /// is still in a purchasing state. purchasing, /// The user's payment has been succesfully processed. /// /// You should provide the user the content that they purchased. purchased, /// The transaction failed. /// /// Check the [PaymentTransactionWrapper.error] property from /// [PaymentTransactionWrapper] for details. failed, /// This transaction is restoring content previously purchased by the user. /// /// The previous transaction information can be obtained in /// [PaymentTransactionWrapper.originalTransaction] from /// [PaymentTransactionWrapper]. restored, /// The transaction is in the queue but pending external action. Wait for /// another callback to get the final state. /// /// You should update your UI to indicate that you are waiting for the /// transaction to update to another state. deferred, /// Indicates the transaction is in an unspecified state. unspecified, } enum SKProductDiscountTypeMessage { /// A constant indicating the discount type is an introductory offer. introductory, /// A constant indicating the discount type is a promotional offer. subscription, } enum SKProductDiscountPaymentModeMessage { /// Allows user to pay the discounted price at each payment period. payAsYouGo, /// Allows user to pay the discounted price upfront and receive the product for the rest of time that was paid for. payUpFront, /// User pays nothing during the discounted period. freeTrial, /// Unspecified mode. unspecified, } enum SKSubscriptionPeriodUnitMessage { day, week, month, year, } class SKPaymentTransactionMessage { SKPaymentTransactionMessage({ required this.payment, required this.transactionState, this.originalTransaction, this.transactionTimeStamp, this.transactionIdentifier, this.error, }); SKPaymentMessage payment; SKPaymentTransactionStateMessage transactionState; SKPaymentTransactionMessage? originalTransaction; double? transactionTimeStamp; String? transactionIdentifier; SKErrorMessage? error; Object encode() { return <Object?>[ payment.encode(), transactionState.index, originalTransaction?.encode(), transactionTimeStamp, transactionIdentifier, error?.encode(), ]; } static SKPaymentTransactionMessage decode(Object result) { result as List<Object?>; return SKPaymentTransactionMessage( payment: SKPaymentMessage.decode(result[0]! as List<Object?>), transactionState: SKPaymentTransactionStateMessage.values[result[1]! as int], originalTransaction: result[2] != null ? SKPaymentTransactionMessage.decode(result[2]! as List<Object?>) : null, transactionTimeStamp: result[3] as double?, transactionIdentifier: result[4] as String?, error: result[5] != null ? SKErrorMessage.decode(result[5]! as List<Object?>) : null, ); } } class SKPaymentMessage { SKPaymentMessage({ required this.productIdentifier, this.applicationUsername, this.requestData, this.quantity = 1, this.simulatesAskToBuyInSandbox = false, this.paymentDiscount, }); String productIdentifier; String? applicationUsername; String? requestData; int quantity; bool simulatesAskToBuyInSandbox; SKPaymentDiscountMessage? paymentDiscount; Object encode() { return <Object?>[ productIdentifier, applicationUsername, requestData, quantity, simulatesAskToBuyInSandbox, paymentDiscount?.encode(), ]; } static SKPaymentMessage decode(Object result) { result as List<Object?>; return SKPaymentMessage( productIdentifier: result[0]! as String, applicationUsername: result[1] as String?, requestData: result[2] as String?, quantity: result[3]! as int, simulatesAskToBuyInSandbox: result[4]! as bool, paymentDiscount: result[5] != null ? SKPaymentDiscountMessage.decode(result[5]! as List<Object?>) : null, ); } } class SKErrorMessage { SKErrorMessage({ required this.code, required this.domain, this.userInfo, }); int code; String domain; Map<String?, Object?>? userInfo; Object encode() { return <Object?>[ code, domain, userInfo, ]; } static SKErrorMessage decode(Object result) { result as List<Object?>; return SKErrorMessage( code: result[0]! as int, domain: result[1]! as String, userInfo: (result[2] as Map<Object?, Object?>?)?.cast<String?, Object?>(), ); } } class SKPaymentDiscountMessage { SKPaymentDiscountMessage({ required this.identifier, required this.keyIdentifier, required this.nonce, required this.signature, required this.timestamp, }); String identifier; String keyIdentifier; String nonce; String signature; int timestamp; Object encode() { return <Object?>[ identifier, keyIdentifier, nonce, signature, timestamp, ]; } static SKPaymentDiscountMessage decode(Object result) { result as List<Object?>; return SKPaymentDiscountMessage( identifier: result[0]! as String, keyIdentifier: result[1]! as String, nonce: result[2]! as String, signature: result[3]! as String, timestamp: result[4]! as int, ); } } class SKStorefrontMessage { SKStorefrontMessage({ required this.countryCode, required this.identifier, }); String countryCode; String identifier; Object encode() { return <Object?>[ countryCode, identifier, ]; } static SKStorefrontMessage decode(Object result) { result as List<Object?>; return SKStorefrontMessage( countryCode: result[0]! as String, identifier: result[1]! as String, ); } } class SKProductsResponseMessage { SKProductsResponseMessage({ this.products, this.invalidProductIdentifiers, }); List<SKProductMessage?>? products; List<String?>? invalidProductIdentifiers; Object encode() { return <Object?>[ products, invalidProductIdentifiers, ]; } static SKProductsResponseMessage decode(Object result) { result as List<Object?>; return SKProductsResponseMessage( products: (result[0] as List<Object?>?)?.cast<SKProductMessage?>(), invalidProductIdentifiers: (result[1] as List<Object?>?)?.cast<String?>(), ); } } class SKProductMessage { SKProductMessage({ required this.productIdentifier, required this.localizedTitle, required this.localizedDescription, required this.priceLocale, this.subscriptionGroupIdentifier, required this.price, this.subscriptionPeriod, this.introductoryPrice, this.discounts, }); String productIdentifier; String localizedTitle; String localizedDescription; SKPriceLocaleMessage priceLocale; String? subscriptionGroupIdentifier; String price; SKProductSubscriptionPeriodMessage? subscriptionPeriod; SKProductDiscountMessage? introductoryPrice; List<SKProductDiscountMessage?>? discounts; Object encode() { return <Object?>[ productIdentifier, localizedTitle, localizedDescription, priceLocale.encode(), subscriptionGroupIdentifier, price, subscriptionPeriod?.encode(), introductoryPrice?.encode(), discounts, ]; } static SKProductMessage decode(Object result) { result as List<Object?>; return SKProductMessage( productIdentifier: result[0]! as String, localizedTitle: result[1]! as String, localizedDescription: result[2]! as String, priceLocale: SKPriceLocaleMessage.decode(result[3]! as List<Object?>), subscriptionGroupIdentifier: result[4] as String?, price: result[5]! as String, subscriptionPeriod: result[6] != null ? SKProductSubscriptionPeriodMessage.decode( result[6]! as List<Object?>) : null, introductoryPrice: result[7] != null ? SKProductDiscountMessage.decode(result[7]! as List<Object?>) : null, discounts: (result[8] as List<Object?>?)?.cast<SKProductDiscountMessage?>(), ); } } class SKPriceLocaleMessage { SKPriceLocaleMessage({ required this.currencySymbol, required this.currencyCode, required this.countryCode, }); ///The currency symbol for the locale, e.g. $ for US locale. String currencySymbol; ///The currency code for the locale, e.g. USD for US locale. String currencyCode; ///The country code for the locale, e.g. US for US locale. String countryCode; Object encode() { return <Object?>[ currencySymbol, currencyCode, countryCode, ]; } static SKPriceLocaleMessage decode(Object result) { result as List<Object?>; return SKPriceLocaleMessage( currencySymbol: result[0]! as String, currencyCode: result[1]! as String, countryCode: result[2]! as String, ); } } class SKProductDiscountMessage { SKProductDiscountMessage({ required this.price, required this.priceLocale, required this.numberOfPeriods, required this.paymentMode, required this.subscriptionPeriod, this.identifier, required this.type, }); String price; SKPriceLocaleMessage priceLocale; int numberOfPeriods; SKProductDiscountPaymentModeMessage paymentMode; SKProductSubscriptionPeriodMessage subscriptionPeriod; String? identifier; SKProductDiscountTypeMessage type; Object encode() { return <Object?>[ price, priceLocale.encode(), numberOfPeriods, paymentMode.index, subscriptionPeriod.encode(), identifier, type.index, ]; } static SKProductDiscountMessage decode(Object result) { result as List<Object?>; return SKProductDiscountMessage( price: result[0]! as String, priceLocale: SKPriceLocaleMessage.decode(result[1]! as List<Object?>), numberOfPeriods: result[2]! as int, paymentMode: SKProductDiscountPaymentModeMessage.values[result[3]! as int], subscriptionPeriod: SKProductSubscriptionPeriodMessage.decode( result[4]! as List<Object?>), identifier: result[5] as String?, type: SKProductDiscountTypeMessage.values[result[6]! as int], ); } } class SKProductSubscriptionPeriodMessage { SKProductSubscriptionPeriodMessage({ required this.numberOfUnits, required this.unit, }); int numberOfUnits; SKSubscriptionPeriodUnitMessage unit; Object encode() { return <Object?>[ numberOfUnits, unit.index, ]; } static SKProductSubscriptionPeriodMessage decode(Object result) { result as List<Object?>; return SKProductSubscriptionPeriodMessage( numberOfUnits: result[0]! as int, unit: SKSubscriptionPeriodUnitMessage.values[result[1]! as int], ); } } class _InAppPurchaseAPICodec extends StandardMessageCodec { const _InAppPurchaseAPICodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is SKErrorMessage) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is SKPaymentDiscountMessage) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is SKPaymentMessage) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is SKPaymentTransactionMessage) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else if (value is SKPriceLocaleMessage) { buffer.putUint8(132); writeValue(buffer, value.encode()); } else if (value is SKProductDiscountMessage) { buffer.putUint8(133); writeValue(buffer, value.encode()); } else if (value is SKProductMessage) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else if (value is SKProductSubscriptionPeriodMessage) { buffer.putUint8(135); writeValue(buffer, value.encode()); } else if (value is SKProductsResponseMessage) { buffer.putUint8(136); writeValue(buffer, value.encode()); } else if (value is SKStorefrontMessage) { buffer.putUint8(137); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return SKErrorMessage.decode(readValue(buffer)!); case 129: return SKPaymentDiscountMessage.decode(readValue(buffer)!); case 130: return SKPaymentMessage.decode(readValue(buffer)!); case 131: return SKPaymentTransactionMessage.decode(readValue(buffer)!); case 132: return SKPriceLocaleMessage.decode(readValue(buffer)!); case 133: return SKProductDiscountMessage.decode(readValue(buffer)!); case 134: return SKProductMessage.decode(readValue(buffer)!); case 135: return SKProductSubscriptionPeriodMessage.decode(readValue(buffer)!); case 136: return SKProductsResponseMessage.decode(readValue(buffer)!); case 137: return SKStorefrontMessage.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class InAppPurchaseAPI { /// Constructor for [InAppPurchaseAPI]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. InAppPurchaseAPI({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = _InAppPurchaseAPICodec(); /// Returns if the current device is able to make payments Future<bool> canMakePayments() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.canMakePayments'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as bool?)!; } } Future<List<SKPaymentTransactionMessage?>> transactions() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.transactions'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as List<Object?>?)! .cast<SKPaymentTransactionMessage?>(); } } Future<SKStorefrontMessage> storefront() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.storefront'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as SKStorefrontMessage?)!; } } Future<void> addPayment(Map<String?, Object?> paymentMap) async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.addPayment'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[paymentMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<SKProductsResponseMessage> startProductRequest( List<String?> productIdentifiers) async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startProductRequest'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[productIdentifiers]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as SKProductsResponseMessage?)!; } } Future<void> finishTransaction(Map<String?, String?> finishMap) async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.finishTransaction'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[finishMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> restoreTransactions(String? applicationUserName) async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.restoreTransactions'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[applicationUserName]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> presentCodeRedemptionSheet() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.presentCodeRedemptionSheet'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<String?> retrieveReceiptData() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.retrieveReceiptData'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as String?); } } Future<void> refreshReceipt( {Map<String?, Object?>? receiptProperties}) async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.refreshReceipt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[receiptProperties]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> startObservingPaymentQueue() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startObservingPaymentQueue'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> stopObservingPaymentQueue() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.stopObservingPaymentQueue'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> registerPaymentQueueDelegate() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.registerPaymentQueueDelegate'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> removePaymentQueueDelegate() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.removePaymentQueueDelegate'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> showPriceConsentIfNeeded() async { const String __pigeon_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.showPriceConsentIfNeeded'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } }
packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 11331 }
988
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter import Foundation import UIKit @objc extension UIImage { /// Loads a UIImage from the embedded Flutter project's assets. /// /// This method loads the Flutter asset that is appropriate for the current /// screen. If you are on a 2x retina device where usually `UIImage` would be /// loading `@2x` assets, it will attempt to load the `2.0x` variant. It will /// load the standard image if it can't find the `2.0x` variant. /// /// For example, if your Flutter project's `pubspec.yaml` lists "assets/foo.png" /// and "assets/2.0x/foo.png", calling /// `[UIImage flutterImageWithName:@"assets/foo.png"]` will load /// "assets/2.0x/foo.png". /// /// See also https://flutter.dev/docs/development/ui/assets-and-images /// /// Note: We don't yet support images from package dependencies (ex. /// `AssetImage('icons/heart.png', package: 'my_icons')`). public static func flutterImageWithName(_ name: String) -> UIImage? { let filename = (name as NSString).lastPathComponent let path = (name as NSString).deletingLastPathComponent for screenScale in stride(from: Int(UIScreen.main.scale), to: 1, by: -1) { // TODO(hellohuanlin): Fix duplicate slashes in this path construction. let key = FlutterDartProject.lookupKey(forAsset: "\(path)/\(screenScale).0x/\(filename)") if let image = UIImage(named: key, in: Bundle.main, compatibleWith: nil) { return image } } let key = FlutterDartProject.lookupKey(forAsset: name) return UIImage(named: key, in: Bundle.main, compatibleWith: nil) } }
packages/packages/ios_platform_images/ios/Classes/UIImageIosPlatformImages.swift/0
{ "file_path": "packages/packages/ios_platform_images/ios/Classes/UIImageIosPlatformImages.swift", "repo_id": "packages", "token_count": 575 }
989
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="vertical" android:paddingLeft="24dp" android:paddingRight="24dp"> <TextView android:id="@+id/fingerprint_required" style="@android:style/TextAppearance.DeviceDefault.Medium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:paddingTop="24dp" android:paddingBottom="20dp" android:textColor="@color/black_text" android:textIsSelectable="false" android:textSize="@dimen/huge_text_size" /> <TextView android:id="@+id/go_to_setting_description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="28dp" android:textColor="@color/grey_text" android:textIsSelectable="false" android:textSize="@dimen/medium_text_size" android:textStyle="normal" /> </LinearLayout>
packages/packages/local_auth/local_auth_android/android/src/main/res/layout/go_to_setting.xml/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/main/res/layout/go_to_setting.xml", "repo_id": "packages", "token_count": 466 }
990
name: local_auth_android description: Android implementation of the local_auth plugin. repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22 version: 1.0.37 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: local_auth platforms: android: package: io.flutter.plugins.localauth pluginClass: LocalAuthPlugin dartPluginClass: LocalAuthAndroid dependencies: flutter: sdk: flutter flutter_plugin_android_lifecycle: ^2.0.1 intl: ">=0.17.0 <0.20.0" local_auth_platform_interface: ^1.0.1 dev_dependencies: build_runner: ^2.3.3 flutter_test: sdk: flutter mockito: 5.4.4 pigeon: ^11.0.0 topics: - authentication - biometrics - local-auth
packages/packages/local_auth/local_auth_android/pubspec.yaml/0
{ "file_path": "packages/packages/local_auth/local_auth_android/pubspec.yaml", "repo_id": "packages", "token_count": 367 }
991
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'local_auth_platform_interface.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/local_auth'); /// The default interface implementation acting as a placeholder for /// the native implementation to be set. /// /// This implementation is not used by any of the implementations in this /// repository, and exists only for backward compatibility with any /// clients that were relying on internal details of the method channel /// in the pre-federated plugin. class DefaultLocalAuthPlatform extends LocalAuthPlatform { @override Future<bool> authenticate({ required String localizedReason, required Iterable<AuthMessages> authMessages, AuthenticationOptions options = const AuthenticationOptions(), }) async { assert(localizedReason.isNotEmpty); final Map<String, Object> args = <String, Object>{ 'localizedReason': localizedReason, 'useErrorDialogs': options.useErrorDialogs, 'stickyAuth': options.stickyAuth, 'sensitiveTransaction': options.sensitiveTransaction, 'biometricOnly': options.biometricOnly, }; for (final AuthMessages messages in authMessages) { args.addAll(messages.args); } return (await _channel.invokeMethod<bool>('authenticate', args)) ?? false; } @override Future<List<BiometricType>> getEnrolledBiometrics() async { final List<String> result = (await _channel.invokeListMethod<String>( 'getAvailableBiometrics', )) ?? <String>[]; final List<BiometricType> biometrics = <BiometricType>[]; for (final String value in result) { switch (value) { case 'face': biometrics.add(BiometricType.face); case 'fingerprint': biometrics.add(BiometricType.fingerprint); case 'iris': biometrics.add(BiometricType.iris); case 'undefined': // Sentinel value for the case when nothing is enrolled, but hardware // support for biometrics is available. break; } } return biometrics; } @override Future<bool> deviceSupportsBiometrics() async { final List<String> availableBiometrics = (await _channel.invokeListMethod<String>( 'getAvailableBiometrics', )) ?? <String>[]; // If anything, including the 'undefined' sentinel, is returned, then there // is device support for biometrics. return availableBiometrics.isNotEmpty; } @override Future<bool> isDeviceSupported() async => (await _channel.invokeMethod<bool>('isDeviceSupported')) ?? false; @override Future<bool> stopAuthentication() async => await _channel.invokeMethod<bool>('stopAuthentication') ?? false; }
packages/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart", "repo_id": "packages", "token_count": 985 }
992
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.2), do not edit directly. // See also: https://pub.dev/packages/pigeon #ifndef PIGEON_MESSAGES_G_H_ #define PIGEON_MESSAGES_G_H_ #include <flutter/basic_message_channel.h> #include <flutter/binary_messenger.h> #include <flutter/encodable_value.h> #include <flutter/standard_message_codec.h> #include <map> #include <optional> #include <string> namespace local_auth_windows { // Generated class from Pigeon. class FlutterError { public: explicit FlutterError(const std::string& code) : code_(code) {} explicit FlutterError(const std::string& code, const std::string& message) : code_(code), message_(message) {} explicit FlutterError(const std::string& code, const std::string& message, const flutter::EncodableValue& details) : code_(code), message_(message), details_(details) {} const std::string& code() const { return code_; } const std::string& message() const { return message_; } const flutter::EncodableValue& details() const { return details_; } private: std::string code_; std::string message_; flutter::EncodableValue details_; }; template <class T> class ErrorOr { public: ErrorOr(const T& rhs) : v_(rhs) {} ErrorOr(const T&& rhs) : v_(std::move(rhs)) {} ErrorOr(const FlutterError& rhs) : v_(rhs) {} ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {} bool has_error() const { return std::holds_alternative<FlutterError>(v_); } const T& value() const { return std::get<T>(v_); }; const FlutterError& error() const { return std::get<FlutterError>(v_); }; private: friend class LocalAuthApi; ErrorOr() = default; T TakeValue() && { return std::get<T>(std::move(v_)); } std::variant<T, FlutterError> v_; }; // Generated interface from Pigeon that represents a handler of messages from // Flutter. class LocalAuthApi { public: LocalAuthApi(const LocalAuthApi&) = delete; LocalAuthApi& operator=(const LocalAuthApi&) = delete; virtual ~LocalAuthApi() {} // Returns true if this device supports authentication. virtual void IsDeviceSupported( std::function<void(ErrorOr<bool> reply)> result) = 0; // Attempts to authenticate the user with the provided [localizedReason] as // the user-facing explanation for the authorization request. // // Returns true if authorization succeeds, false if it is attempted but is // not successful, and an error if authorization could not be attempted. virtual void Authenticate( const std::string& localized_reason, std::function<void(ErrorOr<bool> reply)> result) = 0; // The codec used by LocalAuthApi. static const flutter::StandardMessageCodec& GetCodec(); // Sets up an instance of `LocalAuthApi` to handle messages through the // `binary_messenger`. static void SetUp(flutter::BinaryMessenger* binary_messenger, LocalAuthApi* api); static flutter::EncodableValue WrapError(std::string_view error_message); static flutter::EncodableValue WrapError(const FlutterError& error); protected: LocalAuthApi() = default; }; } // namespace local_auth_windows #endif // PIGEON_MESSAGES_G_H_
packages/packages/local_auth/local_auth_windows/windows/messages.g.h/0
{ "file_path": "packages/packages/local_auth/local_auth_windows/windows/messages.g.h", "repo_id": "packages", "token_count": 1100 }
993
name: metrics_center version: 1.0.13 description: Support multiple performance metrics sources/formats and destinations. repository: https://github.com/flutter/packages/tree/main/packages/metrics_center issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+metrics_center%22 environment: sdk: ^3.1.0 dependencies: _discoveryapis_commons: ^1.0.0 crypto: ^3.0.1 gcloud: ^0.8.2 googleapis: ^12.0.0 googleapis_auth: ^1.1.0 http: ">=0.13.0 <2.0.0" dev_dependencies: build_runner: ^2.1.1 fake_async: ^1.2.0 mockito: 5.4.4 test: ^1.17.11 topics: - ci - metrics
packages/packages/metrics_center/pubspec.yaml/0
{ "file_path": "packages/packages/metrics_center/pubspec.yaml", "repo_id": "packages", "token_count": 276 }
994
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Example script to illustrate how to use the mdns package to lookup names // on the local network. // ignore_for_file: avoid_print import 'package:multicast_dns/multicast_dns.dart'; Future<void> main(List<String> args) async { if (args.length != 1) { print(''' Please provide an address as argument. For example: dart mdns_resolve.dart dartino.local'''); return; } final String name = args[0]; final MDnsClient client = MDnsClient(); await client.start(); await for (final IPAddressResourceRecord record in client .lookup<IPAddressResourceRecord>(ResourceRecordQuery.addressIPv4(name))) { print('Found address (${record.address}).'); } await for (final IPAddressResourceRecord record in client .lookup<IPAddressResourceRecord>(ResourceRecordQuery.addressIPv6(name))) { print('Found address (${record.address}).'); } client.stop(); }
packages/packages/multicast_dns/example/mdns_resolve.dart/0
{ "file_path": "packages/packages/multicast_dns/example/mdns_resolve.dart", "repo_id": "packages", "token_count": 331 }
995
#include "ephemeral/Flutter-Generated.xcconfig"
packages/packages/palette_generator/example/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "packages/packages/palette_generator/example/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "packages", "token_count": 19 }
996
name: path_provider description: Flutter plugin for getting commonly used locations on host platform file systems, such as the temp and app data directories. repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 version: 2.1.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: platforms: android: default_package: path_provider_android ios: default_package: path_provider_foundation linux: default_package: path_provider_linux macos: default_package: path_provider_foundation windows: default_package: path_provider_windows dependencies: flutter: sdk: flutter path_provider_android: ^2.1.0 path_provider_foundation: ^2.3.0 path_provider_linux: ^2.2.0 path_provider_platform_interface: ^2.1.0 path_provider_windows: ^2.2.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter plugin_platform_interface: ^2.1.7 test: ^1.16.0 topics: - files - path-provider - paths
packages/packages/path_provider/path_provider/pubspec.yaml/0
{ "file_path": "packages/packages/path_provider/path_provider/pubspec.yaml", "repo_id": "packages", "token_count": 477 }
997
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/path_provider/path_provider_foundation/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
998
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:path_provider_windows/path_provider_windows.dart'; void main() { runApp(const MyApp()); } /// Sample app class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String? _tempDirectory = 'Unknown'; String? _downloadsDirectory = 'Unknown'; String? _appSupportDirectory = 'Unknown'; String? _documentsDirectory = 'Unknown'; String? _cacheDirectory = 'Unknown'; @override void initState() { super.initState(); initDirectories(); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initDirectories() async { String? tempDirectory; String? downloadsDirectory; String? appSupportDirectory; String? documentsDirectory; String? cacheDirectory; final PathProviderWindows provider = PathProviderWindows(); try { tempDirectory = await provider.getTemporaryPath(); } catch (exception) { tempDirectory = 'Failed to get temp directory: $exception'; } try { downloadsDirectory = await provider.getDownloadsPath(); } catch (exception) { downloadsDirectory = 'Failed to get downloads directory: $exception'; } try { documentsDirectory = await provider.getApplicationDocumentsPath(); } catch (exception) { documentsDirectory = 'Failed to get documents directory: $exception'; } try { appSupportDirectory = await provider.getApplicationSupportPath(); } catch (exception) { appSupportDirectory = 'Failed to get app support directory: $exception'; } try { cacheDirectory = await provider.getApplicationCachePath(); } catch (exception) { cacheDirectory = 'Failed to get cache directory: $exception'; } setState(() { _tempDirectory = tempDirectory; _downloadsDirectory = downloadsDirectory; _appSupportDirectory = appSupportDirectory; _documentsDirectory = documentsDirectory; _cacheDirectory = cacheDirectory; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Path Provider example app'), ), body: Center( child: Column( children: <Widget>[ Text('Temp Directory: $_tempDirectory\n'), Text('Documents Directory: $_documentsDirectory\n'), Text('Downloads Directory: $_downloadsDirectory\n'), Text('Application Support Directory: $_appSupportDirectory\n'), Text('Cache Directory: $_cacheDirectory\n'), ], ), ), ), ); } }
packages/packages/path_provider/path_provider_windows/example/lib/main.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_windows/example/lib/main.dart", "repo_id": "packages", "token_count": 1040 }
999
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/pigeon/example/app/android/gradle.properties/0
{ "file_path": "packages/packages/pigeon/example/app/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
1,000
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'dart:convert'; import 'dart:io'; import 'dart:mirrors'; import 'package:analyzer/dart/analysis/analysis_context.dart' show AnalysisContext; import 'package:analyzer/dart/analysis/analysis_context_collection.dart' show AnalysisContextCollection; import 'package:analyzer/dart/analysis/results.dart' show ParsedUnitResult; import 'package:analyzer/dart/analysis/session.dart' show AnalysisSession; import 'package:analyzer/dart/ast/ast.dart' as dart_ast; import 'package:analyzer/dart/ast/syntactic_entity.dart' as dart_ast_syntactic_entity; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart' as dart_ast_visitor; import 'package:analyzer/error/error.dart' show AnalysisError; import 'package:args/args.dart'; import 'package:collection/collection.dart' as collection; import 'package:path/path.dart' as path; import 'ast.dart'; import 'ast_generator.dart'; import 'cpp_generator.dart'; import 'dart_generator.dart'; import 'generator_tools.dart'; import 'generator_tools.dart' as generator_tools; import 'java_generator.dart'; import 'kotlin_generator.dart'; import 'objc_generator.dart'; import 'swift_generator.dart'; class _Asynchronous { const _Asynchronous(); } class _Attached { const _Attached(); } class _Static { const _Static(); } /// Metadata to annotate a Api method as asynchronous const Object async = _Asynchronous(); /// Metadata to annotate the field of a ProxyApi as an Attached Field. /// /// Attached fields provide a synchronous [ProxyApi] instance as a field for /// another [ProxyApi]. /// /// Attached fields: /// * Must be nonnull. /// * Must be a ProxyApi (a class annotated with `@ProxyApi()`). /// * Must not contain any unattached fields. /// * Must not have a required callback Flutter method. /// /// Example generated code: /// /// ```dart /// class MyProxyApi { /// final MyOtherProxyApi myField = __pigeon_myField(). /// } /// ``` /// /// The field provides access to the value synchronously, but the native /// instance is stored in the native `InstanceManager` asynchronously. Similar /// to how constructors are implemented. const Object attached = _Attached(); /// Metadata to annotate a field of a ProxyApi as static. /// /// Static fields are the same as [attached] fields except the field is static /// and not attached to any instance of the ProxyApi. const Object static = _Static(); /// Metadata annotation used to configure how Pigeon will generate code. class ConfigurePigeon { /// Constructor for ConfigurePigeon. const ConfigurePigeon(this.options); /// The [PigeonOptions] that will be merged into the command line options. final PigeonOptions options; } /// Metadata to annotate a Pigeon API implemented by the host-platform. /// /// The abstract class with this annotation groups a collection of Dart↔host /// interop methods. These methods are invoked by Dart and are received by a /// host-platform (such as in Android or iOS) by a class implementing the /// generated host-platform interface. class HostApi { /// Parametric constructor for [HostApi]. const HostApi({this.dartHostTestHandler}); /// The name of an interface generated for tests. Implement this /// interface and invoke `[name of this handler].setup` to receive /// calls from your real [HostApi] class in Dart instead of the host /// platform code, as is typical. /// /// When using this, you must specify the `--out_test_dart` argument /// to specify where to generate the test file. /// /// Prefer to use a mock of the real [HostApi] with a mocking library for unit /// tests. Generating this Dart handler is sometimes useful in integration /// testing. /// /// Defaults to `null` in which case no handler will be generated. final String? dartHostTestHandler; } /// Metadata to annotate a Pigeon API implemented by Flutter. /// /// The abstract class with this annotation groups a collection of Dart↔host /// interop methods. These methods are invoked by the host-platform (such as in /// Android or iOS) and are received by Flutter by a class implementing the /// generated Dart interface. class FlutterApi { /// Parametric constructor for [FlutterApi]. const FlutterApi(); } /// Metadata to annotate a Pigeon API that wraps a native class. /// /// The abstract class with this annotation groups a collection of Dart↔host /// constructors, fields, methods and host↔Dart methods used to wrap a native /// class. /// /// The generated Dart class acts as a proxy to a native type and maintains /// instances automatically with an `InstanceManager`. The generated host /// language class implements methods to interact with class instances or static /// methods. class ProxyApi { /// Parametric constructor for [ProxyApi]. const ProxyApi({this.superClass}); /// The proxy api that is a super class to this one. /// /// This provides an alternative to calling `extends` on a class since this /// requires calling the super class constructor. /// /// Note that using this instead of `extends` can cause unexpected conflicts /// with inherited method names. final Type? superClass; } /// Metadata to annotation methods to control the selector used for objc output. /// The number of components in the provided selector must match the number of /// arguments in the annotated method. /// For example: /// @ObjcSelector('divideValue:by:') double divide(int x, int y); class ObjCSelector { /// Constructor. const ObjCSelector(this.value); /// The string representation of the selector. final String value; } /// Metadata to annotate methods to control the signature used for Swift output. /// /// The number of components in the provided signature must match the number of /// arguments in the annotated method. /// For example: /// @SwiftFunction('divide(_:by:)') double divide(int x, String y); class SwiftFunction { /// Constructor. const SwiftFunction(this.value); /// The string representation of the function signature. final String value; } /// Type of TaskQueue which determines how handlers are dispatched for /// HostApi's. enum TaskQueueType { /// Handlers are invoked serially on the default thread. This is the value if /// unspecified. serial, /// Handlers are invoked serially on a background thread. serialBackgroundThread, // TODO(gaaclarke): Add support for concurrent task queues. // /// Handlers are invoked concurrently on a background thread. // concurrentBackgroundThread, } /// Metadata annotation to control how handlers are dispatched for HostApi's. /// Note that the TaskQueue API might not be available on the target version of /// Flutter, see also: /// https://docs.flutter.dev/development/platform-integration/platform-channels. class TaskQueue { /// The constructor for a TaskQueue. const TaskQueue({required this.type}); /// The type of the TaskQueue. final TaskQueueType type; } /// Represents an error as a result of parsing and generating code. class Error { /// Parametric constructor for Error. Error({ required this.message, this.filename, this.lineNumber, }); /// A description of the error. String message; /// What file caused the [Error]. String? filename; /// What line the error happened on. int? lineNumber; @override String toString() { return '(Error message:"$message" filename:"$filename" lineNumber:$lineNumber)'; } } /// Options used when running the code generator. class PigeonOptions { /// Creates a instance of PigeonOptions const PigeonOptions({ this.input, this.dartOut, this.dartTestOut, this.objcHeaderOut, this.objcSourceOut, this.objcOptions, this.javaOut, this.javaOptions, this.swiftOut, this.swiftOptions, this.kotlinOut, this.kotlinOptions, this.cppHeaderOut, this.cppSourceOut, this.cppOptions, this.dartOptions, this.copyrightHeader, this.oneLanguage, this.astOut, this.debugGenerators, this.basePath, String? dartPackageName, }) : _dartPackageName = dartPackageName; /// Path to the file which will be processed. final String? input; /// Path to the dart file that will be generated. final String? dartOut; /// Path to the dart file that will be generated for test support classes. final String? dartTestOut; /// Path to the ".h" Objective-C file will be generated. final String? objcHeaderOut; /// Path to the ".m" Objective-C file will be generated. final String? objcSourceOut; /// Options that control how Objective-C will be generated. final ObjcOptions? objcOptions; /// Path to the java file that will be generated. final String? javaOut; /// Options that control how Java will be generated. final JavaOptions? javaOptions; /// Path to the swift file that will be generated. final String? swiftOut; /// Options that control how Swift will be generated. final SwiftOptions? swiftOptions; /// Path to the kotlin file that will be generated. final String? kotlinOut; /// Options that control how Kotlin will be generated. final KotlinOptions? kotlinOptions; /// Path to the ".h" C++ file that will be generated. final String? cppHeaderOut; /// Path to the ".cpp" C++ file that will be generated. final String? cppSourceOut; /// Options that control how C++ will be generated. final CppOptions? cppOptions; /// Options that control how Dart will be generated. final DartOptions? dartOptions; /// Path to a copyright header that will get prepended to generated code. final String? copyrightHeader; /// If Pigeon allows generating code for one language. final bool? oneLanguage; /// Path to AST debugging output. final String? astOut; /// True means print out line number of generators in comments at newlines. final bool? debugGenerators; /// A base path to be prepended to all provided output paths. final String? basePath; /// The name of the package the pigeon files will be used in. final String? _dartPackageName; /// Creates a [PigeonOptions] from a Map representation where: /// `x = PigeonOptions.fromMap(x.toMap())`. static PigeonOptions fromMap(Map<String, Object> map) { return PigeonOptions( input: map['input'] as String?, dartOut: map['dartOut'] as String?, dartTestOut: map['dartTestOut'] as String?, objcHeaderOut: map['objcHeaderOut'] as String?, objcSourceOut: map['objcSourceOut'] as String?, objcOptions: map.containsKey('objcOptions') ? ObjcOptions.fromMap(map['objcOptions']! as Map<String, Object>) : null, javaOut: map['javaOut'] as String?, javaOptions: map.containsKey('javaOptions') ? JavaOptions.fromMap(map['javaOptions']! as Map<String, Object>) : null, swiftOut: map['swiftOut'] as String?, swiftOptions: map.containsKey('swiftOptions') ? SwiftOptions.fromList(map['swiftOptions']! as Map<String, Object>) : null, kotlinOut: map['kotlinOut'] as String?, kotlinOptions: map.containsKey('kotlinOptions') ? KotlinOptions.fromMap(map['kotlinOptions']! as Map<String, Object>) : null, cppHeaderOut: map['cppHeaderOut'] as String?, cppSourceOut: map['cppSourceOut'] as String?, cppOptions: map.containsKey('cppOptions') ? CppOptions.fromMap(map['cppOptions']! as Map<String, Object>) : null, dartOptions: map.containsKey('dartOptions') ? DartOptions.fromMap(map['dartOptions']! as Map<String, Object>) : null, copyrightHeader: map['copyrightHeader'] as String?, oneLanguage: map['oneLanguage'] as bool?, astOut: map['astOut'] as String?, debugGenerators: map['debugGenerators'] as bool?, basePath: map['basePath'] as String?, dartPackageName: map['dartPackageName'] as String?, ); } /// Converts a [PigeonOptions] to a Map representation where: /// `x = PigeonOptions.fromMap(x.toMap())`. Map<String, Object> toMap() { final Map<String, Object> result = <String, Object>{ if (input != null) 'input': input!, if (dartOut != null) 'dartOut': dartOut!, if (dartTestOut != null) 'dartTestOut': dartTestOut!, if (objcHeaderOut != null) 'objcHeaderOut': objcHeaderOut!, if (objcSourceOut != null) 'objcSourceOut': objcSourceOut!, if (objcOptions != null) 'objcOptions': objcOptions!.toMap(), if (javaOut != null) 'javaOut': javaOut!, if (javaOptions != null) 'javaOptions': javaOptions!.toMap(), if (swiftOut != null) 'swiftOut': swiftOut!, if (swiftOptions != null) 'swiftOptions': swiftOptions!.toMap(), if (kotlinOut != null) 'kotlinOut': kotlinOut!, if (kotlinOptions != null) 'kotlinOptions': kotlinOptions!.toMap(), if (cppHeaderOut != null) 'cppHeaderOut': cppHeaderOut!, if (cppSourceOut != null) 'cppSourceOut': cppSourceOut!, if (cppOptions != null) 'cppOptions': cppOptions!.toMap(), if (dartOptions != null) 'dartOptions': dartOptions!.toMap(), if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, if (astOut != null) 'astOut': astOut!, if (oneLanguage != null) 'oneLanguage': oneLanguage!, if (debugGenerators != null) 'debugGenerators': debugGenerators!, if (basePath != null) 'basePath': basePath!, if (_dartPackageName != null) 'dartPackageName': _dartPackageName!, }; return result; } /// Overrides any non-null parameters from [options] into this to make a new /// [PigeonOptions]. PigeonOptions merge(PigeonOptions options) { return PigeonOptions.fromMap(mergeMaps(toMap(), options.toMap())); } /// Returns provided or deduced package name, throws `Exception` if none found. String getPackageName() { final String? name = _dartPackageName ?? deducePackageName(dartOut ?? ''); if (name == null) { throw Exception( 'Unable to deduce package name, and no package name supplied.\n' 'Add a `dartPackageName` property to your `PigeonOptions` config,\n' 'or add --dartPackageName={name_of_package} to your command line pigeon call.', ); } return name; } } /// A collection of an AST represented as a [Root] and [Error]'s. class ParseResults { /// Parametric constructor for [ParseResults]. ParseResults({ required this.root, required this.errors, required this.pigeonOptions, }); /// The resulting AST. final Root root; /// Errors generated while parsing input. final List<Error> errors; /// The Map representation of any [PigeonOptions] specified with /// [ConfigurePigeon] during parsing. final Map<String, Object>? pigeonOptions; } Iterable<String> _lineReader(String path) sync* { final String contents = File(path).readAsStringSync(); const LineSplitter lineSplitter = LineSplitter(); final List<String> lines = lineSplitter.convert(contents); for (final String line in lines) { yield line; } } IOSink? _openSink(String? output, {String basePath = ''}) { if (output == null) { return null; } IOSink sink; File file; if (output == 'stdout') { sink = stdout; } else { file = File(path.posix.join(basePath, output)); file.createSync(recursive: true); sink = file.openWrite(); } return sink; } /// An adapter that will call a generator to write code to a sink /// based on the contents of [PigeonOptions]. abstract class GeneratorAdapter { /// Constructor for [GeneratorAdapter] GeneratorAdapter(this.fileTypeList); /// A list of file types the generator should create. List<FileType> fileTypeList; /// Returns an [IOSink] instance to be written to /// if the [GeneratorAdapter] should generate. /// /// If it returns `null`, the [GeneratorAdapter] will be skipped. IOSink? shouldGenerate(PigeonOptions options, FileType fileType); /// Write the generated code described in [root] to [sink] using the [options]. void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType); /// Generates errors that would only be appropriate for this [GeneratorAdapter]. /// /// For example, if a certain feature isn't implemented in a [GeneratorAdapter] yet. List<Error> validate(PigeonOptions options, Root root); } DartOptions _dartOptionsWithCopyrightHeader( DartOptions? dartOptions, String? copyrightHeader, { String? dartOutPath, String? testOutPath, String basePath = '', }) { dartOptions = dartOptions ?? const DartOptions(); return dartOptions.merge(DartOptions( sourceOutPath: dartOutPath, testOutPath: testOutPath, copyrightHeader: copyrightHeader != null ? _lineReader(path.posix.join(basePath, copyrightHeader)) : null, )); } /// A [GeneratorAdapter] that generates the AST. class AstGeneratorAdapter implements GeneratorAdapter { /// Constructor for [AstGeneratorAdapter]. AstGeneratorAdapter(); @override List<FileType> fileTypeList = const <FileType>[FileType.na]; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { generateAst(root, sink); } @override IOSink? shouldGenerate(PigeonOptions options, FileType _) => _openSink(options.astOut, basePath: options.basePath ?? ''); @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } /// A [GeneratorAdapter] that generates Dart source code. class DartGeneratorAdapter implements GeneratorAdapter { /// Constructor for [DartGeneratorAdapter]. DartGeneratorAdapter(); @override List<FileType> fileTypeList = const <FileType>[FileType.na]; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { final DartOptions dartOptionsWithHeader = _dartOptionsWithCopyrightHeader( options.dartOptions, options.copyrightHeader, testOutPath: options.dartTestOut, basePath: options.basePath ?? '', ); const DartGenerator generator = DartGenerator(); generator.generate( dartOptionsWithHeader, root, sink, dartPackageName: options.getPackageName(), ); } @override IOSink? shouldGenerate(PigeonOptions options, FileType _) => _openSink(options.dartOut, basePath: options.basePath ?? ''); @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } /// A [GeneratorAdapter] that generates Dart test source code. class DartTestGeneratorAdapter implements GeneratorAdapter { /// Constructor for [DartTestGeneratorAdapter]. DartTestGeneratorAdapter(); @override List<FileType> fileTypeList = const <FileType>[FileType.na]; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { final DartOptions dartOptionsWithHeader = _dartOptionsWithCopyrightHeader( options.dartOptions, options.copyrightHeader, dartOutPath: options.dartOut, testOutPath: options.dartTestOut, basePath: options.basePath ?? '', ); const DartGenerator testGenerator = DartGenerator(); // The test code needs the actual package name of the Dart output, even if // the package name has been overridden for other uses. final String outputPackageName = deducePackageName(options.dartOut ?? '') ?? options.getPackageName(); testGenerator.generateTest( dartOptionsWithHeader, root, sink, dartPackageName: options.getPackageName(), dartOutputPackageName: outputPackageName, ); } @override IOSink? shouldGenerate(PigeonOptions options, FileType _) { if (options.dartTestOut != null) { return _openSink(options.dartTestOut, basePath: options.basePath ?? ''); } else { return null; } } @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } /// A [GeneratorAdapter] that generates Objective-C code. class ObjcGeneratorAdapter implements GeneratorAdapter { /// Constructor for [ObjcGeneratorAdapter]. ObjcGeneratorAdapter( {this.fileTypeList = const <FileType>[FileType.header, FileType.source]}); @override List<FileType> fileTypeList; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { final ObjcOptions objcOptions = options.objcOptions ?? const ObjcOptions(); final ObjcOptions objcOptionsWithHeader = objcOptions.merge(ObjcOptions( copyrightHeader: options.copyrightHeader != null ? _lineReader( path.posix.join(options.basePath ?? '', options.copyrightHeader)) : null, )); final OutputFileOptions<ObjcOptions> outputFileOptions = OutputFileOptions<ObjcOptions>( fileType: fileType, languageOptions: objcOptionsWithHeader); const ObjcGenerator generator = ObjcGenerator(); generator.generate( outputFileOptions, root, sink, dartPackageName: options.getPackageName(), ); } @override IOSink? shouldGenerate(PigeonOptions options, FileType fileType) { if (fileType == FileType.source) { return _openSink(options.objcSourceOut, basePath: options.basePath ?? ''); } else { return _openSink(options.objcHeaderOut, basePath: options.basePath ?? ''); } } @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } /// A [GeneratorAdapter] that generates Java source code. class JavaGeneratorAdapter implements GeneratorAdapter { /// Constructor for [JavaGeneratorAdapter]. JavaGeneratorAdapter(); @override List<FileType> fileTypeList = const <FileType>[FileType.na]; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { JavaOptions javaOptions = options.javaOptions ?? const JavaOptions(); javaOptions = javaOptions.merge(JavaOptions( className: javaOptions.className ?? path.basenameWithoutExtension(options.javaOut!), copyrightHeader: options.copyrightHeader != null ? _lineReader( path.posix.join(options.basePath ?? '', options.copyrightHeader)) : null, )); const JavaGenerator generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: options.getPackageName(), ); } @override IOSink? shouldGenerate(PigeonOptions options, FileType _) => _openSink(options.javaOut, basePath: options.basePath ?? ''); @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } /// A [GeneratorAdapter] that generates Swift source code. class SwiftGeneratorAdapter implements GeneratorAdapter { /// Constructor for [SwiftGeneratorAdapter]. SwiftGeneratorAdapter(); @override List<FileType> fileTypeList = const <FileType>[FileType.na]; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { SwiftOptions swiftOptions = options.swiftOptions ?? const SwiftOptions(); swiftOptions = swiftOptions.merge(SwiftOptions( copyrightHeader: options.copyrightHeader != null ? _lineReader( path.posix.join(options.basePath ?? '', options.copyrightHeader)) : null, )); const SwiftGenerator generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: options.getPackageName(), ); } @override IOSink? shouldGenerate(PigeonOptions options, FileType _) => _openSink(options.swiftOut, basePath: options.basePath ?? ''); @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } /// A [GeneratorAdapter] that generates C++ source code. class CppGeneratorAdapter implements GeneratorAdapter { /// Constructor for [CppGeneratorAdapter]. CppGeneratorAdapter( {this.fileTypeList = const <FileType>[FileType.header, FileType.source]}); @override List<FileType> fileTypeList; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { final CppOptions cppOptions = options.cppOptions ?? const CppOptions(); final CppOptions cppOptionsWithHeader = cppOptions.merge(CppOptions( copyrightHeader: options.copyrightHeader != null ? _lineReader( path.posix.join(options.basePath ?? '', options.copyrightHeader)) : null, )); final OutputFileOptions<CppOptions> outputFileOptions = OutputFileOptions<CppOptions>( fileType: fileType, languageOptions: cppOptionsWithHeader); const CppGenerator generator = CppGenerator(); generator.generate( outputFileOptions, root, sink, dartPackageName: options.getPackageName(), ); } @override IOSink? shouldGenerate(PigeonOptions options, FileType fileType) { if (fileType == FileType.source) { return _openSink(options.cppSourceOut, basePath: options.basePath ?? ''); } else { return _openSink(options.cppHeaderOut, basePath: options.basePath ?? ''); } } @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } /// A [GeneratorAdapter] that generates Kotlin source code. class KotlinGeneratorAdapter implements GeneratorAdapter { /// Constructor for [KotlinGeneratorAdapter]. KotlinGeneratorAdapter({this.fileTypeList = const <FileType>[FileType.na]}); @override List<FileType> fileTypeList; @override void generate( StringSink sink, PigeonOptions options, Root root, FileType fileType) { KotlinOptions kotlinOptions = options.kotlinOptions ?? const KotlinOptions(); kotlinOptions = kotlinOptions.merge(KotlinOptions( errorClassName: kotlinOptions.errorClassName ?? 'FlutterError', includeErrorClass: kotlinOptions.includeErrorClass, copyrightHeader: options.copyrightHeader != null ? _lineReader( path.posix.join(options.basePath ?? '', options.copyrightHeader)) : null, )); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: options.getPackageName(), ); } @override IOSink? shouldGenerate(PigeonOptions options, FileType _) => _openSink(options.kotlinOut, basePath: options.basePath ?? ''); @override List<Error> validate(PigeonOptions options, Root root) => <Error>[]; } dart_ast.Annotation? _findMetadata( dart_ast.NodeList<dart_ast.Annotation> metadata, String query) { final Iterable<dart_ast.Annotation> annotations = metadata .where((dart_ast.Annotation element) => element.name.name == query); return annotations.isEmpty ? null : annotations.first; } bool _hasMetadata( dart_ast.NodeList<dart_ast.Annotation> metadata, String query) { return _findMetadata(metadata, query) != null; } extension _ObjectAs on Object { /// A convenience for chaining calls with casts. T? asNullable<T>() => this as T?; } List<Error> _validateAst(Root root, String source) { final List<Error> result = <Error>[]; final List<String> customClasses = root.classes.map((Class x) => x.name).toList(); final Iterable<String> customEnums = root.enums.map((Enum x) => x.name); for (final Class classDefinition in root.classes) { for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { for (final TypeDeclaration typeArgument in field.type.typeArguments) { if (!typeArgument.isNullable) { result.add(Error( message: 'Generic type parameters must be nullable in field "${field.name}" in class "${classDefinition.name}".', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } if (customEnums.contains(typeArgument.baseName)) { result.add(Error( message: 'Enum types aren\'t supported in type arguments in "${field.name}" in class "${classDefinition.name}".', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } } if (!(validTypes.contains(field.type.baseName) || customClasses.contains(field.type.baseName) || customEnums.contains(field.type.baseName))) { result.add(Error( message: 'Unsupported datatype:"${field.type.baseName}" in class "${classDefinition.name}".', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } } } for (final Api api in root.apis) { if (api is AstProxyApi) { result.addAll(_validateProxyApi( api, source, customClasses: customClasses.toSet(), proxyApis: root.apis.whereType<AstProxyApi>().toSet(), )); } for (final Method method in api.methods) { for (final Parameter param in method.parameters) { if (param.type.baseName.isEmpty) { result.add(Error( message: 'Parameters must specify their type in method "${method.name}" in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, param.offset), )); } else { final String? matchingPrefix = _findMatchingPrefixOrNull( method.name, prefixes: <String>['__pigeon_', 'pigeonChannelCodec'], ); if (matchingPrefix != null) { result.add(Error( message: 'Parameter name must not begin with "$matchingPrefix" in method "${method.name} in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, param.offset), )); } } if (api is AstFlutterApi) { if (!param.isPositional) { result.add(Error( message: 'FlutterApi method parameters must be positional, in method "${method.name}" in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, param.offset), )); } else if (param.isOptional) { result.add(Error( message: 'FlutterApi method parameters must not be optional, in method "${method.name}" in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, param.offset), )); } } } if (method.objcSelector.isNotEmpty) { if (':'.allMatches(method.objcSelector).length != method.parameters.length) { result.add(Error( message: 'Invalid selector, expected ${method.parameters.length} parameters.', lineNumber: _calculateLineNumberNullable(source, method.offset), )); } } if (method.swiftFunction.isNotEmpty) { final RegExp signatureRegex = RegExp('\\w+ *\\((\\w+:){${method.parameters.length}}\\)'); if (!signatureRegex.hasMatch(method.swiftFunction)) { result.add(Error( message: 'Invalid function signature, expected ${method.parameters.length} parameters.', lineNumber: _calculateLineNumberNullable(source, method.offset), )); } } if (method.taskQueueType != TaskQueueType.serial && method.location == ApiLocation.flutter) { result.add(Error( message: 'Unsupported TaskQueue specification on ${method.name}', lineNumber: _calculateLineNumberNullable(source, method.offset), )); } } } return result; } List<Error> _validateProxyApi( AstProxyApi api, String source, { required Set<String> customClasses, required Set<AstProxyApi> proxyApis, }) { final List<Error> result = <Error>[]; bool isDataClass(NamedType type) => customClasses.contains(type.type.baseName); bool isProxyApi(NamedType type) => proxyApis.any( (AstProxyApi api) => api.name == type.type.baseName, ); Error unsupportedDataClassError(NamedType type) { return Error( message: 'ProxyApis do not support data classes: ${type.type.baseName}.', lineNumber: _calculateLineNumberNullable(source, type.offset), ); } AstProxyApi? directSuperClass; // Validate direct super class is another ProxyApi if (api.superClass != null) { directSuperClass = proxyApis.firstWhereOrNull( (AstProxyApi proxyApi) => proxyApi.name == api.superClass?.baseName, ); if (directSuperClass == null) { result.add( Error( message: 'Super class of ${api.name} is not marked as a @ProxyApi: ' '${api.superClass?.baseName}', ), ); } } // Validate that the api does not inherit an unattached field from its super class. if (directSuperClass != null && directSuperClass.unattachedFields.isNotEmpty) { result.add(Error( message: 'Unattached fields can not be inherited. Unattached field found for parent class: ${directSuperClass.unattachedFields.first.name}', lineNumber: _calculateLineNumberNullable( source, directSuperClass.unattachedFields.first.offset, ), )); } // Validate all interfaces are other ProxyApis final Iterable<String> interfaceNames = api.interfaces.map( (TypeDeclaration type) => type.baseName, ); for (final String interfaceName in interfaceNames) { if (!proxyApis.any((AstProxyApi api) => api.name == interfaceName)) { result.add(Error( message: 'Interface of ${api.name} is not marked as a @ProxyApi: $interfaceName', )); } } final bool hasUnattachedField = api.unattachedFields.isNotEmpty; final bool hasRequiredFlutterMethod = api.flutterMethods.any((Method method) => method.isRequired); for (final AstProxyApi proxyApi in proxyApis) { // Validate this api is not used as an attached field while either: // 1. Having an unattached field. // 2. Having a required Flutter method. if (hasUnattachedField || hasRequiredFlutterMethod) { for (final ApiField field in proxyApi.attachedFields) { if (field.type.baseName == api.name) { if (hasUnattachedField) { result.add(Error( message: 'ProxyApis with unattached fields can not be used as attached fields: ${field.name}', lineNumber: _calculateLineNumberNullable( source, field.offset, ), )); } if (hasRequiredFlutterMethod) { result.add(Error( message: 'ProxyApis with required callback methods can not be used as attached fields: ${field.name}', lineNumber: _calculateLineNumberNullable( source, field.offset, ), )); } } } } // Validate this api isn't used as an interface and contains anything except // Flutter methods, a static host method, attached methods. final bool isValidInterfaceProxyApi = api.constructors.isEmpty && api.fields.where((ApiField field) => !field.isStatic).isEmpty && api.hostMethods.where((Method method) => !method.isStatic).isEmpty; if (!isValidInterfaceProxyApi) { final Iterable<String> interfaceNames = proxyApi.interfaces.map( (TypeDeclaration type) => type.baseName, ); for (final String interfaceName in interfaceNames) { if (interfaceName == api.name) { result.add(Error( message: 'ProxyApis used as interfaces can only have callback methods: `${proxyApi.name}` implements `${api.name}`', )); } } } } // Validate constructor parameters for (final Constructor constructor in api.constructors) { for (final Parameter parameter in constructor.parameters) { if (isDataClass(parameter)) { result.add(unsupportedDataClassError(parameter)); } if (api.fields.any((ApiField field) => field.name == parameter.name) || api.flutterMethods .any((Method method) => method.name == parameter.name)) { result.add(Error( message: 'Parameter names must not share a name with a field or callback method in constructor "${constructor.name}" in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, parameter.offset), )); } if (parameter.type.baseName.isEmpty) { result.add(Error( message: 'Parameters must specify their type in constructor "${constructor.name}" in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, parameter.offset), )); } else { final String? matchingPrefix = _findMatchingPrefixOrNull( parameter.name, prefixes: <String>[ '__pigeon_', 'pigeonChannelCodec', classNamePrefix, classMemberNamePrefix, ], ); if (matchingPrefix != null) { result.add(Error( message: 'Parameter name must not begin with "$matchingPrefix" in constructor "${constructor.name} in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, parameter.offset), )); } } } if (constructor.swiftFunction.isNotEmpty) { final RegExp signatureRegex = RegExp('\\w+ *\\((\\w+:){${constructor.parameters.length}}\\)'); if (!signatureRegex.hasMatch(constructor.swiftFunction)) { result.add(Error( message: 'Invalid constructor signature, expected ${constructor.parameters.length} parameters.', lineNumber: _calculateLineNumberNullable(source, constructor.offset), )); } } } // Validate method parameters for (final Method method in api.methods) { for (final Parameter parameter in method.parameters) { if (isDataClass(parameter)) { result.add(unsupportedDataClassError(parameter)); } final String? matchingPrefix = _findMatchingPrefixOrNull( parameter.name, prefixes: <String>[ classNamePrefix, classMemberNamePrefix, ], ); if (matchingPrefix != null) { result.add(Error( message: 'Parameter name must not begin with "$matchingPrefix" in method "${method.name} in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, parameter.offset), )); } } if (method.location == ApiLocation.flutter && method.isStatic) { result.add(Error( message: 'Static callback methods are not supported: ${method.name}.', lineNumber: _calculateLineNumberNullable(source, method.offset), )); } } // Validate fields for (final ApiField field in api.fields) { if (isDataClass(field)) { result.add(unsupportedDataClassError(field)); } else if (field.isStatic) { if (!isProxyApi(field)) { result.add(Error( message: 'Static fields are considered attached fields and must be a ProxyApi: ${field.type.baseName}', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } else if (field.type.isNullable) { result.add(Error( message: 'Static fields are considered attached fields and must not be nullable: ${field.type.baseName}?', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } } else if (field.isAttached) { if (!isProxyApi(field)) { result.add(Error( message: 'Attached fields must be a ProxyApi: ${field.type.baseName}', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } if (field.type.isNullable) { result.add(Error( message: 'Attached fields must not be nullable: ${field.type.baseName}?', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } } final String? matchingPrefix = _findMatchingPrefixOrNull( field.name, prefixes: <String>[ '__pigeon_', 'pigeonChannelCodec', classNamePrefix, classMemberNamePrefix, ], ); if (matchingPrefix != null) { result.add(Error( message: 'Field name must not begin with "$matchingPrefix" in API: "${api.name}"', lineNumber: _calculateLineNumberNullable(source, field.offset), )); } } return result; } String? _findMatchingPrefixOrNull( String value, { required List<String> prefixes, }) { for (final String prefix in prefixes) { if (value.startsWith(prefix)) { return prefix; } } return null; } class _FindInitializer extends dart_ast_visitor.RecursiveAstVisitor<Object?> { dart_ast.Expression? initializer; @override Object? visitVariableDeclaration(dart_ast.VariableDeclaration node) { if (node.initializer != null) { initializer = node.initializer; } return null; } } class _RootBuilder extends dart_ast_visitor.RecursiveAstVisitor<Object?> { _RootBuilder(this.source); final List<Api> _apis = <Api>[]; final List<Enum> _enums = <Enum>[]; final List<Class> _classes = <Class>[]; final List<Error> _errors = <Error>[]; final String source; Class? _currentClass; Map<String, String> _currentClassDefaultValues = <String, String>{}; Api? _currentApi; Map<String, Object>? _pigeonOptions; void _storeCurrentApi() { if (_currentApi != null) { _apis.add(_currentApi!); _currentApi = null; } } void _storeCurrentClass() { if (_currentClass != null) { _classes.add(_currentClass!); _currentClass = null; _currentClassDefaultValues = <String, String>{}; } } ParseResults results() { _storeCurrentApi(); _storeCurrentClass(); final Map<TypeDeclaration, List<int>> referencedTypes = getReferencedTypes(_apis, _classes); final Set<String> referencedTypeNames = referencedTypes.keys.map((TypeDeclaration e) => e.baseName).toSet(); final List<Class> referencedClasses = List<Class>.from(_classes); referencedClasses .removeWhere((Class x) => !referencedTypeNames.contains(x.name)); final List<Enum> referencedEnums = List<Enum>.from(_enums); final Root completeRoot = Root(apis: _apis, classes: referencedClasses, enums: referencedEnums); final List<Error> validateErrors = _validateAst(completeRoot, source); final List<Error> totalErrors = List<Error>.from(_errors); totalErrors.addAll(validateErrors); for (final MapEntry<TypeDeclaration, List<int>> element in referencedTypes.entries) { if (!referencedClasses .map((Class e) => e.name) .contains(element.key.baseName) && !referencedEnums .map((Enum e) => e.name) .contains(element.key.baseName) && !_apis .whereType<AstProxyApi>() .map((AstProxyApi e) => e.name) .contains(element.key.baseName) && !validTypes.contains(element.key.baseName) && !element.key.isVoid && element.key.baseName != 'dynamic' && element.key.baseName != 'Object' && element.key.baseName.isNotEmpty) { final int? lineNumber = element.value.isEmpty ? null : _calculateLineNumber(source, element.value.first); totalErrors.add(Error( message: 'Unknown type: ${element.key.baseName}', lineNumber: lineNumber)); } } for (final Class classDefinition in referencedClasses) { classDefinition.fields = _attachAssociatedDefinitions( classDefinition.fields, ); } for (final Api api in _apis) { for (final Method func in api.methods) { func.parameters = _attachAssociatedDefinitions(func.parameters); func.returnType = _attachAssociatedDefinition(func.returnType); } if (api is AstProxyApi) { for (final Constructor constructor in api.constructors) { constructor.parameters = _attachAssociatedDefinitions( constructor.parameters, ); } api.fields = _attachAssociatedDefinitions(api.fields); if (api.superClass != null) { api.superClass = _attachAssociatedDefinition(api.superClass!); } final Set<TypeDeclaration> newInterfaceSet = <TypeDeclaration>{}; for (final TypeDeclaration interface in api.interfaces) { newInterfaceSet.add(_attachAssociatedDefinition(interface)); } api.interfaces = newInterfaceSet; } } return ParseResults( root: totalErrors.isEmpty ? completeRoot : Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]), errors: totalErrors, pigeonOptions: _pigeonOptions, ); } TypeDeclaration _attachAssociatedDefinition(TypeDeclaration type) { final Enum? assocEnum = _enums.firstWhereOrNull( (Enum enumDefinition) => enumDefinition.name == type.baseName); final Class? assocClass = _classes.firstWhereOrNull( (Class classDefinition) => classDefinition.name == type.baseName); final AstProxyApi? assocProxyApi = _apis.whereType<AstProxyApi>().firstWhereOrNull( (Api apiDefinition) => apiDefinition.name == type.baseName, ); if (assocClass != null) { return type.copyWithClass(assocClass); } else if (assocEnum != null) { return type.copyWithEnum(assocEnum); } else if (assocProxyApi != null) { return type.copyWithProxyApi(assocProxyApi); } return type; } List<T> _attachAssociatedDefinitions<T extends NamedType>(Iterable<T> types) { final List<T> result = <T>[]; for (final NamedType type in types) { result.add( type.copyWithType(_attachAssociatedDefinition(type.type)) as T, ); } return result; } Object _expressionToMap(dart_ast.Expression expression) { if (expression is dart_ast.MethodInvocation) { final Map<String, Object> result = <String, Object>{}; for (final dart_ast.Expression argument in expression.argumentList.arguments) { if (argument is dart_ast.NamedExpression) { result[argument.name.label.name] = _expressionToMap(argument.expression); } else { _errors.add(Error( message: 'expected NamedExpression but found $expression', lineNumber: _calculateLineNumber(source, argument.offset), )); } } return result; } else if (expression is dart_ast.SimpleStringLiteral) { return expression.value; } else if (expression is dart_ast.IntegerLiteral) { return expression.value!; } else if (expression is dart_ast.BooleanLiteral) { return expression.value; } else if (expression is dart_ast.SimpleIdentifier) { return expression.name; } else if (expression is dart_ast.ListLiteral) { final List<dynamic> list = <dynamic>[]; for (final dart_ast.CollectionElement element in expression.elements) { if (element is dart_ast.Expression) { list.add(_expressionToMap(element)); } else { _errors.add(Error( message: 'expected Expression but found $element', lineNumber: _calculateLineNumber(source, element.offset), )); } } return list; } else if (expression is dart_ast.SetOrMapLiteral) { final Set<dynamic> set = <dynamic>{}; for (final dart_ast.CollectionElement element in expression.elements) { if (element is dart_ast.Expression) { set.add(_expressionToMap(element)); } else { _errors.add(Error( message: 'expected Expression but found $element', lineNumber: _calculateLineNumber(source, element.offset), )); } } return set; } else { _errors.add(Error( message: 'unrecognized expression type ${expression.runtimeType} $expression', lineNumber: _calculateLineNumber(source, expression.offset), )); return 0; } } @override Object? visitImportDirective(dart_ast.ImportDirective node) { if (node.uri.stringValue != 'package:pigeon/pigeon.dart') { _errors.add(Error( message: "Unsupported import ${node.uri}, only imports of 'package:pigeon/pigeon.dart' are supported.", lineNumber: _calculateLineNumber(source, node.offset), )); } return null; } @override Object? visitAnnotation(dart_ast.Annotation node) { if (node.name.name == 'ConfigurePigeon') { if (node.arguments == null) { _errors.add(Error( message: 'ConfigurePigeon expects a PigeonOptions() call.', lineNumber: _calculateLineNumber(source, node.offset), )); } final Map<String, Object> pigeonOptionsMap = _expressionToMap(node.arguments!.arguments.first) as Map<String, Object>; _pigeonOptions = pigeonOptionsMap; } node.visitChildren(this); return null; } @override Object? visitClassDeclaration(dart_ast.ClassDeclaration node) { _storeCurrentApi(); _storeCurrentClass(); if (node.abstractKeyword != null) { if (_hasMetadata(node.metadata, 'HostApi')) { final dart_ast.Annotation hostApi = node.metadata.firstWhere( (dart_ast.Annotation element) => element.name.name == 'HostApi'); String? dartHostTestHandler; if (hostApi.arguments != null) { for (final dart_ast.Expression expression in hostApi.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { if (expression.name.label.name == 'dartHostTestHandler') { final dart_ast.Expression dartHostTestHandlerExpression = expression.expression; if (dartHostTestHandlerExpression is dart_ast.SimpleStringLiteral) { dartHostTestHandler = dartHostTestHandlerExpression.value; } } } } } _currentApi = AstHostApi( name: node.name.lexeme, methods: <Method>[], dartHostTestHandler: dartHostTestHandler, documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } else if (_hasMetadata(node.metadata, 'FlutterApi')) { _currentApi = AstFlutterApi( name: node.name.lexeme, methods: <Method>[], documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } else if (_hasMetadata(node.metadata, 'ProxyApi')) { final dart_ast.Annotation proxyApiAnnotation = node.metadata.firstWhere( (dart_ast.Annotation element) => element.name.name == 'ProxyApi', ); final Map<String, Object?> annotationMap = <String, Object?>{}; for (final dart_ast.Expression expression in proxyApiAnnotation.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { annotationMap[expression.name.label.name] = _expressionToMap(expression.expression); } } final String? superClassName = annotationMap['superClass'] as String?; TypeDeclaration? superClass; if (superClassName != null && node.extendsClause != null) { _errors.add( Error( message: 'ProxyApis should either set the super class in the annotation OR use extends: ("${node.name.lexeme}").', lineNumber: _calculateLineNumber(source, node.offset), ), ); } else if (superClassName != null) { superClass = TypeDeclaration( baseName: superClassName, isNullable: false, ); } else if (node.extendsClause != null) { superClass = TypeDeclaration( baseName: node.extendsClause!.superclass.name2.lexeme, isNullable: false, ); } final Set<TypeDeclaration> interfaces = <TypeDeclaration>{}; if (node.implementsClause != null) { for (final dart_ast.NamedType type in node.implementsClause!.interfaces) { interfaces.add(TypeDeclaration( baseName: type.name2.lexeme, isNullable: false, )); } } _currentApi = AstProxyApi( name: node.name.lexeme, methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], superClass: superClass, interfaces: interfaces, documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } } else { _currentClass = Class( name: node.name.lexeme, fields: <NamedType>[], documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } node.visitChildren(this); return null; } /// Converts Token's to Strings and removes documentation comment symbol. List<String> _documentationCommentsParser(List<Token>? comments) { const String docCommentPrefix = '///'; return comments ?.map((Token line) => line.length > docCommentPrefix.length ? line.toString().substring(docCommentPrefix.length) : '') .toList() ?? <String>[]; } Parameter formalParameterToPigeonParameter( dart_ast.FormalParameter formalParameter, { bool? isNamed, bool? isOptional, bool? isPositional, bool? isRequired, String? defaultValue, }) { final dart_ast.NamedType? parameter = getFirstChildOfType<dart_ast.NamedType>(formalParameter); final dart_ast.SimpleFormalParameter? simpleFormalParameter = getFirstChildOfType<dart_ast.SimpleFormalParameter>(formalParameter); if (parameter != null) { final String argTypeBaseName = _getNamedTypeQualifiedName(parameter); final bool isNullable = parameter.question != null; final List<TypeDeclaration> argTypeArguments = typeAnnotationsToTypeArguments(parameter.typeArguments); return Parameter( type: TypeDeclaration( baseName: argTypeBaseName, isNullable: isNullable, typeArguments: argTypeArguments, ), name: formalParameter.name?.lexeme ?? '', offset: formalParameter.offset, isNamed: isNamed ?? formalParameter.isNamed, isOptional: isOptional ?? formalParameter.isOptional, isPositional: isPositional ?? formalParameter.isPositional, isRequired: isRequired ?? formalParameter.isRequired, defaultValue: defaultValue, ); } else if (simpleFormalParameter != null) { String? defaultValue; if (formalParameter is dart_ast.DefaultFormalParameter) { defaultValue = formalParameter.defaultValue?.toString(); } return formalParameterToPigeonParameter( simpleFormalParameter, isNamed: simpleFormalParameter.isNamed, isOptional: simpleFormalParameter.isOptional, isPositional: simpleFormalParameter.isPositional, isRequired: simpleFormalParameter.isRequired, defaultValue: defaultValue, ); } else { return Parameter( name: '', type: const TypeDeclaration(baseName: '', isNullable: false), offset: formalParameter.offset, ); } } static T? getFirstChildOfType<T>(dart_ast.AstNode entity) { for (final dart_ast_syntactic_entity.SyntacticEntity child in entity.childEntities) { if (child is T) { return child as T; } } return null; } T? _stringToEnum<T>(List<T> values, String? str) { if (str == null) { return null; } for (final T value in values) { if (value.toString() == str) { return value; } } return null; } @override Object? visitMethodDeclaration(dart_ast.MethodDeclaration node) { final dart_ast.FormalParameterList parameters = node.parameters!; final List<Parameter> arguments = parameters.parameters.map(formalParameterToPigeonParameter).toList(); final bool isAsynchronous = _hasMetadata(node.metadata, 'async'); final bool isStatic = _hasMetadata(node.metadata, 'static'); final String objcSelector = _findMetadata(node.metadata, 'ObjCSelector') ?.arguments ?.arguments .first .asNullable<dart_ast.SimpleStringLiteral>() ?.value ?? ''; final String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') ?.arguments ?.arguments .first .asNullable<dart_ast.SimpleStringLiteral>() ?.value ?? ''; final dart_ast.ArgumentList? taskQueueArguments = _findMetadata(node.metadata, 'TaskQueue')?.arguments; final String? taskQueueTypeName = taskQueueArguments == null ? null : getFirstChildOfType<dart_ast.NamedExpression>(taskQueueArguments) ?.expression .asNullable<dart_ast.PrefixedIdentifier>() ?.name; final TaskQueueType taskQueueType = _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? TaskQueueType.serial; if (_currentApi != null) { // Methods without named return types aren't supported. final dart_ast.TypeAnnotation returnType = node.returnType!; returnType as dart_ast.NamedType; _currentApi!.methods.add( Method( name: node.name.lexeme, returnType: TypeDeclaration( baseName: _getNamedTypeQualifiedName(returnType), typeArguments: typeAnnotationsToTypeArguments(returnType.typeArguments), isNullable: returnType.question != null), parameters: arguments, isStatic: isStatic, location: switch (_currentApi!) { AstHostApi() => ApiLocation.host, AstProxyApi() => ApiLocation.host, AstFlutterApi() => ApiLocation.flutter, }, isAsynchronous: isAsynchronous, objcSelector: objcSelector, swiftFunction: swiftFunction, offset: node.offset, taskQueueType: taskQueueType, documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ), ); } else if (_currentClass != null) { _errors.add(Error( message: 'Methods aren\'t supported in Pigeon data classes ("${node.name.lexeme}").', lineNumber: _calculateLineNumber(source, node.offset))); } node.visitChildren(this); return null; } @override Object? visitEnumDeclaration(dart_ast.EnumDeclaration node) { _enums.add(Enum( name: node.name.lexeme, members: node.constants .map((dart_ast.EnumConstantDeclaration e) => EnumMember( name: e.name.lexeme, documentationComments: _documentationCommentsParser( e.documentationComment?.tokens), )) .toList(), documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), )); node.visitChildren(this); return null; } List<TypeDeclaration> typeAnnotationsToTypeArguments( dart_ast.TypeArgumentList? typeArguments) { final List<TypeDeclaration> result = <TypeDeclaration>[]; if (typeArguments != null) { for (final Object x in typeArguments.childEntities) { if (x is dart_ast.NamedType) { result.add(TypeDeclaration( baseName: _getNamedTypeQualifiedName(x), isNullable: x.question != null, typeArguments: typeAnnotationsToTypeArguments(x.typeArguments))); } } } return result; } @override Object? visitFieldDeclaration(dart_ast.FieldDeclaration node) { final dart_ast.TypeAnnotation? type = node.fields.type; if (_currentClass != null) { if (node.isStatic) { _errors.add(Error( message: 'Pigeon doesn\'t support static fields ("$node"), consider using enums.', lineNumber: _calculateLineNumber(source, node.offset))); } else if (type is dart_ast.NamedType) { final _FindInitializer findInitializerVisitor = _FindInitializer(); node.visitChildren(findInitializerVisitor); if (findInitializerVisitor.initializer != null) { _errors.add(Error( message: 'Initialization isn\'t supported for fields in Pigeon data classes ("$node"), just use nullable types with no initializer (example "int? x;").', lineNumber: _calculateLineNumber(source, node.offset))); } else { final dart_ast.TypeArgumentList? typeArguments = type.typeArguments; final String name = node.fields.variables[0].name.lexeme; final NamedType field = NamedType( type: TypeDeclaration( baseName: _getNamedTypeQualifiedName(type), isNullable: type.question != null, typeArguments: typeAnnotationsToTypeArguments(typeArguments), ), name: name, offset: node.offset, defaultValue: _currentClassDefaultValues[name], documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); _currentClass!.fields.add(field); } } else { _errors.add(Error( message: 'Expected a named type but found "$node".', lineNumber: _calculateLineNumber(source, node.offset))); } } else if (_currentApi is AstProxyApi) { _addProxyApiField(type, node); } else if (_currentApi != null) { _errors.add(Error( message: 'Fields aren\'t supported in Pigeon API classes ("$node").', lineNumber: _calculateLineNumber(source, node.offset))); } node.visitChildren(this); return null; } @override Object? visitConstructorDeclaration(dart_ast.ConstructorDeclaration node) { if (_currentApi is AstProxyApi) { final dart_ast.FormalParameterList parameters = node.parameters; final List<Parameter> arguments = parameters.parameters.map(formalParameterToPigeonParameter).toList(); final String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') ?.arguments ?.arguments .first .asNullable<dart_ast.SimpleStringLiteral>() ?.value ?? ''; (_currentApi as AstProxyApi?)!.constructors.add( Constructor( name: node.name?.lexeme ?? '', parameters: arguments, swiftFunction: swiftFunction, offset: node.offset, documentationComments: _documentationCommentsParser( node.documentationComment?.tokens, ), ), ); } else if (_currentApi != null) { _errors.add(Error( message: 'Constructors aren\'t supported in API classes ("$node").', lineNumber: _calculateLineNumber(source, node.offset))); } else { if (node.body.beginToken.lexeme != ';') { _errors.add(Error( message: 'Constructor bodies aren\'t supported in data classes ("$node").', lineNumber: _calculateLineNumber(source, node.offset))); } else if (node.initializers.isNotEmpty) { _errors.add(Error( message: 'Constructor initializers aren\'t supported in data classes (use "this.fieldName") ("$node").', lineNumber: _calculateLineNumber(source, node.offset))); } else { for (final dart_ast.FormalParameter param in node.parameters.parameters) { if (param is dart_ast.DefaultFormalParameter) { if (param.name != null && param.defaultValue != null) { _currentClassDefaultValues[param.name!.toString()] = param.defaultValue!.toString(); } } } } } node.visitChildren(this); return null; } static String _getNamedTypeQualifiedName(dart_ast.NamedType node) { final dart_ast.ImportPrefixReference? importPrefix = node.importPrefix; if (importPrefix != null) { return '${importPrefix.name.lexeme}.${node.name2.lexeme}'; } return node.name2.lexeme; } void _addProxyApiField( dart_ast.TypeAnnotation? type, dart_ast.FieldDeclaration node, ) { final bool isStatic = _hasMetadata(node.metadata, 'static'); if (type is dart_ast.GenericFunctionType) { final List<Parameter> parameters = type.parameters.parameters .map(formalParameterToPigeonParameter) .toList(); final String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') ?.arguments ?.arguments .first .asNullable<dart_ast.SimpleStringLiteral>() ?.value ?? ''; final dart_ast.ArgumentList? taskQueueArguments = _findMetadata(node.metadata, 'TaskQueue')?.arguments; final String? taskQueueTypeName = taskQueueArguments == null ? null : getFirstChildOfType<dart_ast.NamedExpression>(taskQueueArguments) ?.expression .asNullable<dart_ast.PrefixedIdentifier>() ?.name; final TaskQueueType taskQueueType = _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? TaskQueueType.serial; // Methods without named return types aren't supported. final dart_ast.TypeAnnotation returnType = type.returnType!; returnType as dart_ast.NamedType; _currentApi!.methods.add( Method( name: node.fields.variables[0].name.lexeme, returnType: TypeDeclaration( baseName: _getNamedTypeQualifiedName(returnType), typeArguments: typeAnnotationsToTypeArguments(returnType.typeArguments), isNullable: returnType.question != null, ), location: ApiLocation.flutter, isRequired: type.question == null, isStatic: isStatic, parameters: parameters, isAsynchronous: _hasMetadata(node.metadata, 'async'), swiftFunction: swiftFunction, offset: node.offset, taskQueueType: taskQueueType, documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ), ); } else if (type is dart_ast.NamedType) { final _FindInitializer findInitializerVisitor = _FindInitializer(); node.visitChildren(findInitializerVisitor); if (findInitializerVisitor.initializer != null) { _errors.add(Error( message: 'Initialization isn\'t supported for fields in ProxyApis ("$node"), just use nullable types with no initializer (example "int? x;").', lineNumber: _calculateLineNumber(source, node.offset))); } else { final dart_ast.TypeArgumentList? typeArguments = type.typeArguments; (_currentApi as AstProxyApi?)!.fields.add( ApiField( type: TypeDeclaration( baseName: _getNamedTypeQualifiedName(type), isNullable: type.question != null, typeArguments: typeAnnotationsToTypeArguments( typeArguments, ), ), name: node.fields.variables[0].name.lexeme, isAttached: _hasMetadata(node.metadata, 'attached') || isStatic, isStatic: isStatic, offset: node.offset, documentationComments: _documentationCommentsParser( node.documentationComment?.tokens, ), ), ); } } } } int? _calculateLineNumberNullable(String contents, int? offset) { return (offset == null) ? null : _calculateLineNumber(contents, offset); } int _calculateLineNumber(String contents, int offset) { int result = 1; for (int i = 0; i < offset; ++i) { if (contents[i] == '\n') { result += 1; } } return result; } /// Tool for generating code to facilitate platform channels usage. class Pigeon { /// Create and setup a [Pigeon] instance. static Pigeon setup() { return Pigeon(); } /// Reads the file located at [path] and generates [ParseResults] by parsing /// it. [types] optionally filters out what datatypes are actually parsed. /// [sdkPath] for specifying the Dart SDK path for /// [AnalysisContextCollection]. ParseResults parseFile(String inputPath, {String? sdkPath}) { final List<String> includedPaths = <String>[ path.absolute(path.normalize(inputPath)) ]; final AnalysisContextCollection collection = AnalysisContextCollection( includedPaths: includedPaths, sdkPath: sdkPath, ); final List<Error> compilationErrors = <Error>[]; final _RootBuilder rootBuilder = _RootBuilder(File(inputPath).readAsStringSync()); for (final AnalysisContext context in collection.contexts) { for (final String path in context.contextRoot.analyzedFiles()) { final AnalysisSession session = context.currentSession; final ParsedUnitResult result = session.getParsedUnit(path) as ParsedUnitResult; if (result.errors.isEmpty) { final dart_ast.CompilationUnit unit = result.unit; unit.accept(rootBuilder); } else { for (final AnalysisError error in result.errors) { compilationErrors.add(Error( message: error.message, filename: error.source.fullName, lineNumber: _calculateLineNumber( error.source.contents.data, error.offset))); } } } } if (compilationErrors.isEmpty) { return rootBuilder.results(); } else { return ParseResults( root: Root.makeEmpty(), errors: compilationErrors, pigeonOptions: null, ); } } /// String that describes how the tool is used. static String get usage { return ''' Pigeon is a tool for generating type-safe communication code between Flutter and the host platform. usage: pigeon --input <pigeon path> --dart_out <dart path> [option]* options: ${_argParser.usage}'''; } static final ArgParser _argParser = ArgParser() ..addOption('input', help: 'REQUIRED: Path to pigeon file.') ..addOption('dart_out', help: 'Path to generated Dart source file (.dart). ' 'Required if one_language is not specified.') ..addOption('dart_test_out', help: 'Path to generated library for Dart tests, when using ' '@HostApi(dartHostTestHandler:).') ..addOption('objc_source_out', help: 'Path to generated Objective-C source file (.m).') ..addOption('java_out', help: 'Path to generated Java file (.java).') ..addOption('java_package', help: 'The package that generated Java code will be in.') ..addFlag('java_use_generated_annotation', help: 'Adds the java.annotation.Generated annotation to the output.') ..addOption( 'swift_out', help: 'Path to generated Swift file (.swift).', aliases: const <String>['experimental_swift_out'], ) ..addOption( 'kotlin_out', help: 'Path to generated Kotlin file (.kt).', aliases: const <String>['experimental_kotlin_out'], ) ..addOption( 'kotlin_package', help: 'The package that generated Kotlin code will be in.', aliases: const <String>['experimental_kotlin_package'], ) ..addOption( 'cpp_header_out', help: 'Path to generated C++ header file (.h).', aliases: const <String>['experimental_cpp_header_out'], ) ..addOption( 'cpp_source_out', help: 'Path to generated C++ classes file (.cpp).', aliases: const <String>['experimental_cpp_source_out'], ) ..addOption('cpp_namespace', help: 'The namespace that generated C++ code will be in.') ..addOption('objc_header_out', help: 'Path to generated Objective-C header file (.h).') ..addOption('objc_prefix', help: 'Prefix for generated Objective-C classes and protocols.') ..addOption('copyright_header', help: 'Path to file with copyright header to be prepended to generated code.') ..addFlag('one_language', help: 'Allow Pigeon to only generate code for one language.') ..addOption('ast_out', help: 'Path to generated AST debugging info. (Warning: format subject to change)') ..addFlag('debug_generators', help: 'Print the line number of the generator in comments at newlines.') ..addOption('base_path', help: 'A base path to be prefixed to all outputs and copyright header path. Generally used for testing', hide: true) ..addOption('package_name', help: 'The package that generated code will be in.'); /// Convert command-line arguments to [PigeonOptions]. static PigeonOptions parseArgs(List<String> args) { // Note: This function shouldn't perform any logic, just translate the args // to PigeonOptions. Synthesized values inside of the PigeonOption should // get set in the `run` function to accommodate users that are using the // `configurePigeon` function. final ArgResults results = _argParser.parse(args); final PigeonOptions opts = PigeonOptions( input: results['input'] as String?, dartOut: results['dart_out'] as String?, dartTestOut: results['dart_test_out'] as String?, objcHeaderOut: results['objc_header_out'] as String?, objcSourceOut: results['objc_source_out'] as String?, objcOptions: ObjcOptions( prefix: results['objc_prefix'] as String?, ), javaOut: results['java_out'] as String?, javaOptions: JavaOptions( package: results['java_package'] as String?, useGeneratedAnnotation: results['java_use_generated_annotation'] as bool?, ), swiftOut: results['swift_out'] as String?, kotlinOut: results['kotlin_out'] as String?, kotlinOptions: KotlinOptions( package: results['kotlin_package'] as String?, ), cppHeaderOut: results['cpp_header_out'] as String?, cppSourceOut: results['cpp_source_out'] as String?, cppOptions: CppOptions( namespace: results['cpp_namespace'] as String?, ), copyrightHeader: results['copyright_header'] as String?, oneLanguage: results['one_language'] as bool?, astOut: results['ast_out'] as String?, debugGenerators: results['debug_generators'] as bool?, basePath: results['base_path'] as String?, dartPackageName: results['package_name'] as String?, ); return opts; } /// Crawls through the reflection system looking for a configurePigeon method and /// executing it. static void _executeConfigurePigeon(PigeonOptions options) { for (final LibraryMirror library in currentMirrorSystem().libraries.values) { for (final DeclarationMirror declaration in library.declarations.values) { if (declaration is MethodMirror && MirrorSystem.getName(declaration.simpleName) == 'configurePigeon') { if (declaration.parameters.length == 1 && declaration.parameters[0].type == reflectClass(PigeonOptions)) { library.invoke(declaration.simpleName, <dynamic>[options]); } else { print("warning: invalid 'configurePigeon' method defined."); } } } } } /// The 'main' entrypoint used by the command-line tool. [args] are the /// command-line arguments. The optional parameter [adapters] allows you to /// customize the generators that pigeon will use. The optional parameter /// [sdkPath] allows you to specify the Dart SDK path. static Future<int> run(List<String> args, {List<GeneratorAdapter>? adapters, String? sdkPath}) { final PigeonOptions options = Pigeon.parseArgs(args); return runWithOptions(options, adapters: adapters, sdkPath: sdkPath); } /// The 'main' entrypoint used by external packages. [options] is /// used when running the code generator. The optional parameter [adapters] allows you to /// customize the generators that pigeon will use. The optional parameter /// [sdkPath] allows you to specify the Dart SDK path. static Future<int> runWithOptions(PigeonOptions options, {List<GeneratorAdapter>? adapters, String? sdkPath}) async { final Pigeon pigeon = Pigeon.setup(); if (options.debugGenerators ?? false) { generator_tools.debugGenerators = true; } final List<GeneratorAdapter> safeGeneratorAdapters = adapters ?? <GeneratorAdapter>[ DartGeneratorAdapter(), JavaGeneratorAdapter(), SwiftGeneratorAdapter(), KotlinGeneratorAdapter(), CppGeneratorAdapter(), DartTestGeneratorAdapter(), ObjcGeneratorAdapter(), AstGeneratorAdapter(), ]; _executeConfigurePigeon(options); if (options.input == null) { print(usage); return 0; } final ParseResults parseResults = pigeon.parseFile(options.input!, sdkPath: sdkPath); final List<Error> errors = <Error>[]; errors.addAll(parseResults.errors); // Helper to clean up non-Stdout sinks. Future<void> releaseSink(IOSink sink) async { if (sink is! Stdout) { await sink.close(); } } for (final GeneratorAdapter adapter in safeGeneratorAdapters) { final IOSink? sink = adapter.shouldGenerate(options, FileType.source); if (sink != null) { final List<Error> adapterErrors = adapter.validate(options, parseResults.root); errors.addAll(adapterErrors); await releaseSink(sink); } } if (errors.isNotEmpty) { printErrors(errors .map((Error err) => Error( message: err.message, filename: options.input, lineNumber: err.lineNumber)) .toList()); return 1; } if (parseResults.pigeonOptions != null) { options = PigeonOptions.fromMap( mergeMaps(options.toMap(), parseResults.pigeonOptions!)); } if (options.oneLanguage == false && options.dartOut == null) { print(usage); return 1; } if (options.objcHeaderOut != null) { options = options.merge(PigeonOptions( objcOptions: (options.objcOptions ?? const ObjcOptions()).merge( ObjcOptions( headerIncludePath: path.basename(options.objcHeaderOut!))))); } if (options.cppHeaderOut != null) { options = options.merge(PigeonOptions( cppOptions: (options.cppOptions ?? const CppOptions()).merge( CppOptions( headerIncludePath: path.basename(options.cppHeaderOut!))))); } for (final GeneratorAdapter adapter in safeGeneratorAdapters) { for (final FileType fileType in adapter.fileTypeList) { final IOSink? sink = adapter.shouldGenerate(options, fileType); if (sink != null) { adapter.generate(sink, options, parseResults.root, fileType); await sink.flush(); await releaseSink(sink); } } } return 0; } /// Print a list of errors to stderr. static void printErrors(List<Error> errors) { for (final Error err in errors) { if (err.filename != null) { if (err.lineNumber != null) { stderr.writeln( 'Error: ${err.filename}:${err.lineNumber}: ${err.message}'); } else { stderr.writeln('Error: ${err.filename}: ${err.message}'); } } else { stderr.writeln('Error: ${err.message}'); } } } }
packages/packages/pigeon/lib/pigeon_lib.dart/0
{ "file_path": "packages/packages/pigeon/lib/pigeon_lib.dart", "repo_id": "packages", "token_count": 31564 }
1,001
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.alternate_language_test_plugin; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; public class NullFieldsTest { @Test public void builderWithValues() { NullFields.NullFieldsSearchRequest request = new NullFields.NullFieldsSearchRequest.Builder() .setQuery("hello") .setIdentifier(1L) .build(); NullFields.NullFieldsSearchReply reply = new NullFields.NullFieldsSearchReply.Builder() .setResult("result") .setError("error") .setIndices(Arrays.asList(1L, 2L, 3L)) .setRequest(request) .setType(NullFields.NullFieldsSearchReplyType.SUCCESS) .build(); assertEquals(reply.getResult(), "result"); assertEquals(reply.getError(), "error"); assertEquals(reply.getIndices(), Arrays.asList(1L, 2L, 3L)); assertEquals(reply.getRequest().getQuery(), "hello"); assertEquals(reply.getType(), NullFields.NullFieldsSearchReplyType.SUCCESS); } @Test public void builderRequestWithNulls() { NullFields.NullFieldsSearchRequest request = new NullFields.NullFieldsSearchRequest.Builder().setQuery(null).setIdentifier(1L).build(); } @Test public void builderReplyWithNulls() { NullFields.NullFieldsSearchReply reply = new NullFields.NullFieldsSearchReply.Builder() .setResult(null) .setError(null) .setIndices(null) .setRequest(null) .setType(null) .build(); assertNull(reply.getResult()); assertNull(reply.getError()); assertNull(reply.getIndices()); assertNull(reply.getRequest()); assertNull(reply.getType()); } @Test public void requestFromMapWithValues() { ArrayList<Object> list = new ArrayList<Object>(); list.add("hello"); list.add(1L); NullFields.NullFieldsSearchRequest request = NullFields.NullFieldsSearchRequest.fromList(list); assertEquals(request.getQuery(), "hello"); } @Test public void requestFromMapWithNulls() { ArrayList<Object> list = new ArrayList<Object>(); list.add(null); list.add(1L); NullFields.NullFieldsSearchRequest request = NullFields.NullFieldsSearchRequest.fromList(list); assertNull(request.getQuery()); } @Test public void replyFromMapWithValues() { ArrayList<Object> requestList = new ArrayList<Object>(); requestList.add("hello"); requestList.add(1L); ArrayList<Object> list = new ArrayList<Object>(); list.add("result"); list.add("error"); list.add(Arrays.asList(1L, 2L, 3L)); list.add(requestList); list.add(NullFields.NullFieldsSearchReplyType.SUCCESS.ordinal()); NullFields.NullFieldsSearchReply reply = NullFields.NullFieldsSearchReply.fromList(list); assertEquals(reply.getResult(), "result"); assertEquals(reply.getError(), "error"); assertEquals(reply.getIndices(), Arrays.asList(1L, 2L, 3L)); assertEquals(reply.getRequest().getQuery(), "hello"); assertEquals(reply.getType(), NullFields.NullFieldsSearchReplyType.SUCCESS); } @Test public void replyFromMapWithNulls() { ArrayList<Object> list = new ArrayList<Object>(); list.add(null); list.add(null); list.add(null); list.add(null); list.add(null); NullFields.NullFieldsSearchReply reply = NullFields.NullFieldsSearchReply.fromList(list); assertNull(reply.getResult()); assertNull(reply.getError()); assertNull(reply.getIndices()); assertNull(reply.getRequest()); assertNull(reply.getType()); } @Test public void requestToMapWithValues() { NullFields.NullFieldsSearchRequest request = new NullFields.NullFieldsSearchRequest.Builder() .setQuery("hello") .setIdentifier(1L) .build(); ArrayList<Object> list = request.toList(); assertEquals(list.get(0), "hello"); } @Test public void requestToMapWithNulls() { NullFields.NullFieldsSearchRequest request = new NullFields.NullFieldsSearchRequest.Builder().setQuery(null).setIdentifier(1L).build(); ArrayList<Object> list = request.toList(); assertNull(list.get(0)); } @Test public void replyToMapWithValues() { NullFields.NullFieldsSearchReply reply = new NullFields.NullFieldsSearchReply.Builder() .setResult("result") .setError("error") .setIndices(Arrays.asList(1L, 2L, 3L)) .setRequest( new NullFields.NullFieldsSearchRequest.Builder() .setQuery("hello") .setIdentifier(1L) .build()) .setType(NullFields.NullFieldsSearchReplyType.SUCCESS) .build(); ArrayList<Object> list = reply.toList(); assertEquals(list.get(0), "result"); assertEquals(list.get(1), "error"); assertEquals(list.get(2), Arrays.asList(1L, 2L, 3L)); assertEquals(list.get(3), reply.getRequest().toList()); assertEquals(list.get(4), NullFields.NullFieldsSearchReplyType.SUCCESS.ordinal()); } @Test public void replyToMapWithNulls() { NullFields.NullFieldsSearchReply reply = new NullFields.NullFieldsSearchReply.Builder() .setResult(null) .setError(null) .setIndices(null) .setRequest(null) .setType(null) .build(); ArrayList<Object> list = reply.toList(); assertNull(list.get(0)); assertNull(list.get(1)); assertNull(list.get(2)); assertNull(list.get(3)); assertNull(list.get(4)); } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/NullFieldsTest.java/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/NullFieldsTest.java", "repo_id": "packages", "token_count": 2376 }
1,002
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import XCTest; @import alternate_language_test_plugin; @interface ACMessageSearchReply () + (ACMessageSearchReply *)fromList:(NSArray *)list; - (NSArray *)toList; @end @interface RunnerTests : XCTestCase @end @implementation RunnerTests - (void)testToMapAndBack { ACMessageSearchReply *reply = [[ACMessageSearchReply alloc] init]; reply.result = @"foobar"; NSArray *list = [reply toList]; ACMessageSearchReply *copy = [ACMessageSearchReply fromList:list]; XCTAssertEqual(reply.result, copy.result); } - (void)testHandlesNull { ACMessageSearchReply *reply = [[ACMessageSearchReply alloc] init]; reply.result = nil; NSArray *list = [reply toList]; ACMessageSearchReply *copy = [ACMessageSearchReply fromList:list]; XCTAssertNil(copy.result); } - (void)testHandlesNullFirst { ACMessageSearchReply *reply = [[ACMessageSearchReply alloc] init]; reply.error = @"foobar"; NSArray *list = [reply toList]; ACMessageSearchReply *copy = [ACMessageSearchReply fromList:list]; XCTAssertEqual(reply.error, copy.error); } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/RunnerTests.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/RunnerTests.m", "repo_id": "packages", "token_count": 391 }
1,003
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer, immutable, protected; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart' show WidgetsFlutterBinding; PlatformException _createConnectionError(String channelName) { return PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel: "$channelName".', ); } List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } /// An immutable object that serves as the base class for all ProxyApis and /// can provide functional copies of itself. /// /// All implementers are expected to be [immutable] as defined by the annotation /// and override [pigeon_copy] returning an instance of itself. @immutable abstract class PigeonProxyApiBaseClass { /// Construct a [PigeonProxyApiBaseClass]. PigeonProxyApiBaseClass({ this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) : pigeon_instanceManager = pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used, which routes to /// the host platform. @protected final BinaryMessenger? pigeon_binaryMessenger; /// Maintains instances stored to communicate with native language objects. @protected final PigeonInstanceManager pigeon_instanceManager; /// Instantiates and returns a functionally identical object to oneself. /// /// Outside of tests, this method should only ever be called by /// [PigeonInstanceManager]. /// /// Subclasses should always override their parent's implementation of this /// method. @protected PigeonProxyApiBaseClass pigeon_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 PigeonInstanceManager { /// Constructs a [PigeonInstanceManager]. PigeonInstanceManager({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; /// The default [PigeonInstanceManager] used by ProxyApis. /// /// On creation, this manager makes a call to clear the native /// InstanceManager. This is to prevent identifier conflicts after a host /// restart. static final PigeonInstanceManager instance = _initInstance(); // 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<PigeonProxyApiBaseClass>> _weakInstances = <int, WeakReference<PigeonProxyApiBaseClass>>{}; final Map<int, PigeonProxyApiBaseClass> _strongInstances = <int, PigeonProxyApiBaseClass>{}; 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; static PigeonInstanceManager _initInstance() { WidgetsFlutterBinding.ensureInitialized(); final _PigeonInstanceManagerApi api = _PigeonInstanceManagerApi(); // Clears the native `PigeonInstanceManager` on the initial use of the Dart one. api.clear(); final PigeonInstanceManager instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (int identifier) { api.removeStrongReference(identifier); }, ); _PigeonInstanceManagerApi.setUpMessageHandlers( instanceManager: instanceManager); ProxyApiTestClass.pigeon_setUpMessageHandlers( pigeon_instanceManager: instanceManager); ProxyApiSuperClass.pigeon_setUpMessageHandlers( pigeon_instanceManager: instanceManager); ProxyApiInterface.pigeon_setUpMessageHandlers( pigeon_instanceManager: instanceManager); return instanceManager; } /// 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(PigeonProxyApiBaseClass instance) { 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 strong referenced instance associated with /// [instance]. This can be done with [remove]. int? removeWeakReference(PigeonProxyApiBaseClass 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 weak referenced instance associated with /// [identifier]. This can be done with [removeWeakReference]. T? remove<T extends PigeonProxyApiBaseClass>(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 PigeonProxyApiBaseClass>( int identifier) { final PigeonProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; if (weakInstance == null) { final PigeonProxyApiBaseClass? strongInstance = _strongInstances[identifier]; if (strongInstance != null) { final PigeonProxyApiBaseClass copy = strongInstance.pigeon_copy(); _identifiers[copy] = identifier; _weakInstances[identifier] = WeakReference<PigeonProxyApiBaseClass>(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(PigeonProxyApiBaseClass 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( PigeonProxyApiBaseClass instance, int identifier) { _addInstanceWithIdentifier(instance, identifier); } void _addInstanceWithIdentifier( PigeonProxyApiBaseClass instance, int identifier) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); _identifiers[instance] = identifier; _weakInstances[identifier] = WeakReference<PigeonProxyApiBaseClass>(instance); _finalizer.attach(instance, identifier, detach: instance); final PigeonProxyApiBaseClass copy = instance.pigeon_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; } } /// Generated API for managing the Dart and native `PigeonInstanceManager`s. class _PigeonInstanceManagerApi { /// Constructor for [_PigeonInstanceManagerApi]. _PigeonInstanceManagerApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); static void setUpMessageHandlers({ BinaryMessenger? binaryMessenger, PigeonInstanceManager? instanceManager, }) { const String channelName = r'dev.flutter.pigeon.pigeon_integration_tests.PigeonInstanceManagerApi.removeStrongReference'; final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( channelName, pigeonChannelCodec, binaryMessenger: binaryMessenger, ); channel.setMessageHandler((Object? message) async { assert( message != null, 'Argument for $channelName was null.', ); final int? identifier = message as int?; assert( identifier != null, r'Argument for $channelName, expected non-null int.', ); (instanceManager ?? PigeonInstanceManager.instance).remove(identifier!); return; }); } Future<void> removeStrongReference(int identifier) async { const String channelName = r'dev.flutter.pigeon.pigeon_integration_tests.PigeonInstanceManagerApi.removeStrongReference'; final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( channelName, pigeonChannelCodec, binaryMessenger: _binaryMessenger, ); final List<Object?>? replyList = await channel.send(identifier) as List<Object?>?; if (replyList == null) { throw _createConnectionError(channelName); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } /// Clear the native `PigeonInstanceManager`. /// /// This is typically called after a hot restart. Future<void> clear() async { const String channelName = r'dev.flutter.pigeon.pigeon_integration_tests.PigeonInstanceManagerApi.clear'; final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( channelName, pigeonChannelCodec, binaryMessenger: _binaryMessenger, ); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw _createConnectionError(channelName); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } } class _PigeonProxyApiBaseCodec extends StandardMessageCodec { const _PigeonProxyApiBaseCodec(this.instanceManager); final PigeonInstanceManager instanceManager; @override void writeValue(WriteBuffer buffer, Object? value) { if (value is PigeonProxyApiBaseClass) { buffer.putUint8(128); writeValue(buffer, instanceManager.getIdentifier(value)); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return instanceManager .getInstanceWithWeakReference(readValue(buffer)! as int); default: return super.readValueOfType(type, buffer); } } } enum ProxyApiTestEnum { one, two, three, } /// The core ProxyApi test class that each supported host language must /// implement in platform_tests integration tests. class ProxyApiTestClass extends ProxyApiSuperClass implements ProxyApiInterface { ProxyApiTestClass({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, required this.aBool, required this.anInt, required this.aDouble, required this.aString, required this.aUint8List, required this.aList, required this.aMap, required this.anEnum, required this.aProxyApi, this.aNullableBool, this.aNullableInt, this.aNullableDouble, this.aNullableString, this.aNullableUint8List, this.aNullableList, this.aNullableMap, this.aNullableEnum, this.aNullableProxyApi, this.anInterfaceMethod, this.flutterNoop, this.flutterThrowError, this.flutterThrowErrorFromVoid, this.flutterEchoBool, this.flutterEchoInt, this.flutterEchoDouble, this.flutterEchoString, this.flutterEchoUint8List, this.flutterEchoList, this.flutterEchoProxyApiList, this.flutterEchoMap, this.flutterEchoProxyApiMap, this.flutterEchoEnum, this.flutterEchoProxyApi, this.flutterEchoNullableBool, this.flutterEchoNullableInt, this.flutterEchoNullableDouble, this.flutterEchoNullableString, this.flutterEchoNullableUint8List, this.flutterEchoNullableList, this.flutterEchoNullableMap, this.flutterEchoNullableEnum, this.flutterEchoNullableProxyApi, this.flutterNoopAsync, this.flutterEchoAsyncString, required bool boolParam, required int intParam, required double doubleParam, required String stringParam, required Uint8List aUint8ListParam, required List<Object?> listParam, required Map<String?, Object?> mapParam, required ProxyApiTestEnum enumParam, required ProxyApiSuperClass proxyApiParam, bool? nullableBoolParam, int? nullableIntParam, double? nullableDoubleParam, String? nullableStringParam, Uint8List? nullableUint8ListParam, List<Object?>? nullableListParam, Map<String?, Object?>? nullableMapParam, ProxyApiTestEnum? nullableEnumParam, ProxyApiSuperClass? nullableProxyApiParam, }) : super.pigeon_detached() { final int __pigeon_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; () async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_defaultConstructor'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[ __pigeon_instanceIdentifier, aBool, anInt, aDouble, aString, aUint8List, aList, aMap, anEnum.index, aProxyApi, aNullableBool, aNullableInt, aNullableDouble, aNullableString, aNullableUint8List, aNullableList, aNullableMap, aNullableEnum?.index, aNullableProxyApi, boolParam, intParam, doubleParam, stringParam, aUint8ListParam, listParam, mapParam, enumParam.index, proxyApiParam, nullableBoolParam, nullableIntParam, nullableDoubleParam, nullableStringParam, nullableUint8ListParam, nullableListParam, nullableMapParam, nullableEnumParam?.index, nullableProxyApiParam ]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } }(); } /// Constructs [ProxyApiTestClass] without creating the associated native object. /// /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected ProxyApiTestClass.pigeon_detached({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, required this.aBool, required this.anInt, required this.aDouble, required this.aString, required this.aUint8List, required this.aList, required this.aMap, required this.anEnum, required this.aProxyApi, this.aNullableBool, this.aNullableInt, this.aNullableDouble, this.aNullableString, this.aNullableUint8List, this.aNullableList, this.aNullableMap, this.aNullableEnum, this.aNullableProxyApi, this.anInterfaceMethod, this.flutterNoop, this.flutterThrowError, this.flutterThrowErrorFromVoid, this.flutterEchoBool, this.flutterEchoInt, this.flutterEchoDouble, this.flutterEchoString, this.flutterEchoUint8List, this.flutterEchoList, this.flutterEchoProxyApiList, this.flutterEchoMap, this.flutterEchoProxyApiMap, this.flutterEchoEnum, this.flutterEchoProxyApi, this.flutterEchoNullableBool, this.flutterEchoNullableInt, this.flutterEchoNullableDouble, this.flutterEchoNullableString, this.flutterEchoNullableUint8List, this.flutterEchoNullableList, this.flutterEchoNullableMap, this.flutterEchoNullableEnum, this.flutterEchoNullableProxyApi, this.flutterNoopAsync, this.flutterEchoAsyncString, }) : super.pigeon_detached(); late final _PigeonProxyApiBaseCodec __pigeon_codecProxyApiTestClass = _PigeonProxyApiBaseCodec(pigeon_instanceManager); final bool aBool; final int anInt; final double aDouble; final String aString; final Uint8List aUint8List; final List<Object?> aList; final Map<String?, Object?> aMap; final ProxyApiTestEnum anEnum; final ProxyApiSuperClass aProxyApi; final bool? aNullableBool; final int? aNullableInt; final double? aNullableDouble; final String? aNullableString; final Uint8List? aNullableUint8List; final List<Object?>? aNullableList; final Map<String?, Object?>? aNullableMap; final ProxyApiTestEnum? aNullableEnum; final ProxyApiSuperClass? aNullableProxyApi; /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterNoop: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final void Function(ProxyApiTestClass pigeon_instance)? flutterNoop; /// Responds with an error from an async function returning a value. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterThrowError: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError; /// Responds with an error from an async void function. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterThrowErrorFromVoid: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid; /// Returns the passed boolean, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoBool: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final bool Function( ProxyApiTestClass pigeon_instance, bool aBool, )? flutterEchoBool; /// Returns the passed int, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoInt: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final int Function( ProxyApiTestClass pigeon_instance, int anInt, )? flutterEchoInt; /// Returns the passed double, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoDouble: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final double Function( ProxyApiTestClass pigeon_instance, double aDouble, )? flutterEchoDouble; /// Returns the passed string, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoString: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final String Function( ProxyApiTestClass pigeon_instance, String aString, )? flutterEchoString; /// Returns the passed byte list, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoUint8List: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Uint8List Function( ProxyApiTestClass pigeon_instance, Uint8List aList, )? flutterEchoUint8List; /// Returns the passed list, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoList: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final List<Object?> Function( ProxyApiTestClass pigeon_instance, List<Object?> aList, )? flutterEchoList; /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoProxyApiList: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final List<ProxyApiTestClass?> Function( ProxyApiTestClass pigeon_instance, List<ProxyApiTestClass?> aList, )? flutterEchoProxyApiList; /// Returns the passed map, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoMap: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Map<String?, Object?> Function( ProxyApiTestClass pigeon_instance, Map<String?, Object?> aMap, )? flutterEchoMap; /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoProxyApiMap: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Map<String?, ProxyApiTestClass?> Function( ProxyApiTestClass pigeon_instance, Map<String?, ProxyApiTestClass?> aMap, )? flutterEchoProxyApiMap; /// Returns the passed enum to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoEnum: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, )? flutterEchoEnum; /// Returns the passed ProxyApi to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoProxyApi: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, )? flutterEchoProxyApi; /// Returns the passed boolean, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableBool: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final bool? Function( ProxyApiTestClass pigeon_instance, bool? aBool, )? flutterEchoNullableBool; /// Returns the passed int, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableInt: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final int? Function( ProxyApiTestClass pigeon_instance, int? anInt, )? flutterEchoNullableInt; /// Returns the passed double, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableDouble: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final double? Function( ProxyApiTestClass pigeon_instance, double? aDouble, )? flutterEchoNullableDouble; /// Returns the passed string, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableString: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final String? Function( ProxyApiTestClass pigeon_instance, String? aString, )? flutterEchoNullableString; /// Returns the passed byte list, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableUint8List: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Uint8List? Function( ProxyApiTestClass pigeon_instance, Uint8List? aList, )? flutterEchoNullableUint8List; /// Returns the passed list, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableList: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final List<Object?>? Function( ProxyApiTestClass pigeon_instance, List<Object?>? aList, )? flutterEchoNullableList; /// Returns the passed map, to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableMap: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Map<String?, Object?>? Function( ProxyApiTestClass pigeon_instance, Map<String?, Object?>? aMap, )? flutterEchoNullableMap; /// Returns the passed enum to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableEnum: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, )? flutterEchoNullableEnum; /// Returns the passed ProxyApi to test serialization and deserialization. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoNullableProxyApi: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, )? flutterEchoNullableProxyApi; /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterNoopAsync: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Future<void> Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync; /// Returns the passed in generic Object asynchronously. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiTestClass instance = ProxyApiTestClass( /// flutterEchoAsyncString: (ProxyApiTestClass pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final Future<String> Function( ProxyApiTestClass pigeon_instance, String aString, )? flutterEchoAsyncString; @override final void Function(ProxyApiInterface pigeon_instance)? anInterfaceMethod; late final ProxyApiSuperClass attachedField = __pigeon_attachedField(); static final ProxyApiSuperClass staticAttachedField = __pigeon_staticAttachedField(); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, ProxyApiTestClass Function( bool aBool, int anInt, double aDouble, String aString, Uint8List aUint8List, List<Object?> aList, Map<String?, Object?> aMap, ProxyApiTestEnum anEnum, ProxyApiSuperClass aProxyApi, bool? aNullableBool, int? aNullableInt, double? aNullableDouble, String? aNullableString, Uint8List? aNullableUint8List, List<Object?>? aNullableList, Map<String?, Object?>? aNullableMap, ProxyApiTestEnum? aNullableEnum, ProxyApiSuperClass? aNullableProxyApi, )? pigeon_newInstance, void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, bool Function( ProxyApiTestClass pigeon_instance, bool aBool, )? flutterEchoBool, int Function( ProxyApiTestClass pigeon_instance, int anInt, )? flutterEchoInt, double Function( ProxyApiTestClass pigeon_instance, double aDouble, )? flutterEchoDouble, String Function( ProxyApiTestClass pigeon_instance, String aString, )? flutterEchoString, Uint8List Function( ProxyApiTestClass pigeon_instance, Uint8List aList, )? flutterEchoUint8List, List<Object?> Function( ProxyApiTestClass pigeon_instance, List<Object?> aList, )? flutterEchoList, List<ProxyApiTestClass?> Function( ProxyApiTestClass pigeon_instance, List<ProxyApiTestClass?> aList, )? flutterEchoProxyApiList, Map<String?, Object?> Function( ProxyApiTestClass pigeon_instance, Map<String?, Object?> aMap, )? flutterEchoMap, Map<String?, ProxyApiTestClass?> Function( ProxyApiTestClass pigeon_instance, Map<String?, ProxyApiTestClass?> aMap, )? flutterEchoProxyApiMap, ProxyApiTestEnum Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum, )? flutterEchoEnum, ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, )? flutterEchoProxyApi, bool? Function( ProxyApiTestClass pigeon_instance, bool? aBool, )? flutterEchoNullableBool, int? Function( ProxyApiTestClass pigeon_instance, int? anInt, )? flutterEchoNullableInt, double? Function( ProxyApiTestClass pigeon_instance, double? aDouble, )? flutterEchoNullableDouble, String? Function( ProxyApiTestClass pigeon_instance, String? aString, )? flutterEchoNullableString, Uint8List? Function( ProxyApiTestClass pigeon_instance, Uint8List? aList, )? flutterEchoNullableUint8List, List<Object?>? Function( ProxyApiTestClass pigeon_instance, List<Object?>? aList, )? flutterEchoNullableList, Map<String?, Object?>? Function( ProxyApiTestClass pigeon_instance, Map<String?, Object?>? aMap, )? flutterEchoNullableMap, ProxyApiTestEnum? Function( ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum, )? flutterEchoNullableEnum, ProxyApiSuperClass? Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi, )? flutterEchoNullableProxyApi, Future<void> Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, Future<String> Function( ProxyApiTestClass pigeon_instance, String aString, )? flutterEchoAsyncString, }) { final _PigeonProxyApiBaseCodec pigeonChannelCodec = _PigeonProxyApiBaseCodec( pigeon_instanceManager ?? PigeonInstanceManager.instance); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); assert(arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null int.'); final bool? arg_aBool = (args[1] as bool?); assert(arg_aBool != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null bool.'); final int? arg_anInt = (args[2] as int?); assert(arg_anInt != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null int.'); final double? arg_aDouble = (args[3] as double?); assert(arg_aDouble != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null double.'); final String? arg_aString = (args[4] as String?); assert(arg_aString != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null String.'); final Uint8List? arg_aUint8List = (args[5] as Uint8List?); assert(arg_aUint8List != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null Uint8List.'); final List<Object?>? arg_aList = (args[6] as List<Object?>?)?.cast<Object?>(); assert(arg_aList != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null List<Object?>.'); final Map<String?, Object?>? arg_aMap = (args[7] as Map<Object?, Object?>?)?.cast<String?, Object?>(); assert(arg_aMap != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null Map<String?, Object?>.'); final ProxyApiTestEnum? arg_anEnum = args[8] == null ? null : ProxyApiTestEnum.values[args[8]! as int]; assert(arg_anEnum != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null ProxyApiTestEnum.'); final ProxyApiSuperClass? arg_aProxyApi = (args[9] as ProxyApiSuperClass?); assert(arg_aProxyApi != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_newInstance was null, expected non-null ProxyApiSuperClass.'); final bool? arg_aNullableBool = (args[10] as bool?); final int? arg_aNullableInt = (args[11] as int?); final double? arg_aNullableDouble = (args[12] as double?); final String? arg_aNullableString = (args[13] as String?); final Uint8List? arg_aNullableUint8List = (args[14] as Uint8List?); final List<Object?>? arg_aNullableList = (args[15] as List<Object?>?)?.cast<Object?>(); final Map<String?, Object?>? arg_aNullableMap = (args[16] as Map<Object?, Object?>?)?.cast<String?, Object?>(); final ProxyApiTestEnum? arg_aNullableEnum = args[17] == null ? null : ProxyApiTestEnum.values[args[17]! as int]; final ProxyApiSuperClass? arg_aNullableProxyApi = (args[18] as ProxyApiSuperClass?); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( pigeon_newInstance?.call( arg_aBool!, arg_anInt!, arg_aDouble!, arg_aString!, arg_aUint8List!, arg_aList!, arg_aMap!, arg_anEnum!, arg_aProxyApi!, arg_aNullableBool, arg_aNullableInt, arg_aNullableDouble, arg_aNullableString, arg_aNullableUint8List, arg_aNullableList, arg_aNullableMap, arg_aNullableEnum, arg_aNullableProxyApi) ?? ProxyApiTestClass.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, aBool: arg_aBool!, anInt: arg_anInt!, aDouble: arg_aDouble!, aString: arg_aString!, aUint8List: arg_aUint8List!, aList: arg_aList!, aMap: arg_aMap!, anEnum: arg_anEnum!, aProxyApi: arg_aProxyApi!, aNullableBool: arg_aNullableBool, aNullableInt: arg_aNullableInt, aNullableDouble: arg_aNullableDouble, aNullableString: arg_aNullableString, aNullableUint8List: arg_aNullableUint8List, aNullableList: arg_aNullableList, aNullableMap: arg_aNullableMap, aNullableEnum: arg_aNullableEnum, aNullableProxyApi: arg_aNullableProxyApi, ), arg_pigeon_instanceIdentifier!, ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null, expected non-null ProxyApiTestClass.'); try { (flutterNoop ?? arg_pigeon_instance!.flutterNoop) ?.call(arg_pigeon_instance!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null, expected non-null ProxyApiTestClass.'); try { final Object? output = (flutterThrowError ?? arg_pigeon_instance!.flutterThrowError) ?.call(arg_pigeon_instance!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null, expected non-null ProxyApiTestClass.'); try { (flutterThrowErrorFromVoid ?? arg_pigeon_instance!.flutterThrowErrorFromVoid) ?.call(arg_pigeon_instance!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null ProxyApiTestClass.'); final bool? arg_aBool = (args[1] as bool?); assert(arg_aBool != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null bool.'); try { final bool? output = (flutterEchoBool ?? arg_pigeon_instance!.flutterEchoBool) ?.call(arg_pigeon_instance!, arg_aBool!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null ProxyApiTestClass.'); final int? arg_anInt = (args[1] as int?); assert(arg_anInt != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null int.'); try { final int? output = (flutterEchoInt ?? arg_pigeon_instance!.flutterEchoInt) ?.call(arg_pigeon_instance!, arg_anInt!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null ProxyApiTestClass.'); final double? arg_aDouble = (args[1] as double?); assert(arg_aDouble != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null double.'); try { final double? output = (flutterEchoDouble ?? arg_pigeon_instance!.flutterEchoDouble) ?.call(arg_pigeon_instance!, arg_aDouble!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null ProxyApiTestClass.'); final String? arg_aString = (args[1] as String?); assert(arg_aString != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null String.'); try { final String? output = (flutterEchoString ?? arg_pigeon_instance!.flutterEchoString) ?.call(arg_pigeon_instance!, arg_aString!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null ProxyApiTestClass.'); final Uint8List? arg_aList = (args[1] as Uint8List?); assert(arg_aList != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null Uint8List.'); try { final Uint8List? output = (flutterEchoUint8List ?? arg_pigeon_instance!.flutterEchoUint8List) ?.call(arg_pigeon_instance!, arg_aList!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null ProxyApiTestClass.'); final List<Object?>? arg_aList = (args[1] as List<Object?>?)?.cast<Object?>(); assert(arg_aList != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null List<Object?>.'); try { final List<Object?>? output = (flutterEchoList ?? arg_pigeon_instance!.flutterEchoList) ?.call(arg_pigeon_instance!, arg_aList!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null ProxyApiTestClass.'); final List<ProxyApiTestClass?>? arg_aList = (args[1] as List<Object?>?)?.cast<ProxyApiTestClass?>(); assert(arg_aList != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null List<ProxyApiTestClass?>.'); try { final List<ProxyApiTestClass?>? output = (flutterEchoProxyApiList ?? arg_pigeon_instance!.flutterEchoProxyApiList) ?.call(arg_pigeon_instance!, arg_aList!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null ProxyApiTestClass.'); final Map<String?, Object?>? arg_aMap = (args[1] as Map<Object?, Object?>?)?.cast<String?, Object?>(); assert(arg_aMap != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null Map<String?, Object?>.'); try { final Map<String?, Object?>? output = (flutterEchoMap ?? arg_pigeon_instance!.flutterEchoMap) ?.call(arg_pigeon_instance!, arg_aMap!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null ProxyApiTestClass.'); final Map<String?, ProxyApiTestClass?>? arg_aMap = (args[1] as Map<Object?, Object?>?) ?.cast<String?, ProxyApiTestClass?>(); assert(arg_aMap != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null Map<String?, ProxyApiTestClass?>.'); try { final Map<String?, ProxyApiTestClass?>? output = (flutterEchoProxyApiMap ?? arg_pigeon_instance!.flutterEchoProxyApiMap) ?.call(arg_pigeon_instance!, arg_aMap!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestClass.'); final ProxyApiTestEnum? arg_anEnum = args[1] == null ? null : ProxyApiTestEnum.values[args[1]! as int]; assert(arg_anEnum != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestEnum.'); try { final ProxyApiTestEnum? output = (flutterEchoEnum ?? arg_pigeon_instance!.flutterEchoEnum) ?.call(arg_pigeon_instance!, arg_anEnum!); return wrapResponse(result: output?.index); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiTestClass.'); final ProxyApiSuperClass? arg_aProxyApi = (args[1] as ProxyApiSuperClass?); assert(arg_aProxyApi != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiSuperClass.'); try { final ProxyApiSuperClass? output = (flutterEchoProxyApi ?? arg_pigeon_instance!.flutterEchoProxyApi) ?.call(arg_pigeon_instance!, arg_aProxyApi!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null, expected non-null ProxyApiTestClass.'); final bool? arg_aBool = (args[1] as bool?); try { final bool? output = (flutterEchoNullableBool ?? arg_pigeon_instance!.flutterEchoNullableBool) ?.call(arg_pigeon_instance!, arg_aBool); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null, expected non-null ProxyApiTestClass.'); final int? arg_anInt = (args[1] as int?); try { final int? output = (flutterEchoNullableInt ?? arg_pigeon_instance!.flutterEchoNullableInt) ?.call(arg_pigeon_instance!, arg_anInt); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null, expected non-null ProxyApiTestClass.'); final double? arg_aDouble = (args[1] as double?); try { final double? output = (flutterEchoNullableDouble ?? arg_pigeon_instance!.flutterEchoNullableDouble) ?.call(arg_pigeon_instance!, arg_aDouble); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null, expected non-null ProxyApiTestClass.'); final String? arg_aString = (args[1] as String?); try { final String? output = (flutterEchoNullableString ?? arg_pigeon_instance!.flutterEchoNullableString) ?.call(arg_pigeon_instance!, arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null, expected non-null ProxyApiTestClass.'); final Uint8List? arg_aList = (args[1] as Uint8List?); try { final Uint8List? output = (flutterEchoNullableUint8List ?? arg_pigeon_instance!.flutterEchoNullableUint8List) ?.call(arg_pigeon_instance!, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null, expected non-null ProxyApiTestClass.'); final List<Object?>? arg_aList = (args[1] as List<Object?>?)?.cast<Object?>(); try { final List<Object?>? output = (flutterEchoNullableList ?? arg_pigeon_instance!.flutterEchoNullableList) ?.call(arg_pigeon_instance!, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null, expected non-null ProxyApiTestClass.'); final Map<String?, Object?>? arg_aMap = (args[1] as Map<Object?, Object?>?)?.cast<String?, Object?>(); try { final Map<String?, Object?>? output = (flutterEchoNullableMap ?? arg_pigeon_instance!.flutterEchoNullableMap) ?.call(arg_pigeon_instance!, arg_aMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null, expected non-null ProxyApiTestClass.'); final ProxyApiTestEnum? arg_anEnum = args[1] == null ? null : ProxyApiTestEnum.values[args[1]! as int]; try { final ProxyApiTestEnum? output = (flutterEchoNullableEnum ?? arg_pigeon_instance!.flutterEchoNullableEnum) ?.call(arg_pigeon_instance!, arg_anEnum); return wrapResponse(result: output?.index); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null, expected non-null ProxyApiTestClass.'); final ProxyApiSuperClass? arg_aProxyApi = (args[1] as ProxyApiSuperClass?); try { final ProxyApiSuperClass? output = (flutterEchoNullableProxyApi ?? arg_pigeon_instance!.flutterEchoNullableProxyApi) ?.call(arg_pigeon_instance!, arg_aProxyApi); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null, expected non-null ProxyApiTestClass.'); try { await (flutterNoopAsync ?? arg_pigeon_instance!.flutterNoopAsync) ?.call(arg_pigeon_instance!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiTestClass? arg_pigeon_instance = (args[0] as ProxyApiTestClass?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null ProxyApiTestClass.'); final String? arg_aString = (args[1] as String?); assert(arg_aString != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null String.'); try { final String? output = await (flutterEchoAsyncString ?? arg_pigeon_instance!.flutterEchoAsyncString) ?.call(arg_pigeon_instance!, arg_aString!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } ProxyApiSuperClass __pigeon_attachedField() { final ProxyApiSuperClass __pigeon_instance = ProxyApiSuperClass.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ); final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; final int __pigeon_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(__pigeon_instance); () async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.attachedField'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, __pigeon_instanceIdentifier]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } }(); return __pigeon_instance; } static ProxyApiSuperClass __pigeon_staticAttachedField() { final ProxyApiSuperClass __pigeon_instance = ProxyApiSuperClass.pigeon_detached(); final _PigeonProxyApiBaseCodec pigeonChannelCodec = _PigeonProxyApiBaseCodec(PigeonInstanceManager.instance); final BinaryMessenger __pigeon_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; final int __pigeon_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(__pigeon_instance); () async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAttachedField'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[__pigeon_instanceIdentifier]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } }(); return __pigeon_instance; } /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. Future<void> noop() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noop'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } /// Returns an error, to test error handling. Future<Object?> throwError() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwError'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return __pigeon_replyList[0]; } } /// Returns an error from a void function, to test error handling. Future<void> throwErrorFromVoid() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwErrorFromVoid'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } /// Returns a Flutter error, to test error handling. Future<Object?> throwFlutterError() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwFlutterError'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return __pigeon_replyList[0]; } } /// Returns passed in int. Future<int> echoInt(int anInt) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoInt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, anInt]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as int?)!; } } /// Returns passed in double. Future<double> echoDouble(double aDouble) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoDouble'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aDouble]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as double?)!; } } /// Returns the passed in boolean. Future<bool> echoBool(bool aBool) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoBool'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aBool]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as bool?)!; } } /// Returns the passed in string. Future<String> echoString(String aString) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as String?)!; } } /// Returns the passed in Uint8List. Future<Uint8List> echoUint8List(Uint8List aUint8List) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoUint8List'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aUint8List]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Uint8List?)!; } } /// Returns the passed in generic Object. Future<Object> echoObject(Object anObject) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoObject'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anObject]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return __pigeon_replyList[0]!; } } /// Returns the passed list, to test serialization and deserialization. Future<List<Object?>> echoList(List<Object?> aList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as List<Object?>?)!.cast<Object?>(); } } /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. Future<List<ProxyApiTestClass?>> echoProxyApiList( List<ProxyApiTestClass?> aList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as List<Object?>?)! .cast<ProxyApiTestClass?>(); } } /// Returns the passed map, to test serialization and deserialization. Future<Map<String?, Object?>> echoMap(Map<String?, Object?> aMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?)! .cast<String?, Object?>(); } } /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. Future<Map<String?, ProxyApiTestClass?>> echoProxyApiMap( Map<String?, ProxyApiTestClass?> aMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?)! .cast<String?, ProxyApiTestClass?>(); } } /// Returns the passed enum to test serialization and deserialization. Future<ProxyApiTestEnum> echoEnum(ProxyApiTestEnum anEnum) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoEnum'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anEnum.index]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return ProxyApiTestEnum.values[__pigeon_replyList[0]! as int]; } } /// Returns the passed ProxyApi to test serialization and deserialization. Future<ProxyApiSuperClass> echoProxyApi(ProxyApiSuperClass aProxyApi) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApi'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aProxyApi]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as ProxyApiSuperClass?)!; } } /// Returns passed in int. Future<int?> echoNullableInt(int? aNullableInt) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableInt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableInt]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as int?); } } /// Returns passed in double. Future<double?> echoNullableDouble(double? aNullableDouble) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableDouble'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableDouble]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as double?); } } /// Returns the passed in boolean. Future<bool?> echoNullableBool(bool? aNullableBool) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableBool'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableBool]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as bool?); } } /// Returns the passed in string. Future<String?> echoNullableString(String? aNullableString) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as String?); } } /// Returns the passed in Uint8List. Future<Uint8List?> echoNullableUint8List( Uint8List? aNullableUint8List) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableUint8List'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableUint8List]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as Uint8List?); } } /// Returns the passed in generic Object. Future<Object?> echoNullableObject(Object? aNullableObject) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableObject'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableObject]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return __pigeon_replyList[0]; } } /// Returns the passed list, to test serialization and deserialization. Future<List<Object?>?> echoNullableList(List<Object?>? aNullableList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as List<Object?>?)?.cast<Object?>(); } } /// Returns the passed map, to test serialization and deserialization. Future<Map<String?, Object?>?> echoNullableMap( Map<String?, Object?>? aNullableMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?) ?.cast<String?, Object?>(); } } Future<ProxyApiTestEnum?> echoNullableEnum( ProxyApiTestEnum? aNullableEnum) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableEnum'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableEnum?.index]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as int?) == null ? null : ProxyApiTestEnum.values[__pigeon_replyList[0]! as int]; } } /// Returns the passed ProxyApi to test serialization and deserialization. Future<ProxyApiSuperClass?> echoNullableProxyApi( ProxyApiSuperClass? aNullableProxyApi) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableProxyApi'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aNullableProxyApi]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as ProxyApiSuperClass?); } } /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. Future<void> noopAsync() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noopAsync'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } /// Returns passed in int asynchronously. Future<int> echoAsyncInt(int anInt) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncInt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, anInt]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as int?)!; } } /// Returns passed in double asynchronously. Future<double> echoAsyncDouble(double aDouble) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncDouble'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aDouble]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as double?)!; } } /// Returns the passed in boolean asynchronously. Future<bool> echoAsyncBool(bool aBool) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncBool'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aBool]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as bool?)!; } } /// Returns the passed string asynchronously. Future<String> echoAsyncString(String aString) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as String?)!; } } /// Returns the passed in Uint8List asynchronously. Future<Uint8List> echoAsyncUint8List(Uint8List aUint8List) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncUint8List'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aUint8List]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Uint8List?)!; } } /// Returns the passed in generic Object asynchronously. Future<Object> echoAsyncObject(Object anObject) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncObject'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anObject]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return __pigeon_replyList[0]!; } } /// Returns the passed list, to test asynchronous serialization and deserialization. Future<List<Object?>> echoAsyncList(List<Object?> aList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as List<Object?>?)!.cast<Object?>(); } } /// Returns the passed map, to test asynchronous serialization and deserialization. Future<Map<String?, Object?>> echoAsyncMap(Map<String?, Object?> aMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?)! .cast<String?, Object?>(); } } /// Returns the passed enum, to test asynchronous serialization and deserialization. Future<ProxyApiTestEnum> echoAsyncEnum(ProxyApiTestEnum anEnum) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncEnum'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anEnum.index]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return ProxyApiTestEnum.values[__pigeon_replyList[0]! as int]; } } /// Responds with an error from an async function returning a value. Future<Object?> throwAsyncError() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncError'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return __pigeon_replyList[0]; } } /// Responds with an error from an async void function. Future<void> throwAsyncErrorFromVoid() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncErrorFromVoid'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } /// Responds with a Flutter error from an async function returning a value. Future<Object?> throwAsyncFlutterError() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncFlutterError'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return __pigeon_replyList[0]; } } /// Returns passed in int asynchronously. Future<int?> echoAsyncNullableInt(int? anInt) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableInt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, anInt]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as int?); } } /// Returns passed in double asynchronously. Future<double?> echoAsyncNullableDouble(double? aDouble) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableDouble'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aDouble]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as double?); } } /// Returns the passed in boolean asynchronously. Future<bool?> echoAsyncNullableBool(bool? aBool) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableBool'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aBool]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as bool?); } } /// Returns the passed string asynchronously. Future<String?> echoAsyncNullableString(String? aString) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as String?); } } /// Returns the passed in Uint8List asynchronously. Future<Uint8List?> echoAsyncNullableUint8List(Uint8List? aUint8List) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableUint8List'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aUint8List]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as Uint8List?); } } /// Returns the passed in generic Object asynchronously. Future<Object?> echoAsyncNullableObject(Object? anObject) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableObject'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anObject]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return __pigeon_replyList[0]; } } /// Returns the passed list, to test asynchronous serialization and deserialization. Future<List<Object?>?> echoAsyncNullableList(List<Object?>? aList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as List<Object?>?)?.cast<Object?>(); } } /// Returns the passed map, to test asynchronous serialization and deserialization. Future<Map<String?, Object?>?> echoAsyncNullableMap( Map<String?, Object?>? aMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?) ?.cast<String?, Object?>(); } } /// Returns the passed enum, to test asynchronous serialization and deserialization. Future<ProxyApiTestEnum?> echoAsyncNullableEnum( ProxyApiTestEnum? anEnum) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableEnum'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anEnum?.index]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as int?) == null ? null : ProxyApiTestEnum.values[__pigeon_replyList[0]! as int]; } } static Future<void> staticNoop({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = _PigeonProxyApiBaseCodec( pigeon_instanceManager ?? PigeonInstanceManager.instance); final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticNoop'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } static Future<String> echoStaticString( String aString, { BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = _PigeonProxyApiBaseCodec( pigeon_instanceManager ?? PigeonInstanceManager.instance); final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoStaticString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[aString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as String?)!; } } static Future<void> staticAsyncNoop({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, }) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = _PigeonProxyApiBaseCodec( pigeon_instanceManager ?? PigeonInstanceManager.instance); final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAsyncNoop'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<void> callFlutterNoop() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoop'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<Object?> callFlutterThrowError() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowError'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return __pigeon_replyList[0]; } } Future<void> callFlutterThrowErrorFromVoid() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowErrorFromVoid'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<bool> callFlutterEchoBool(bool aBool) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoBool'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aBool]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as bool?)!; } } Future<int> callFlutterEchoInt(int anInt) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoInt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, anInt]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as int?)!; } } Future<double> callFlutterEchoDouble(double aDouble) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoDouble'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aDouble]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as double?)!; } } Future<String> callFlutterEchoString(String aString) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as String?)!; } } Future<Uint8List> callFlutterEchoUint8List(Uint8List aUint8List) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoUint8List'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aUint8List]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Uint8List?)!; } } Future<List<Object?>> callFlutterEchoList(List<Object?> aList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as List<Object?>?)!.cast<Object?>(); } } Future<List<ProxyApiTestClass?>> callFlutterEchoProxyApiList( List<ProxyApiTestClass?> aList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as List<Object?>?)! .cast<ProxyApiTestClass?>(); } } Future<Map<String?, Object?>> callFlutterEchoMap( Map<String?, Object?> aMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?)! .cast<String?, Object?>(); } } Future<Map<String?, ProxyApiTestClass?>> callFlutterEchoProxyApiMap( Map<String?, ProxyApiTestClass?> aMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?)! .cast<String?, ProxyApiTestClass?>(); } } Future<ProxyApiTestEnum> callFlutterEchoEnum(ProxyApiTestEnum anEnum) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoEnum'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anEnum.index]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return ProxyApiTestEnum.values[__pigeon_replyList[0]! as int]; } } Future<ProxyApiSuperClass> callFlutterEchoProxyApi( ProxyApiSuperClass aProxyApi) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApi'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aProxyApi]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as ProxyApiSuperClass?)!; } } Future<bool?> callFlutterEchoNullableBool(bool? aBool) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableBool'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aBool]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as bool?); } } Future<int?> callFlutterEchoNullableInt(int? anInt) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableInt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, anInt]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as int?); } } Future<double?> callFlutterEchoNullableDouble(double? aDouble) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableDouble'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aDouble]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as double?); } } Future<String?> callFlutterEchoNullableString(String? aString) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as String?); } } Future<Uint8List?> callFlutterEchoNullableUint8List( Uint8List? aUint8List) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableUint8List'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aUint8List]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as Uint8List?); } } Future<List<Object?>?> callFlutterEchoNullableList( List<Object?>? aList) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aList]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as List<Object?>?)?.cast<Object?>(); } } Future<Map<String?, Object?>?> callFlutterEchoNullableMap( Map<String?, Object?>? aMap) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aMap]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as Map<Object?, Object?>?) ?.cast<String?, Object?>(); } } Future<ProxyApiTestEnum?> callFlutterEchoNullableEnum( ProxyApiTestEnum? anEnum) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableEnum'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, anEnum?.index]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as int?) == null ? null : ProxyApiTestEnum.values[__pigeon_replyList[0]! as int]; } } Future<ProxyApiSuperClass?> callFlutterEchoNullableProxyApi( ProxyApiSuperClass? aProxyApi) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableProxyApi'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[this, aProxyApi]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as ProxyApiSuperClass?); } } Future<void> callFlutterNoopAsync() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoopAsync'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } Future<String> callFlutterEchoAsyncString(String aString) async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiTestClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoAsyncString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this, aString]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as String?)!; } } @override ProxyApiTestClass pigeon_copy() { return ProxyApiTestClass.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, aBool: aBool, anInt: anInt, aDouble: aDouble, aString: aString, aUint8List: aUint8List, aList: aList, aMap: aMap, anEnum: anEnum, aProxyApi: aProxyApi, aNullableBool: aNullableBool, aNullableInt: aNullableInt, aNullableDouble: aNullableDouble, aNullableString: aNullableString, aNullableUint8List: aNullableUint8List, aNullableList: aNullableList, aNullableMap: aNullableMap, aNullableEnum: aNullableEnum, aNullableProxyApi: aNullableProxyApi, anInterfaceMethod: anInterfaceMethod, flutterNoop: flutterNoop, flutterThrowError: flutterThrowError, flutterThrowErrorFromVoid: flutterThrowErrorFromVoid, flutterEchoBool: flutterEchoBool, flutterEchoInt: flutterEchoInt, flutterEchoDouble: flutterEchoDouble, flutterEchoString: flutterEchoString, flutterEchoUint8List: flutterEchoUint8List, flutterEchoList: flutterEchoList, flutterEchoProxyApiList: flutterEchoProxyApiList, flutterEchoMap: flutterEchoMap, flutterEchoProxyApiMap: flutterEchoProxyApiMap, flutterEchoEnum: flutterEchoEnum, flutterEchoProxyApi: flutterEchoProxyApi, flutterEchoNullableBool: flutterEchoNullableBool, flutterEchoNullableInt: flutterEchoNullableInt, flutterEchoNullableDouble: flutterEchoNullableDouble, flutterEchoNullableString: flutterEchoNullableString, flutterEchoNullableUint8List: flutterEchoNullableUint8List, flutterEchoNullableList: flutterEchoNullableList, flutterEchoNullableMap: flutterEchoNullableMap, flutterEchoNullableEnum: flutterEchoNullableEnum, flutterEchoNullableProxyApi: flutterEchoNullableProxyApi, flutterNoopAsync: flutterNoopAsync, flutterEchoAsyncString: flutterEchoAsyncString, ); } } /// ProxyApi to serve as a super class to the core ProxyApi class. class ProxyApiSuperClass extends PigeonProxyApiBaseClass { ProxyApiSuperClass({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, }) { final int __pigeon_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiSuperClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; () async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_defaultConstructor'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel .send(<Object?>[__pigeon_instanceIdentifier]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } }(); } /// Constructs [ProxyApiSuperClass] without creating the associated native object. /// /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected ProxyApiSuperClass.pigeon_detached({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, }); late final _PigeonProxyApiBaseCodec __pigeon_codecProxyApiSuperClass = _PigeonProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, ProxyApiSuperClass Function()? pigeon_newInstance, }) { final _PigeonProxyApiBaseCodec pigeonChannelCodec = _PigeonProxyApiBaseCodec( pigeon_instanceManager ?? PigeonInstanceManager.instance); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); assert(arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance was null, expected non-null int.'); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( pigeon_newInstance?.call() ?? ProxyApiSuperClass.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ), arg_pigeon_instanceIdentifier!, ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } Future<void> aSuperMethod() async { final _PigeonProxyApiBaseCodec pigeonChannelCodec = __pigeon_codecProxyApiSuperClass; final BinaryMessenger? __pigeon_binaryMessenger = pigeon_binaryMessenger; const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.aSuperMethod'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[this]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } @override ProxyApiSuperClass pigeon_copy() { return ProxyApiSuperClass.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ); } } /// ProxyApi to serve as an interface to the core ProxyApi class. class ProxyApiInterface extends PigeonProxyApiBaseClass { /// Constructs [ProxyApiInterface] without creating the associated native object. /// /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected ProxyApiInterface.pigeon_detached({ super.pigeon_binaryMessenger, super.pigeon_instanceManager, this.anInterfaceMethod, }); /// Callback method. /// /// For the associated Native object to be automatically garbage collected, /// it is required that the implementation of this `Function` doesn't have a /// strong reference to the encapsulating class instance. When this `Function` /// references a non-local variable, it is strongly recommended to access it /// with a `WeakReference`: /// /// ```dart /// final WeakReference weakMyVariable = WeakReference(myVariable); /// final ProxyApiInterface instance = ProxyApiInterface( /// anInterfaceMethod: (ProxyApiInterface pigeon_instance, ...) { /// print(weakMyVariable?.target); /// }, /// ); /// ``` /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. final void Function(ProxyApiInterface pigeon_instance)? anInterfaceMethod; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, ProxyApiInterface Function()? pigeon_newInstance, void Function(ProxyApiInterface pigeon_instance)? anInterfaceMethod, }) { final _PigeonProxyApiBaseCodec pigeonChannelCodec = _PigeonProxyApiBaseCodec( pigeon_instanceManager ?? PigeonInstanceManager.instance); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_pigeon_instanceIdentifier = (args[0] as int?); assert(arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance was null, expected non-null int.'); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( pigeon_newInstance?.call() ?? ProxyApiInterface.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ), arg_pigeon_instanceIdentifier!, ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null.'); final List<Object?> args = (message as List<Object?>?)!; final ProxyApiInterface? arg_pigeon_instance = (args[0] as ProxyApiInterface?); assert(arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null, expected non-null ProxyApiInterface.'); try { (anInterfaceMethod ?? arg_pigeon_instance!.anInterfaceMethod) ?.call(arg_pigeon_instance!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } @override ProxyApiInterface pigeon_copy() { return ProxyApiInterface.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, anInterfaceMethod: anInterfaceMethod, ); } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart", "repo_id": "packages", "token_count": 83615 }
1,004
# This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled. version: revision: c7d11549a51eb37807604bdfd1141a82be8fac4b channel: main project_type: plugin # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b base_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b - platform: android create_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b base_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b - platform: ios create_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b base_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b - platform: macos create_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b base_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b - platform: windows create_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b base_revision: c7d11549a51eb37807604bdfd1141a82be8fac4b # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj'
packages/packages/pigeon/platform_tests/test_plugin/.metadata/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/.metadata", "repo_id": "packages", "token_count": 576 }
1,005
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.test_plugin import io.flutter.plugin.common.BinaryMessenger import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import junit.framework.TestCase import org.junit.Test class NullableReturnsTest : TestCase() { @Test fun testNullableParameterHost() { val binaryMessenger = mockk<BinaryMessenger>(relaxed = true) val api = mockk<NullableReturnHostApi>(relaxed = true) val output = 1L val channelName = "dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit" val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>() every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit every { api.doit() } returns output NullableReturnHostApi.setUp(binaryMessenger, api) val codec = PrimitiveHostApi.codec val message = codec.encodeMessage(null) message?.rewind() handlerSlot.captured.onMessage(message) { it?.rewind() @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>? assertNotNull(wrapped) wrapped?.let { assertEquals(output, wrapped[0]) } } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { api.doit() } } @Test fun testNullableParameterFlutter() { val binaryMessenger = mockk<BinaryMessenger>() val api = NullableReturnFlutterApi(binaryMessenger) val output = 12L every { binaryMessenger.send(any(), any(), any()) } answers { val codec = NullableReturnFlutterApi.codec val reply = arg<BinaryMessenger.BinaryReply>(2) val replyData = codec.encodeMessage(listOf(output)) replyData?.position(0) reply.reply(replyData) } var didCall = false api.doit { didCall = true assertEquals(output, it.getOrNull()) } assertTrue(didCall) } }
packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NullableReturnsTest.kt/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NullableReturnsTest.kt", "repo_id": "packages", "token_count": 775 }
1,006
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter import Foundation class EchoBinaryMessenger: NSObject, FlutterBinaryMessenger { let codec: FlutterMessageCodec private(set) var count = 0 var defaultReturn: Any? init(codec: FlutterMessageCodec) { self.codec = codec super.init() } func send(onChannel channel: String, message: Data?) { // Method not implemented because this messenger is just for echoing } func send( onChannel channel: String, message: Data?, binaryReply callback: FlutterBinaryReply? = nil ) { guard let callback = callback else { return } guard let args = self.codec.decode(message) as? [Any?], let firstArg = args.first, let castedFirstArg: Any? = nilOrValue(firstArg) else { callback(self.defaultReturn.flatMap { self.codec.encode([$0]) }) return } callback(self.codec.encode([castedFirstArg])) } func setMessageHandlerOnChannel( _ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler? = nil ) -> FlutterBinaryMessengerConnection { self.count += 1 return FlutterBinaryMessengerConnection(self.count) } func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) { // Method not implemented because this messenger is just for echoing } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return (value as Any) as! T? } }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EchoBinaryMessenger.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EchoBinaryMessenger.swift", "repo_id": "packages", "token_count": 526 }
1,007
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint test_plugin.podspec` to validate before publishing. # Pod::Spec.new do |s| s.name = 'test_plugin' s.version = '0.0.1' s.summary = 'Pigeon test plugin' s.description = <<-DESC A plugin to test Pigeon generation for primary languages. DESC s.homepage = 'http://example.com' s.license = { :type => 'BSD', :file => '../../../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/pigeon' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' s.platform = :ios, '12.0' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift', 'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift', } # Flutter.framework does not contain a i386 slice. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } s.swift_version = '5.0' end
packages/packages/pigeon/platform_tests/test_plugin/ios/test_plugin.podspec/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/ios/test_plugin.podspec", "repo_id": "packages", "token_count": 526 }
1,008
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtest/gtest.h> #include <optional> #include "pigeon/nullable_returns.gen.h" #include "test/utils/fake_host_messenger.h" namespace nullable_returns_pigeontest { namespace { using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; using testing::FakeHostMessenger; class TestNullableArgHostApi : public NullableArgHostApi { public: TestNullableArgHostApi() {} virtual ~TestNullableArgHostApi() {} protected: ErrorOr<int64_t> Doit(const int64_t* x) override { return x == nullptr ? 42 : *x; } }; class TestNullableReturnHostApi : public NullableReturnHostApi { public: TestNullableReturnHostApi(std::optional<int64_t> return_value) : value_(return_value) {} virtual ~TestNullableReturnHostApi() {} protected: ErrorOr<std::optional<int64_t>> Doit() override { return value_; } private: std::optional<int64_t> value_; }; const EncodableValue& GetResult(const EncodableValue& pigeon_response) { return std::get<EncodableList>(pigeon_response)[0]; } } // namespace TEST(NullableReturns, HostNullableArgNull) { FakeHostMessenger messenger(&NullableArgHostApi::GetCodec()); TestNullableArgHostApi api; NullableArgHostApi::SetUp(&messenger, &api); int64_t result = 0; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit", EncodableValue(EncodableList({EncodableValue()})), [&result](const EncodableValue& reply) { result = GetResult(reply).LongValue(); }); EXPECT_EQ(result, 42); } TEST(NullableReturns, HostNullableArgNonNull) { FakeHostMessenger messenger(&NullableArgHostApi::GetCodec()); TestNullableArgHostApi api; NullableArgHostApi::SetUp(&messenger, &api); int64_t result = 0; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit", EncodableValue(EncodableList({EncodableValue(7)})), [&result](const EncodableValue& reply) { result = GetResult(reply).LongValue(); }); EXPECT_EQ(result, 7); } TEST(NullableReturns, HostNullableReturnNull) { FakeHostMessenger messenger(&NullableReturnHostApi::GetCodec()); TestNullableReturnHostApi api(std::nullopt); NullableReturnHostApi::SetUp(&messenger, &api); // Initialize to a non-null value to ensure that it's actually set to null, // rather than just never set. EncodableValue result(true); messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit", EncodableValue(EncodableList({})), [&result](const EncodableValue& reply) { result = GetResult(reply); }); EXPECT_TRUE(result.IsNull()); } TEST(NullableReturns, HostNullableReturnNonNull) { FakeHostMessenger messenger(&NullableReturnHostApi::GetCodec()); TestNullableReturnHostApi api(42); NullableReturnHostApi::SetUp(&messenger, &api); EncodableValue result; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit", EncodableValue(EncodableList({})), [&result](const EncodableValue& reply) { result = GetResult(reply); }); EXPECT_FALSE(result.IsNull()); EXPECT_EQ(result.LongValue(), 42); } // TODO(stuartmorgan): Add FlutterApi versions of the tests. } // namespace nullable_returns_pigeontest
packages/packages/pigeon/platform_tests/test_plugin/windows/test/nullable_returns_test.cpp/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/nullable_returns_test.cpp", "repo_id": "packages", "token_count": 1252 }
1,009
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/ast.dart'; import 'package:pigeon/generator_tools.dart'; import 'package:test/test.dart'; bool _equalSet<T>(Set<T> x, Set<T> y) { if (x.length != y.length) { return false; } for (final T object in x) { if (!y.contains(object)) { return false; } } return true; } bool _equalMaps(Map<String, Object> x, Map<String, Object> y) { if (!_equalSet(x.keys.toSet(), y.keys.toSet())) { return false; } for (final String key in x.keys) { final Object xValue = x[key]!; if (xValue is Map<String, Object>) { if (!_equalMaps(xValue, (y[key] as Map<String, Object>?)!)) { return false; } } else { if (xValue != y[key]) { return false; } } } return true; } final Class emptyClass = Class(name: 'className', fields: <NamedType>[ NamedType( name: 'namedTypeName', type: const TypeDeclaration(baseName: 'baseName', isNullable: false), ) ]); final Enum emptyEnum = Enum( name: 'enumName', members: <EnumMember>[EnumMember(name: 'enumMemberName')], ); void main() { test('test merge maps', () { final Map<String, Object> source = <String, Object>{ '1': '1', '2': <String, Object>{ '1': '1', '3': '3', }, '3': '3', // not modified }; final Map<String, Object> modification = <String, Object>{ '1': '2', // modify '2': <String, Object>{ '2': '2', // added }, }; final Map<String, Object> expected = <String, Object>{ '1': '2', '2': <String, Object>{ '1': '1', '2': '2', '3': '3', }, '3': '3', }; expect(_equalMaps(expected, mergeMaps(source, modification)), isTrue); }); test('get codec classes from argument type arguments', () { final AstFlutterApi api = AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[ TypeDeclaration( baseName: 'Input', isNullable: true, associatedClass: emptyClass, ) ], ), name: '', ) ], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), isAsynchronous: true, ) ]); final Root root = Root(classes: <Class>[], apis: <Api>[api], enums: <Enum>[]); final List<EnumeratedClass> classes = getCodecClasses(api, root).toList(); expect(classes.length, 2); expect( classes .where((EnumeratedClass element) => element.name == 'Input') .length, 1); expect( classes .where((EnumeratedClass element) => element.name == 'Output') .length, 1); }); test('get codec classes from return value type arguments', () { final AstFlutterApi api = AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), name: '', ) ], returnType: TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[ TypeDeclaration( baseName: 'Input', isNullable: true, associatedClass: emptyClass, ) ], ), isAsynchronous: true, ) ]); final Root root = Root(classes: <Class>[], apis: <Api>[api], enums: <Enum>[]); final List<EnumeratedClass> classes = getCodecClasses(api, root).toList(); expect(classes.length, 2); expect( classes .where((EnumeratedClass element) => element.name == 'Input') .length, 1); expect( classes .where((EnumeratedClass element) => element.name == 'Output') .length, 1); }); test('get codec classes from all arguments', () { final AstFlutterApi api = AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Foo', isNullable: false, associatedClass: emptyClass, ), name: '', ), Parameter( type: TypeDeclaration( baseName: 'Bar', isNullable: false, associatedEnum: emptyEnum, ), name: '', ), ], returnType: const TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[TypeDeclaration.voidDeclaration()], ), isAsynchronous: true, ) ]); final Root root = Root(classes: <Class>[], apis: <Api>[api], enums: <Enum>[]); final List<EnumeratedClass> classes = getCodecClasses(api, root).toList(); expect(classes.length, 2); expect( classes .where((EnumeratedClass element) => element.name == 'Foo') .length, 1); expect( classes .where((EnumeratedClass element) => element.name == 'Bar') .length, 1); }); test('getCodecClasses: nested type arguments', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'foo', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( name: 'x', type: TypeDeclaration( isNullable: false, baseName: 'List', typeArguments: <TypeDeclaration>[ TypeDeclaration( baseName: 'Foo', isNullable: true, associatedClass: emptyClass, ) ])), ], returnType: const TypeDeclaration.voidDeclaration(), ) ]) ], classes: <Class>[ Class(name: 'Foo', fields: <NamedType>[ NamedType( name: 'bar', type: TypeDeclaration( baseName: 'Bar', isNullable: true, associatedClass: emptyClass, )), ]), Class(name: 'Bar', fields: <NamedType>[ NamedType( name: 'value', type: const TypeDeclaration( baseName: 'int', isNullable: true, )) ]) ], enums: <Enum>[]); final List<EnumeratedClass> classes = getCodecClasses(root.apis[0], root).toList(); expect(classes.length, 2); expect( classes .where((EnumeratedClass element) => element.name == 'Foo') .length, 1); expect( classes .where((EnumeratedClass element) => element.name == 'Bar') .length, 1); }); test('getCodecClasses: with Object', () { final Root root = Root(apis: <Api>[ AstFlutterApi( name: 'Api1', methods: <Method>[ Method( name: 'foo', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( name: 'x', type: const TypeDeclaration( isNullable: false, baseName: 'List', typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'Object', isNullable: true) ])), ], returnType: const TypeDeclaration.voidDeclaration(), ) ], ), ], classes: <Class>[ Class(name: 'Foo', fields: <NamedType>[ NamedType( name: 'bar', type: const TypeDeclaration(baseName: 'int', isNullable: true)), ]), ], enums: <Enum>[]); final List<EnumeratedClass> classes = getCodecClasses(root.apis[0], root).toList(); expect(classes.length, 1); expect( classes .where((EnumeratedClass element) => element.name == 'Foo') .length, 1); }); test('getCodecClasses: unique entries', () { final Root root = Root(apis: <Api>[ AstFlutterApi( name: 'Api1', methods: <Method>[ Method( name: 'foo', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( name: 'x', type: TypeDeclaration( isNullable: false, baseName: 'Foo', associatedClass: emptyClass, )), ], returnType: const TypeDeclaration.voidDeclaration(), ) ], ), AstHostApi( name: 'Api2', methods: <Method>[ Method( name: 'foo', location: ApiLocation.host, parameters: <Parameter>[ Parameter( name: 'x', type: TypeDeclaration( isNullable: false, baseName: 'Foo', associatedClass: emptyClass, )), ], returnType: const TypeDeclaration.voidDeclaration(), ) ], ) ], classes: <Class>[ Class(name: 'Foo', fields: <NamedType>[ NamedType( name: 'bar', type: const TypeDeclaration(baseName: 'int', isNullable: true)), ]), ], enums: <Enum>[]); final List<EnumeratedClass> classes = getCodecClasses(root.apis[0], root).toList(); expect(classes.length, 1); expect( classes .where((EnumeratedClass element) => element.name == 'Foo') .length, 1); }); test('deduces package name successfully', () { final String? dartPackageName = deducePackageName('./pigeons/core_tests.dart'); expect(dartPackageName, 'pigeon'); }); test('recursiveGetSuperClassApisChain', () { final AstProxyApi superClassOfSuperClassApi = AstProxyApi( name: 'Api3', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], ); final AstProxyApi superClassApi = AstProxyApi( name: 'Api2', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], superClass: TypeDeclaration( baseName: 'Api3', isNullable: false, associatedProxyApi: superClassOfSuperClassApi, ), ); final AstProxyApi api = AstProxyApi( name: 'Api', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], superClass: TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: superClassApi, ), ); expect( api.allSuperClasses().toList(), containsAllInOrder(<AstProxyApi>[ superClassApi, superClassOfSuperClassApi, ]), ); }); test('recursiveFindAllInterfacesApis', () { final AstProxyApi interfaceOfInterfaceApi2 = AstProxyApi( name: 'Api5', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], ); final AstProxyApi interfaceOfInterfaceApi = AstProxyApi( name: 'Api4', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], ); final AstProxyApi interfaceApi2 = AstProxyApi( name: 'Api3', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], interfaces: <TypeDeclaration>{ TypeDeclaration( baseName: 'Api5', isNullable: false, associatedProxyApi: interfaceOfInterfaceApi2, ), }, ); final AstProxyApi interfaceApi = AstProxyApi( name: 'Api2', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], interfaces: <TypeDeclaration>{ TypeDeclaration( baseName: 'Api4', isNullable: false, associatedProxyApi: interfaceOfInterfaceApi, ), TypeDeclaration( baseName: 'Api5', isNullable: false, associatedProxyApi: interfaceOfInterfaceApi2, ), }, ); final AstProxyApi api = AstProxyApi( name: 'Api', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], interfaces: <TypeDeclaration>{ TypeDeclaration( baseName: 'Api2', isNullable: false, associatedProxyApi: interfaceApi, ), TypeDeclaration( baseName: 'Api3', isNullable: false, associatedProxyApi: interfaceApi2, ), }, ); expect( api.apisOfInterfaces(), containsAll(<AstProxyApi>[ interfaceApi, interfaceApi2, interfaceOfInterfaceApi, interfaceOfInterfaceApi2, ]), ); }); test( 'recursiveFindAllInterfacesApis throws error if api recursively implements itself', () { final AstProxyApi a = AstProxyApi( name: 'A', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], ); final AstProxyApi b = AstProxyApi( name: 'B', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], ); final AstProxyApi c = AstProxyApi( name: 'C', methods: <Method>[], constructors: <Constructor>[], fields: <ApiField>[], ); a.interfaces = <TypeDeclaration>{ TypeDeclaration(baseName: 'B', isNullable: false, associatedProxyApi: b), }; b.interfaces = <TypeDeclaration>{ TypeDeclaration(baseName: 'C', isNullable: false, associatedProxyApi: c), }; c.interfaces = <TypeDeclaration>{ TypeDeclaration(baseName: 'A', isNullable: false, associatedProxyApi: a), }; expect(() => a.apisOfInterfaces(), throwsArgumentError); }); }
packages/packages/pigeon/test/generator_tools_test.dart/0
{ "file_path": "packages/packages/pigeon/test/generator_tools_test.dart", "repo_id": "packages", "token_count": 7328 }
1,010
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print //////////////////////////////////////////////////////////////////////////////// /// Script for executing the Pigeon tests /// /// usage: dart run tool/test.dart //////////////////////////////////////////////////////////////////////////////// library; import 'dart:io' show Platform, exit; import 'dart:math'; import 'package:args/args.dart'; import 'shared/test_runner.dart'; import 'shared/test_suites.dart'; const String _testFlag = 'test'; const String _noGen = 'no-generation'; const String _listFlag = 'list'; const String _format = 'format'; Future<void> main(List<String> args) async { final ArgParser parser = ArgParser() ..addMultiOption(_testFlag, abbr: 't', help: 'Only run specified tests.') ..addFlag(_noGen, abbr: 'g', help: 'Skips the generation step.', negatable: false) ..addFlag(_format, abbr: 'f', help: 'Formats generated test files before running tests.') ..addFlag(_listFlag, negatable: false, abbr: 'l', help: 'List available tests.') ..addFlag('help', negatable: false, abbr: 'h', help: 'Print this reference.'); final ArgResults argResults = parser.parse(args); List<String> testsToRun = <String>[]; if (argResults.wasParsed(_listFlag)) { print('available tests:'); final int columnWidth = testSuites.keys.map((String key) => key.length).reduce(max) + 4; for (final MapEntry<String, TestInfo> info in testSuites.entries) { print('${info.key.padRight(columnWidth)}- ${info.value.description}'); } exit(0); } else if (argResults.wasParsed('help')) { print(''' Pigeon run_tests usage: dart run tool/test.dart [-l | -t <test name>] ${parser.usage}'''); exit(0); } else if (argResults.wasParsed(_testFlag)) { testsToRun = argResults[_testFlag] as List<String>; } // If no tests are provided, run everything that is supported on the current // platform. if (testsToRun.isEmpty) { const List<String> dartTests = <String>[ dartUnitTests, flutterUnitTests, commandLineTests, ]; const List<String> androidTests = <String>[ androidJavaUnitTests, androidKotlinUnitTests, androidJavaIntegrationTests, androidKotlinIntegrationTests, androidJavaLint, ]; const List<String> iOSTests = <String>[ iOSObjCUnitTests, iOSObjCIntegrationTests, iOSSwiftUnitTests, iOSSwiftIntegrationTests, ]; const List<String> macOSTests = <String>[ macOSObjCIntegrationTests, macOSSwiftUnitTests, macOSSwiftIntegrationTests ]; const List<String> windowsTests = <String>[ windowsUnitTests, windowsIntegrationTests, ]; if (Platform.isMacOS) { testsToRun = <String>[ ...dartTests, ...androidTests, ...iOSTests, ...macOSTests, ]; } else if (Platform.isWindows) { testsToRun = <String>[ ...dartTests, ...windowsTests, ]; } else if (Platform.isLinux) { testsToRun = <String>[ ...dartTests, ...androidTests, ]; } else { print('Unsupported host platform.'); exit(1); } } await runTests( testsToRun, runGeneration: !argResults.wasParsed(_noGen), runFormat: argResults.wasParsed(_format), ); }
packages/packages/pigeon/tool/test.dart/0
{ "file_path": "packages/packages/pigeon/tool/test.dart", "repo_id": "packages", "token_count": 1328 }
1,011
#include "Generated.xcconfig"
packages/packages/platform/example/ios/Flutter/Release.xcconfig/0
{ "file_path": "packages/packages/platform/example/ios/Flutter/Release.xcconfig", "repo_id": "packages", "token_count": 12 }
1,012
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 2.1.8 * Fixes new lint warnings. ## 2.1.7 * Changes `MockPlatformInterfaceMixin` to a `mixin class` for better compatibility with projects that have a minumum Dart SDK version of 3.0. * Updates minimum supported SDK version to Dart 3.0. ## 2.1.6 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.1.5 * Updates README to improve example and discuss `base`. * Updates minimum Flutter version to 3.3. ## 2.1.4 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum supported Dart version. ## 2.1.3 * Minor fixes for new analysis options. * Adds additional tests for `PlatformInterface` and `MockPlatformInterfaceMixin`. * Modifies `PlatformInterface` to use an expando for detecting if a customer tries to implement PlatformInterface using `implements` rather than `extends`. This ensures that `verify` will continue to work as advertized after https://github.com/dart-lang/language/issues/2020 is implemented. ## 2.1.2 * Updates README to demonstrate `verify` rather than `verifyToken`, and to note that the test mixin applies to fakes as well as mocks. * Adds an additional test for `verifyToken`. ## 2.1.1 * Fixes `verify` to work with fake objects, not just mocks. ## 2.1.0 * Introduce `verify`, which prevents use of `const Object()` as instance token. * Add a comment indicating that `verifyToken` will be deprecated in a future release. ## 2.0.2 * Update package description. ## 2.0.1 * Fix `federated flutter plugins` link in the README.md. ## 2.0.0 * Migrate to null safety. ## 1.0.3 * Fix homepage in `pubspec.yaml`. ## 1.0.2 * Make the pedantic dev_dependency explicit. ## 1.0.1 * Fixed a bug that made all platform interfaces appear as mocks in release builds (https://github.com/flutter/flutter/issues/46941). ## 1.0.0 - Initial release. * Provides `PlatformInterface` with common mechanism for enforcing that a platform interface is not implemented with `implements`. * Provides test only `MockPlatformInterface` to enable using Mockito to mock platform interfaces.
packages/packages/plugin_platform_interface/CHANGELOG.md/0
{ "file_path": "packages/packages/plugin_platform_interface/CHANGELOG.md", "repo_id": "packages", "token_count": 664 }
1,013
# pointer_interceptor_example An example for the PointerInterceptor widget. ## Getting Started `flutter run -d chrome` to run the sample. You can tweak some code in the `lib/main.dart`, but be careful, changes there can break integration tests! ## Running tests `flutter drive --target integration_test/widget_test.dart --driver test_driver/integration_test.dart --show-web-server-device -d web-server --web-renderer=html` The command above will run the integration tests for this package. Make sure that you have `chromedriver` running in port `4444`. Read more on: [flutter.dev > Docs > Testing & debugging > Integration testing](https://flutter.dev/docs/testing/integration-tests).
packages/packages/pointer_interceptor/pointer_interceptor/example/README.md/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor/example/README.md", "repo_id": "packages", "token_count": 194 }
1,014
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter class PointerInterceptorFactory: NSObject, FlutterPlatformViewFactory { func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView { let debug = (args as? [String: Any])?["debug"] as? Bool ?? false return PointerInterceptorView(frame: frame, debug: debug) } public func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol { return FlutterStandardMessageCodec.sharedInstance() } }
packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/Classes/PointerInterceptorFactory.swift/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/Classes/PointerInterceptorFactory.swift", "repo_id": "packages", "token_count": 191 }
1,015
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('Default implementation of PointerInterceptor does not do anything', () { final PointerInterceptorPlatform defaultPointerInterceptor = PointerInterceptorPlatform.instance; final Container testChild = Container(); expect(defaultPointerInterceptor.buildWidget(child: testChild), testChild); }); }
packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/default_pointer_interceptor_test.dart/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/default_pointer_interceptor_test.dart", "repo_id": "packages", "token_count": 211 }
1,016
name: process description: A pluggable, mockable process invocation abstraction for Dart. repository: https://github.com/flutter/packages/tree/main/packages/process issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+process%22 version: 5.0.2 environment: sdk: ^3.1.0 dependencies: file: '>=6.0.0 <8.0.0' path: ^1.8.0 platform: '^3.0.0' dev_dependencies: test: ^1.16.8 topics: - process
packages/packages/process/pubspec.yaml/0
{ "file_path": "packages/packages/process/pubspec.yaml", "repo_id": "packages", "token_count": 186 }
1,017
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/quick_actions/quick_actions_android/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,018
## NEXT * Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6. ## 1.0.10 * Adds privacy manifest. ## 1.0.9 * Updates minimum required plugin_platform_interface version to 2.1.7. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 1.0.8 * Changes method channels to pigeon. ## 1.0.7 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 1.0.6 * Removes obsolete null checks on non-nullable values. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 1.0.5 * Updates minimum iOS version to 11 and Flutter version to 3.3. ## 1.0.4 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 1.0.3 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 1.0.2 * Migrates remaining components to Swift and removes all Objective-C settings. * Migrates `RunnerUITests` to Swift. ## 1.0.1 * Removes custom modulemap file with "Test" submodule and private headers for Swift migration. * Migrates `FLTQuickActionsPlugin` class to Swift. ## 1.0.0 * Updates version to 1.0 to reflect current status. * Updates minimum Flutter version to 2.10. ## 0.6.0+14 * Refactors `FLTQuickActionsPlugin` class into multiple components. * Increases unit tests coverage to 100%. ## 0.6.0+13 * Adds some unit tests for `FLTQuickActionsPlugin` class. ## 0.6.0+12 * Adds a custom module map with a Test submodule for unit tests on iOS platform. ## 0.6.0+11 * Updates references to the obsolete master branch. ## 0.6.0+10 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.6.0+9 * Switches to a package-internal implementation of the platform interface.
packages/packages/quick_actions/quick_actions_ios/CHANGELOG.md/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/CHANGELOG.md", "repo_id": "packages", "token_count": 597 }
1,019
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'quick_actions_ios' s.version = '0.0.1' s.summary = 'Flutter Quick Actions' s.description = <<-DESC This Flutter plugin allows you to manage and interact with the application's home screen quick actions. Downloaded by pub (not CocoaPods). DESC s.homepage = 'https://github.com/flutter/packages' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/quick_actions' } s.documentation_url = 'https://pub.dev/packages/quick_actions' s.swift_version = '5.0' s.source_files = 'Classes/**/*.swift' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift', 'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift', } s.dependency 'Flutter' s.platform = :ios, '12.0' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.resource_bundles = {'quick_actions_ios_privacy' => ['Resources/PrivacyInfo.xcprivacy']} end
packages/packages/quick_actions/quick_actions_ios/ios/quick_actions_ios.podspec/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/ios/quick_actions_ios.podspec", "repo_id": "packages", "token_count": 558 }
1,020
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/rfw/example/hello/android/gradle.properties/0
{ "file_path": "packages/packages/rfw/example/hello/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
1,021
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is hand-formatted. import 'dart:io'; import 'package:rfw/formats.dart'; void main() { final String counterApp1 = File('counter_app1.rfwtxt').readAsStringSync(); File('counter_app1.rfw').writeAsBytesSync(encodeLibraryBlob(parseLibraryFile(counterApp1))); final String counterApp2 = File('counter_app2.rfwtxt').readAsStringSync(); File('counter_app2.rfw').writeAsBytesSync(encodeLibraryBlob(parseLibraryFile(counterApp2))); }
packages/packages/rfw/example/remote/remote_widget_libraries/encode.dart/0
{ "file_path": "packages/packages/rfw/example/remote/remote_widget_libraries/encode.dart", "repo_id": "packages", "token_count": 196 }
1,022
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // There's a lot of <Object>[] lists in this file so to avoid making this // file even less readable we relax our usual stance on verbose typing. // ignore_for_file: always_specify_types // This file is hand-formatted. import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'argument_decoders.dart'; import 'runtime.dart'; /// A widget library for Remote Flutter Widgets that defines widgets that are /// implemented on the client in terms of Flutter widgets from the `material` /// Dart library. /// /// The following widgets are implemented: /// /// * [AboutListTile] /// * [AppBar] /// * [ButtonBar] /// * [Card] /// * [CircularProgressIndicator] /// * [Divider] /// * [DrawerHeader] /// * [DropdownButton] /// * [ElevatedButton] /// * [FloatingActionButton] /// * [InkResponse] /// * [InkWell] /// * [LinearProgressIndicator] /// * [ListTile] /// * [Material] /// * [OutlinedButton] /// * [Scaffold] /// * [TextButton] /// * [VerticalDivider] /// * [OverflowBar] /// /// For each, every parameter is implemented using the same name. Parameters /// that take structured types are represented using maps, with each named /// parameter of that type's default constructor represented by a key. The /// conventions edscribed for [createCoreWidgets] are reused here. /// /// In addition, the following conventions are introduced: /// /// * Hero tags are always strings. /// /// * [VisualDensity] is represented in the manner described in the documentation /// of the [ArgumentDecoders.visualDensity] method. /// /// Some features have changed in the underlying Flutter's material library and are /// therefore no longer supported, including: /// /// * The [ButtonBar] widget in the Flutter's material library is planned to be /// deprecated in favor of the [OverflowBar] widget. The [ButtonBar] widget in /// `rfw` package uses the [OverflowBar] widget internally for backward compatibility. /// The [ButtonBar] widget in `rfw` package is not deprecated and will continue to /// be supported. As a result, the following [ButtonBar] parameters are no longer /// supported: /// /// * `buttonMinWidth` /// * `buttonHeight` /// * `buttonAlignedDropdown` /// /// It is recommended to use the [OverflowBar] widget. /// /// Some features are not supported: /// /// * [AppBar]s do not support [AppBar.bottom], [AppBar.flexibleSpace], and /// related properties. Also, [AppBar.systemOverlayStyle] is not suported. /// /// * Theming in general is not currently supported. /// /// * Properties whose values are [Animation]s or based on /// [MaterialStateProperty] are not supported. /// /// * Features related to focus or configuring mouse support are not /// implemented. /// /// * Callbacks such as [Scafford.onDrawerChanged] are not exposed. /// /// * The [Scaffold]'s floating action button position and animation features /// are not supported. /// /// * [DropdownButton] takes a `items` object which contains a list of /// [DropdownMenuItem] configuration objects. Each object may contain /// `onTap`, `value`, `enabled` and `child`. The `child` parameter is /// required. /// /// In general, the trend will all of these unsupported features is that this /// library doesn't support features that can't be trivially expressed using the /// JSON-like structures of RFW. For example, [MaterialStateProperty] is /// designed to be used with code to select the values, which doesn't work well /// in the RFW structure. LocalWidgetLibrary createMaterialWidgets() => LocalWidgetLibrary(_materialWidgetsDefinitions); Map<String, LocalWidgetBuilder> get _materialWidgetsDefinitions => <String, LocalWidgetBuilder>{ // Keep these in alphabetical order. 'AboutListTile': (BuildContext context, DataSource source) { return AboutListTile( icon: source.optionalChild(['icon']), applicationName: source.v<String>(['applicationName']), applicationVersion: source.v<String>(['applicationVersion']), applicationIcon: source.optionalChild(['applicationIcon']), applicationLegalese: source.v<String>(['applicationLegalese']), aboutBoxChildren: source.childList(['aboutBoxChildren']), dense: source.v<bool>(['dense']), child: source.optionalChild(['child']), ); }, 'AppBar': (BuildContext context, DataSource source) { // not implemented: bottom (and bottomOpacity), flexibleSpace; systemOverlayStyle return AppBar( leading: source.optionalChild(['leading']), automaticallyImplyLeading: source.v<bool>(['automaticallyImplyLeading']) ?? true, title: source.optionalChild(['title']), actions: source.childList(['actions']), elevation: source.v<double>(['elevation']), shadowColor: ArgumentDecoders.color(source, ['shadowColor']), shape: ArgumentDecoders.shapeBorder(source, ['shape']), backgroundColor: ArgumentDecoders.color(source, ['backgroundColor']), foregroundColor: ArgumentDecoders.color(source, ['foregroundColor']), iconTheme: ArgumentDecoders.iconThemeData(source, ['iconTheme']), actionsIconTheme: ArgumentDecoders.iconThemeData(source, ['actionsIconTheme']), primary: source.v<bool>(['primary']) ?? true, centerTitle: source.v<bool>(['centerTitle']), excludeHeaderSemantics: source.v<bool>(['excludeHeaderSemantics']) ?? false, titleSpacing: source.v<double>(['titleSpacing']), toolbarOpacity: source.v<double>(['toolbarOpacity']) ?? 1.0, toolbarHeight: source.v<double>(['toolbarHeight']), leadingWidth: source.v<double>(['leadingWidth']), toolbarTextStyle: ArgumentDecoders.textStyle(source, ['toolbarTextStyle']), titleTextStyle: ArgumentDecoders.textStyle(source, ['titleTextStyle']), ); }, // The [ButtonBar] widget in Flutter's material library is planned to be deprecated // in favor of the [OverflowBar] widget. This [ButtonBar] implementation uses the // [OverflowBar] widget internally for backward compatibility. The [ButtonBar] // widget in `rfw` package is not deprecated and will continue to be supported. // // The [ButtonBar] widget in Flutter's material library has changed over time. // The following parameters are no longer supported: // - `buttonMinWidth` // - `buttonHeight` // - `buttonAlignedDropdown` // // It is recommended to use the [OverflowBar] widget. 'ButtonBar': (BuildContext context, DataSource source) { final EdgeInsetsGeometry buttonPadding = ArgumentDecoders.edgeInsets(source, ['buttonPadding']) ?? const EdgeInsets.all(8.0); final ButtonBarLayoutBehavior layoutBehavior = ArgumentDecoders.enumValue<ButtonBarLayoutBehavior>(ButtonBarLayoutBehavior.values, source, ['layoutBehavior']) ?? ButtonBarLayoutBehavior.padded; Widget overflowBar = OverflowBar( alignment: ArgumentDecoders.enumValue<MainAxisAlignment>(MainAxisAlignment.values, source, ['alignment']) ?? MainAxisAlignment.start, spacing: buttonPadding.horizontal / 2, overflowDirection: ArgumentDecoders.enumValue<VerticalDirection>(VerticalDirection.values, source, ['overflowDirection']) ?? VerticalDirection.down, overflowSpacing: source.v<double>(['overflowButtonSpacing']) ?? 0.0, children: source.childList(['children']), ); switch (layoutBehavior) { case ButtonBarLayoutBehavior.padded: overflowBar = Padding( padding: EdgeInsets.symmetric( vertical: 2.0 * (buttonPadding.horizontal / 4.0), horizontal: buttonPadding.horizontal / 2.0, ), child: overflowBar, ); case ButtonBarLayoutBehavior.constrained: overflowBar = Container( padding: EdgeInsets.symmetric(horizontal: buttonPadding.horizontal / 2.0), constraints: const BoxConstraints(minHeight: 52.0), alignment: Alignment.center, child: overflowBar, ); } if (ArgumentDecoders.enumValue<MainAxisSize>(MainAxisSize.values, source, ['mainAxisSize']) == MainAxisSize.min) { return IntrinsicWidth(child: overflowBar); } return overflowBar; }, 'OverflowBar': (BuildContext context, DataSource source) { return OverflowBar( spacing: source.v<double>(['spacing']) ?? 0.0, alignment: ArgumentDecoders.enumValue<MainAxisAlignment>(MainAxisAlignment.values, source, ['alignment']), overflowSpacing: source.v<double>(['overflowSpacing']) ?? 0.0, overflowAlignment: ArgumentDecoders.enumValue<OverflowBarAlignment>(OverflowBarAlignment.values, source, ['overflowAlignment']) ?? OverflowBarAlignment.start, overflowDirection: ArgumentDecoders.enumValue<VerticalDirection>(VerticalDirection.values, source, ['overflowDirection']) ?? VerticalDirection.down, textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), children: source.childList(['children']), ); }, 'Card': (BuildContext context, DataSource source) { return Card( color: ArgumentDecoders.color(source, ['color']), shadowColor: ArgumentDecoders.color(source, ['shadowColor']), elevation: source.v<double>(['elevation']), shape: ArgumentDecoders.shapeBorder(source, ['shape']), borderOnForeground: source.v<bool>(['borderOnForeground']) ?? true, margin: ArgumentDecoders.edgeInsets(source, ['margin']), clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, semanticContainer: source.v<bool>(['semanticContainer']) ?? true, child: source.optionalChild(['child']), ); }, 'CircularProgressIndicator': (BuildContext context, DataSource source) { // not implemented: valueColor return CircularProgressIndicator( value: source.v<double>(['value']), color: ArgumentDecoders.color(source, ['color']), backgroundColor: ArgumentDecoders.color(source, ['backgroundColor']), strokeWidth: source.v<double>(['strokeWidth']) ?? 4.0, semanticsLabel: source.v<String>(['semanticsLabel']), semanticsValue: source.v<String>(['semanticsValue']), ); }, 'Divider': (BuildContext context, DataSource source) { return Divider( height: source.v<double>(['height']), thickness: source.v<double>(['thickness']), indent: source.v<double>(['indent']), endIndent: source.v<double>(['endIndent']), color: ArgumentDecoders.color(source, ['color']), ); }, 'Drawer': (BuildContext context, DataSource source) { return Drawer( elevation: source.v<double>(['elevation']) ?? 16.0, semanticLabel: source.v<String>(['semanticLabel']), child: source.optionalChild(['child']), ); }, 'DrawerHeader': (BuildContext context, DataSource source) { return DrawerHeader( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), decoration: ArgumentDecoders.decoration(source, ['decoration']), margin: ArgumentDecoders.edgeInsets(source, ['margin']) ?? const EdgeInsets.only(bottom: 8.0), padding: ArgumentDecoders.edgeInsets(source, ['padding']) ?? const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 8.0), child: source.optionalChild(['child']), ); }, 'DropdownButton': (BuildContext context, DataSource source) { final int length = source.length(['items']); final List<DropdownMenuItem<Object>> dropdownMenuItems = List<DropdownMenuItem<Object>>.generate( length, (int index) => DropdownMenuItem<Object>( onTap: source.voidHandler(['items', index, 'onTap']), value: source.v<String>(['items', index, 'value']) ?? source.v<int>(['items', index, 'value']) ?? source.v<double>(['items', index, 'value']) ?? source.v<bool>(['items', index, 'value']), enabled: source.v<bool>(['items', index, 'enabled']) ?? true, alignment: ArgumentDecoders.alignment(source, ['items', index, 'alignment']) ?? AlignmentDirectional.centerStart, child: source.child(['items', index, 'child']), ), ); return DropdownButton<Object>( items: dropdownMenuItems, value: source.v<String>(['value']) ?? source.v<int>(['value']) ?? source.v<double>(['value']) ?? source.v<bool>(['value']), disabledHint: source.optionalChild(['disabledHint']), onChanged: source.handler(<Object>['onChanged'], (HandlerTrigger trigger) => (Object? value) => trigger(<String, Object?>{'value': value})), onTap: source.voidHandler(['onTap']), elevation: source.v<int>(['elevation']) ?? 8, style: ArgumentDecoders.textStyle(source, ['style']), underline: source.optionalChild(['underline']), icon: source.optionalChild(['icon']), iconDisabledColor: ArgumentDecoders.color(source, ['iconDisabledColor']), iconEnabledColor: ArgumentDecoders.color(source, ['iconEnabledColor']), iconSize: source.v<double>(['iconSize']) ?? 24.0, isDense: source.v<bool>(['isDense']) ?? false, isExpanded: source.v<bool>(['isExpanded']) ?? false, itemHeight: source.v<double>(['itemHeight']) ?? kMinInteractiveDimension, focusColor: ArgumentDecoders.color(source, ['focusColor']), autofocus: source.v<bool>(['autofocus']) ?? false, dropdownColor: ArgumentDecoders.color(source, ['dropdownColor']), menuMaxHeight: source.v<double>(['menuMaxHeight']), enableFeedback: source.v<bool>(['enableFeedback']), alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? AlignmentDirectional.centerStart, borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius'])?.resolve(Directionality.of(context)), padding: ArgumentDecoders.edgeInsets(source, ['padding']), ); }, 'ElevatedButton': (BuildContext context, DataSource source) { // not implemented: buttonStyle, focusNode return ElevatedButton( onPressed: source.voidHandler(['onPressed']), onLongPress: source.voidHandler(['onLongPress']), autofocus: source.v<bool>(['autofocus']) ?? false, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.child(['child']), ); }, 'FloatingActionButton': (BuildContext context, DataSource source) { // not implemented: mouseCursor, focusNode return FloatingActionButton( tooltip: source.v<String>(['tooltip']), foregroundColor: ArgumentDecoders.color(source, ['foregroundColor']), backgroundColor: ArgumentDecoders.color(source, ['backgroundColor']), focusColor: ArgumentDecoders.color(source, ['focusColor']), hoverColor: ArgumentDecoders.color(source, ['hoverColor']), splashColor: ArgumentDecoders.color(source, ['splashColor']), heroTag: source.v<String>(['heroTag']), elevation: source.v<double>(['elevation']), focusElevation: source.v<double>(['focusElevation']), hoverElevation: source.v<double>(['hoverElevation']), highlightElevation: source.v<double>(['highlightElevation']), disabledElevation: source.v<double>(['disabledElevation']), onPressed: source.voidHandler(['onPressed']), mini: source.v<bool>(['mini']) ?? false, shape: ArgumentDecoders.shapeBorder(source, ['shape']), clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, autofocus: source.v<bool>(['autofocus']) ?? false, materialTapTargetSize: ArgumentDecoders.enumValue<MaterialTapTargetSize>(MaterialTapTargetSize.values, source, ['materialTapTargetSize']), isExtended: source.v<bool>(['isExtended']) ?? false, enableFeedback: source.v<bool>(['enableFeedback']), child: source.child(['child']), ); }, 'InkResponse': (BuildContext context, DataSource source) { // not implemented: mouseCursor, overlayColor, splashFactory, focusNode. return InkResponse( onTap: source.voidHandler(['onTap']), onTapDown: source.handler(['onTapDown'], (VoidCallback trigger) => (TapDownDetails details) => trigger()), onTapUp: source.handler(['onTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), onTapCancel: source.voidHandler(['onTapCancel']), onDoubleTap: source.voidHandler(['onDoubleTap']), onLongPress: source.voidHandler(['onLongPress']), onSecondaryTap: source.voidHandler(['onSecondaryTap']), onSecondaryTapUp: source.handler(['onSecondaryTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), onSecondaryTapDown: source.handler(['onSecondaryTapDown'], (VoidCallback trigger) => (TapDownDetails details) => trigger()), onSecondaryTapCancel: source.voidHandler(['onSecondaryTapCancel']), onHighlightChanged: source.handler(['onHighlightChanged'], (VoidCallback trigger) => (bool highlighted) => trigger()), onHover: source.handler(['onHover'], (VoidCallback trigger) => (bool hovered) => trigger()), containedInkWell: source.v<bool>(['containedInkWell']) ?? false, highlightShape: ArgumentDecoders.enumValue<BoxShape>(BoxShape.values, source, ['highlightShape']) ?? BoxShape.circle, radius: source.v<double>(['radius']), borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius'])?.resolve(Directionality.of(context)), customBorder: ArgumentDecoders.shapeBorder(source, ['customBorder']), focusColor: ArgumentDecoders.color(source, ['focusColor']), hoverColor: ArgumentDecoders.color(source, ['hoverColor']), highlightColor: ArgumentDecoders.color(source, ['highlightColor']), splashColor: ArgumentDecoders.color(source, ['splashColor']), enableFeedback: source.v<bool>(['enableFeedback']) ?? true, excludeFromSemantics: source.v<bool>(['excludeFromSemantics']) ?? false, canRequestFocus: source.v<bool>(['canRequestFocus']) ?? true, onFocusChange: source.handler(['onFocusChange'], (VoidCallback trigger) => (bool focus) => trigger()), autofocus: source.v<bool>(['autofocus']) ?? false, hoverDuration: ArgumentDecoders.duration(source, ['hoverDuration'], context), child: source.optionalChild(['child']), ); }, 'InkWell': (BuildContext context, DataSource source) { // not implemented: mouseCursor; overlayColor, splashFactory; focusNode, onFocusChange return InkWell( onTap: source.voidHandler(['onTap']), onDoubleTap: source.voidHandler(['onDoubleTap']), onLongPress: source.voidHandler(['onLongPress']), onTapDown: source.handler(['onTapDown'], (VoidCallback trigger) => (TapDownDetails details) => trigger()), onTapCancel: source.voidHandler(['onTapCancel']), onSecondaryTap: source.voidHandler(['onSecondaryTap']), onSecondaryTapUp: source.handler(['onSecondaryTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), onSecondaryTapDown: source.handler(['onSecondaryTapDown'], (VoidCallback trigger) => (TapDownDetails details) => trigger()), onSecondaryTapCancel: source.voidHandler(['onSecondaryTapCancel']), onHighlightChanged: source.handler(['onHighlightChanged'], (VoidCallback trigger) => (bool highlighted) => trigger()), onHover: source.handler(['onHover'], (VoidCallback trigger) => (bool hovered) => trigger()), focusColor: ArgumentDecoders.color(source, ['focusColor']), hoverColor: ArgumentDecoders.color(source, ['hoverColor']), highlightColor: ArgumentDecoders.color(source, ['highlightColor']), splashColor: ArgumentDecoders.color(source, ['splashColor']), radius: source.v<double>(['radius']), borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius'])?.resolve(Directionality.of(context)), customBorder: ArgumentDecoders.shapeBorder(source, ['customBorder']), enableFeedback: source.v<bool>(['enableFeedback']) ?? true, excludeFromSemantics: source.v<bool>(['excludeFromSemantics']) ?? false, autofocus: source.v<bool>(['autofocus']) ?? false, child: source.optionalChild(['child']), ); }, 'LinearProgressIndicator': (BuildContext context, DataSource source) { // not implemented: valueColor return LinearProgressIndicator( value: source.v<double>(['value']), color: ArgumentDecoders.color(source, ['color']), backgroundColor: ArgumentDecoders.color(source, ['backgroundColor']), minHeight: source.v<double>(['minHeight']), semanticsLabel: source.v<String>(['semanticsLabel']), semanticsValue: source.v<String>(['semanticsValue']), ); }, 'ListTile': (BuildContext context, DataSource source) { // not implemented: mouseCursor, focusNode return ListTile( leading: source.optionalChild(['leading']), title: source.optionalChild(['title']), subtitle: source.optionalChild(['subtitle']), trailing: source.optionalChild(['trailing']), isThreeLine: source.v<bool>(['isThreeLine']) ?? false, dense: source.v<bool>(['dense']), visualDensity: ArgumentDecoders.visualDensity(source, ['visualDensity']), shape: ArgumentDecoders.shapeBorder(source, ['shape']), contentPadding: ArgumentDecoders.edgeInsets(source, ['contentPadding']), enabled: source.v<bool>(['enabled']) ?? true, onTap: source.voidHandler(['onTap']), onLongPress: source.voidHandler(['onLongPress']), selected: source.v<bool>(['selected']) ?? false, focusColor: ArgumentDecoders.color(source, ['focusColor']), hoverColor: ArgumentDecoders.color(source, ['hoverColor']), autofocus: source.v<bool>(['autofocus']) ?? false, tileColor: ArgumentDecoders.color(source, ['tileColor']), selectedTileColor: ArgumentDecoders.color(source, ['selectedTileColor']), enableFeedback: source.v<bool>(['enableFeedback']), horizontalTitleGap: source.v<double>(['horizontalTitleGap']), minVerticalPadding: source.v<double>(['minVerticalPadding']), minLeadingWidth: source.v<double>(['minLeadingWidth']), ); }, 'Material': (BuildContext context, DataSource source) { return Material( type: ArgumentDecoders.enumValue<MaterialType>(MaterialType.values,source, ['type']) ?? MaterialType.canvas, elevation: source.v<double>(['elevation']) ?? 0.0, color: ArgumentDecoders.color(source, ['color']), shadowColor: ArgumentDecoders.color(source, ['shadowColor']), surfaceTintColor: ArgumentDecoders.color(source, ['surfaceTintColor']), textStyle: ArgumentDecoders.textStyle(source, ['textStyle']), borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius']), shape: ArgumentDecoders.shapeBorder(source, ['shape']), borderOnForeground: source.v<bool>(['borderOnForeground']) ?? true, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, animationDuration: ArgumentDecoders.duration(source, ['animationDuration'], context), child: source.child(['child']), ); }, 'OutlinedButton': (BuildContext context, DataSource source) { // not implemented: buttonStyle, focusNode return OutlinedButton( onPressed: source.voidHandler(['onPressed']), onLongPress: source.voidHandler(['onLongPress']), autofocus: source.v<bool>(['autofocus']) ?? false, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.child(['child']), ); }, 'Scaffold': (BuildContext context, DataSource source) { // not implemented: floatingActionButtonLocation, floatingActionButtonAnimator; onDrawerChanged, onEndDrawerChanged final Widget? appBarWidget = source.optionalChild(['appBar']); final List<Widget> persistentFooterButtons = source.childList(['persistentFooterButtons']); return Scaffold( appBar: appBarWidget == null ? null : PreferredSize( preferredSize: Size.fromHeight(source.v<double>(['bottomHeight']) ?? 56.0), child: appBarWidget, ), body: source.optionalChild(['body']), floatingActionButton: source.optionalChild(['floatingActionButton']), persistentFooterButtons: persistentFooterButtons.isEmpty ? null : persistentFooterButtons, drawer: source.optionalChild(['drawer']), endDrawer: source.optionalChild(['endDrawer']), bottomNavigationBar: source.optionalChild(['bottomNavigationBar']), bottomSheet: source.optionalChild(['bottomSheet']), backgroundColor: ArgumentDecoders.color(source, ['backgroundColor']), resizeToAvoidBottomInset: source.v<bool>(['resizeToAvoidBottomInset']), primary: source.v<bool>(['primary']) ?? true, drawerDragStartBehavior: ArgumentDecoders.enumValue<DragStartBehavior>(DragStartBehavior.values, source, ['drawerDragStartBehavior']) ?? DragStartBehavior.start, extendBody: source.v<bool>(['extendBody']) ?? false, extendBodyBehindAppBar: source.v<bool>(['extendBodyBehindAppBar']) ?? false, drawerScrimColor: ArgumentDecoders.color(source, ['drawerScrimColor']), drawerEdgeDragWidth: source.v<double>(['drawerEdgeDragWidth']), drawerEnableOpenDragGesture: source.v<bool>(['drawerEnableOpenDragGesture']) ?? true, endDrawerEnableOpenDragGesture: source.v<bool>(['endDrawerEnableOpenDragGesture']) ?? true, restorationId: source.v<String>(['restorationId']), ); }, 'TextButton': (BuildContext context, DataSource source) { // not implemented: buttonStyle, focusNode return TextButton( onPressed: source.voidHandler(['onPressed']), onLongPress: source.voidHandler(['onLongPress']), autofocus: source.v<bool>(['autofocus']) ?? false, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.child(['child']), ); }, 'VerticalDivider': (BuildContext context, DataSource source) { return VerticalDivider( width: source.v<double>(['width']), thickness: source.v<double>(['thickness']), indent: source.v<double>(['indent']), endIndent: source.v<double>(['endIndent']), color: ArgumentDecoders.color(source, ['color']), ); }, };
packages/packages/rfw/lib/src/flutter/material_widgets.dart/0
{ "file_path": "packages/packages/rfw/lib/src/flutter/material_widgets.dart", "repo_id": "packages", "token_count": 9097 }
1,023
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); const String testString = 'hello world'; const bool testBool = true; const int testInt = 42; const double testDouble = 3.14159; const List<String> testList = <String>['foo', 'bar']; const String testString2 = 'goodbye world'; const bool testBool2 = false; const int testInt2 = 1337; const double testDouble2 = 2.71828; const List<String> testList2 = <String>['baz', 'quox']; late SharedPreferences preferences; void runAllTests() { testWidgets('reading', (WidgetTester _) async { expect(preferences.get('String'), isNull); expect(preferences.get('bool'), isNull); expect(preferences.get('int'), isNull); expect(preferences.get('double'), isNull); expect(preferences.get('List'), isNull); expect(preferences.getString('String'), isNull); expect(preferences.getBool('bool'), isNull); expect(preferences.getInt('int'), isNull); expect(preferences.getDouble('double'), isNull); expect(preferences.getStringList('List'), isNull); }); testWidgets('writing', (WidgetTester _) async { await Future.wait(<Future<bool>>[ preferences.setString('String', testString2), preferences.setBool('bool', testBool2), preferences.setInt('int', testInt2), preferences.setDouble('double', testDouble2), preferences.setStringList('List', testList2) ]); expect(preferences.getString('String'), testString2); expect(preferences.getBool('bool'), testBool2); expect(preferences.getInt('int'), testInt2); expect(preferences.getDouble('double'), testDouble2); expect(preferences.getStringList('List'), testList2); }); testWidgets('removing', (WidgetTester _) async { const String key = 'testKey'; await preferences.setString(key, testString); await preferences.setBool(key, testBool); await preferences.setInt(key, testInt); await preferences.setDouble(key, testDouble); await preferences.setStringList(key, testList); await preferences.remove(key); expect(preferences.get('testKey'), isNull); }); testWidgets('clearing', (WidgetTester _) async { await preferences.setString('String', testString); await preferences.setBool('bool', testBool); await preferences.setInt('int', testInt); await preferences.setDouble('double', testDouble); await preferences.setStringList('List', testList); await preferences.clear(); expect(preferences.getString('String'), null); expect(preferences.getBool('bool'), null); expect(preferences.getInt('int'), null); expect(preferences.getDouble('double'), null); expect(preferences.getStringList('List'), null); }); testWidgets('simultaneous writes', (WidgetTester _) async { final List<Future<bool>> writes = <Future<bool>>[]; const int writeCount = 100; for (int i = 1; i <= writeCount; i++) { writes.add(preferences.setInt('int', i)); } final List<bool> result = await Future.wait(writes, eagerError: true); // All writes should succeed. expect(result.where((bool element) => !element), isEmpty); // The last write should win. expect(preferences.getInt('int'), writeCount); }); } group('SharedPreferences', () { setUp(() async { preferences = await SharedPreferences.getInstance(); }); tearDown(() async { await preferences.clear(); SharedPreferences.resetStatic(); }); runAllTests(); }); group('setPrefix', () { setUp(() async { SharedPreferences.resetStatic(); SharedPreferences.setPrefix('prefix.'); preferences = await SharedPreferences.getInstance(); }); tearDown(() async { await preferences.clear(); SharedPreferences.resetStatic(); }); runAllTests(); }); group('setNoPrefix', () { setUp(() async { SharedPreferences.resetStatic(); SharedPreferences.setPrefix(''); preferences = await SharedPreferences.getInstance(); }); tearDown(() async { await preferences.clear(); SharedPreferences.resetStatic(); }); runAllTests(); }); testWidgets('allowList only gets allowed items', (WidgetTester _) async { const String allowedString = 'stringKey'; const String allowedBool = 'boolKey'; const String notAllowedDouble = 'doubleKey'; const String resultString = 'resultString'; const Set<String> allowList = <String>{allowedString, allowedBool}; SharedPreferences.resetStatic(); SharedPreferences.setPrefix('', allowList: allowList); final SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString(allowedString, resultString); await prefs.setBool(allowedBool, true); await prefs.setDouble(notAllowedDouble, 3.14); await prefs.reload(); final String? testString = prefs.getString(allowedString); expect(testString, resultString); final bool? testBool = prefs.getBool(allowedBool); expect(testBool, true); final double? testDouble = prefs.getDouble(notAllowedDouble); expect(testDouble, null); }); }
packages/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart", "repo_id": "packages", "token_count": 1990 }
1,024
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences_example/readme_excerpts.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('sanity check readmeSnippets', () async { // This key is set and cleared in the snippets. const String clearedKey = 'counter'; // Set a mock store so that there's a platform implementation. SharedPreferences.setMockInitialValues(<String, Object>{clearedKey: 2}); final SharedPreferences prefs = await SharedPreferences.getInstance(); // Ensure that the snippet code runs successfully. await readmeSnippets(); // Spot-check some functionality to ensure that it's showing working calls. // It should also set some preferences. expect(prefs.getBool('repeat'), isNotNull); expect(prefs.getDouble('decimal'), isNotNull); // It should clear this preference. expect(prefs.getInt(clearedKey), isNull); }); test('readmeTestSnippets', () async { await readmeTestSnippets(); final SharedPreferences prefs = await SharedPreferences.getInstance(); // The snippet sets a single initial pref. expect(prefs.getKeys().length, 1); }); }
packages/packages/shared_preferences/shared_preferences/example/test/readme_excerpts_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/example/test/readme_excerpts_test.dart", "repo_id": "packages", "token_count": 434 }
1,025
group 'io.flutter.plugins.sharedpreferences' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.2.2' } } rootProject.allprojects { repositories { google() mavenCentral() } } allprojects { gradle.projectsEvaluated { tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" } } } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'io.flutter.plugins.sharedpreferences' } compileSdk 34 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } dependencies { testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:5.0.0' } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } }
packages/packages/shared_preferences/shared_preferences_android/android/build.gradle/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/android/build.gradle", "repo_id": "packages", "token_count": 735 }
1,026
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import XCTest @testable import shared_preferences_foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #endif class RunnerTests: XCTestCase { let prefixes: [String] = ["aPrefix", ""] func testSetAndGet() throws { for aPrefix in prefixes { let plugin = SharedPreferencesPlugin() plugin.setBool(key: "\(aPrefix)aBool", value: true) plugin.setDouble(key: "\(aPrefix)aDouble", value: 3.14) plugin.setValue(key: "\(aPrefix)anInt", value: 42) plugin.setValue(key: "\(aPrefix)aString", value: "hello world") plugin.setValue(key: "\(aPrefix)aStringList", value: ["hello", "world"]) let storedValues = plugin.getAll(prefix: aPrefix, allowList: nil) XCTAssertEqual(storedValues["\(aPrefix)aBool"] as? Bool, true) XCTAssertEqual(storedValues["\(aPrefix)aDouble"] as! Double, 3.14, accuracy: 0.0001) XCTAssertEqual(storedValues["\(aPrefix)anInt"] as? Int, 42) XCTAssertEqual(storedValues["\(aPrefix)aString"] as? String, "hello world") XCTAssertEqual(storedValues["\(aPrefix)aStringList"] as? [String], ["hello", "world"]) } } func testGetWithAllowList() throws { for aPrefix in prefixes { let plugin = SharedPreferencesPlugin() plugin.setBool(key: "\(aPrefix)aBool", value: true) plugin.setDouble(key: "\(aPrefix)aDouble", value: 3.14) plugin.setValue(key: "\(aPrefix)anInt", value: 42) plugin.setValue(key: "\(aPrefix)aString", value: "hello world") plugin.setValue(key: "\(aPrefix)aStringList", value: ["hello", "world"]) let storedValues = plugin.getAll(prefix: aPrefix, allowList: ["\(aPrefix)aBool"]) XCTAssertEqual(storedValues["\(aPrefix)aBool"] as? Bool, true) XCTAssertNil(storedValues["\(aPrefix)aDouble"] ?? nil) XCTAssertNil(storedValues["\(aPrefix)anInt"] ?? nil) XCTAssertNil(storedValues["\(aPrefix)aString"] ?? nil) XCTAssertNil(storedValues["\(aPrefix)aStringList"] ?? nil) } } func testRemove() throws { for aPrefix in prefixes { let plugin = SharedPreferencesPlugin() let testKey = "\(aPrefix)foo" plugin.setValue(key: testKey, value: 42) // Make sure there is something to remove, so the test can't pass due to a set failure. let preRemovalValues = plugin.getAll(prefix: aPrefix, allowList: nil) XCTAssertEqual(preRemovalValues[testKey] as? Int, 42) // Then verify that removing it works. plugin.remove(key: testKey) let finalValues = plugin.getAll(prefix: aPrefix, allowList: nil) XCTAssertNil(finalValues[testKey] as Any?) } } func testClearWithNoAllowlist() throws { for aPrefix in prefixes { let plugin = SharedPreferencesPlugin() let testKey = "\(aPrefix)foo" plugin.setValue(key: testKey, value: 42) // Make sure there is something to clear, so the test can't pass due to a set failure. let preRemovalValues = plugin.getAll(prefix: aPrefix, allowList: nil) XCTAssertEqual(preRemovalValues[testKey] as? Int, 42) // Then verify that clearing works. plugin.clear(prefix: aPrefix, allowList: nil) let finalValues = plugin.getAll(prefix: aPrefix, allowList: nil) XCTAssertNil(finalValues[testKey] as Any?) } } func testClearWithAllowlist() throws { for aPrefix in prefixes { let plugin = SharedPreferencesPlugin() let testKey = "\(aPrefix)foo" plugin.setValue(key: testKey, value: 42) // Make sure there is something to clear, so the test can't pass due to a set failure. let preRemovalValues = plugin.getAll(prefix: aPrefix, allowList: nil) XCTAssertEqual(preRemovalValues[testKey] as? Int, 42) plugin.clear(prefix: aPrefix, allowList: ["\(aPrefix)notfoo"]) let finalValues = plugin.getAll(prefix: aPrefix, allowList: nil) XCTAssertEqual(finalValues[testKey] as? Int, 42) } } }
packages/packages/shared_preferences/shared_preferences_foundation/darwin/Tests/RunnerTests.swift/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/darwin/Tests/RunnerTests.swift", "repo_id": "packages", "token_count": 1621 }
1,027
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,028
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert' show json; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:flutter/foundation.dart' show debugPrint, visibleForTesting; import 'package:path/path.dart' as path; import 'package:path_provider_windows/path_provider_windows.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; /// The Windows implementation of [SharedPreferencesStorePlatform]. /// /// This class implements the `package:shared_preferences` functionality for Windows. class SharedPreferencesWindows extends SharedPreferencesStorePlatform { /// Deprecated instance of [SharedPreferencesWindows]. /// Use [SharedPreferencesStorePlatform.instance] instead. @Deprecated('Use `SharedPreferencesStorePlatform.instance` instead.') static SharedPreferencesWindows instance = SharedPreferencesWindows(); /// Registers the Windows implementation. static void registerWith() { SharedPreferencesStorePlatform.instance = SharedPreferencesWindows(); } static const String _defaultPrefix = 'flutter.'; /// File system used to store to disk. Exposed for testing only. @visibleForTesting FileSystem fs = const LocalFileSystem(); /// The path_provider_windows instance used to find the support directory. @visibleForTesting PathProviderWindows pathProvider = PathProviderWindows(); /// Local copy of preferences Map<String, Object>? _cachedPreferences; /// Cached file for storing preferences. File? _localDataFilePath; /// Gets the file where the preferences are stored. Future<File?> _getLocalDataFile() async { if (_localDataFilePath != null) { return _localDataFilePath!; } final String? directory = await pathProvider.getApplicationSupportPath(); if (directory == null) { return null; } return _localDataFilePath = fs.file(path.join(directory, 'shared_preferences.json')); } /// Gets the preferences from the stored file. Once read, the preferences are /// maintained in memory. Future<Map<String, Object>> _reload() async { Map<String, Object> preferences = <String, Object>{}; final File? localDataFile = await _getLocalDataFile(); if (localDataFile != null && localDataFile.existsSync()) { final String stringMap = localDataFile.readAsStringSync(); if (stringMap.isNotEmpty) { final Object? data = json.decode(stringMap); if (data is Map) { preferences = data.cast<String, Object>(); } } } _cachedPreferences = preferences; return preferences; } Future<Map<String, Object>> _readPreferences() async { return _cachedPreferences ?? await _reload(); } /// Writes the cached preferences to disk. Returns [true] if the operation /// succeeded. Future<bool> _writePreferences(Map<String, Object> preferences) async { try { final File? localDataFile = await _getLocalDataFile(); if (localDataFile == null) { debugPrint('Unable to determine where to write preferences.'); return false; } if (!localDataFile.existsSync()) { localDataFile.createSync(recursive: true); } final String stringMap = json.encode(preferences); localDataFile.writeAsStringSync(stringMap); } catch (e) { debugPrint('Error saving preferences to disk: $e'); return false; } return true; } @override Future<bool> clear() async { return clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: _defaultPrefix), ), ); } @override Future<bool> clearWithPrefix(String prefix) async { return clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override Future<bool> clearWithParameters(ClearParameters parameters) async { final PreferencesFilter filter = parameters.filter; final Map<String, Object> preferences = await _readPreferences(); preferences.removeWhere((String key, _) => key.startsWith(filter.prefix) && (filter.allowList == null || filter.allowList!.contains(key))); return _writePreferences(preferences); } @override Future<Map<String, Object>> getAll() async { return getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: _defaultPrefix), ), ); } @override Future<Map<String, Object>> getAllWithPrefix(String prefix) async { return getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final Map<String, Object> withPrefix = Map<String, Object>.from(await _readPreferences()); withPrefix.removeWhere((String key, _) => !(key.startsWith(filter.prefix) && (filter.allowList?.contains(key) ?? true))); return withPrefix; } @override Future<bool> remove(String key) async { final Map<String, Object> preferences = await _readPreferences(); preferences.remove(key); return _writePreferences(preferences); } @override Future<bool> setValue(String valueType, String key, Object value) async { final Map<String, Object> preferences = await _readPreferences(); preferences[key] = value; return _writePreferences(preferences); } }
packages/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart", "repo_id": "packages", "token_count": 1822 }
1,029
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'table.dart'; import 'table_cell.dart'; import 'table_span.dart'; /// Signature for a function that creates a [TableSpan] for a given index of row /// or column in a [TableView]. /// /// Used by the [TableCellDelegateMixin.buildColumn] and /// [TableCellDelegateMixin.buildRow] to configure rows and columns in the /// [TableView]. typedef TableSpanBuilder = TableSpan Function(int index); /// Signature for a function that creates a child [TableViewCell] for a given /// [TableVicinity] in a [TableView], but may return null. /// /// Used by [TableCellBuilderDelegate.builder] to build cells on demand for the /// table. typedef TableViewCellBuilder = TableViewCell Function( BuildContext context, TableVicinity vicinity, ); /// A mixin that defines the model for a [TwoDimensionalChildDelegate] to be /// used with a [TableView]. mixin TableCellDelegateMixin on TwoDimensionalChildDelegate { /// The number of columns that the table has content for. /// /// The [buildColumn] method will be called for indices smaller than the value /// provided here to learn more about the extent and visual appearance of a /// particular column. // TODO(Piinks): land infinite separately, https://github.com/flutter/flutter/issues/131226 // If null, the table will have an infinite number of columns. /// /// The value returned by this getter may be an estimate of the total /// available columns, but [buildColumn] method must provide a valid /// [TableSpan] for all indices smaller than this integer. /// /// The integer returned by this getter must be larger than (or equal to) the /// integer returned by [pinnedColumnCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get columnCount; /// The number of rows that the table has content for. /// /// The [buildRow] method will be called for indices smaller than the value /// provided here to learn more about the extent and visual appearance of a /// particular row. // TODO(Piinks): land infinite separately, https://github.com/flutter/flutter/issues/131226 // If null, the table will have an infinite number of rows. /// /// The value returned by this getter may be an estimate of the total /// available rows, but [buildRow] method must provide a valid /// [TableSpan] for all indices smaller than this integer. /// /// The integer returned by this getter must be larger than (or equal to) the /// integer returned by [pinnedRowCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get rowCount; /// The number of columns that are permanently shown on the leading vertical /// edge of the viewport. /// /// If scrolling is enabled, other columns will scroll underneath the pinned /// columns. /// /// Just like for regular columns, [buildColumn] method will be consulted for /// additional information about the pinned column. The indices of pinned /// columns start at zero and go to `pinnedColumnCount - 1`. /// /// The integer returned by this getter must be smaller than (or equal to) the /// integer returned by [columnCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get pinnedColumnCount => 0; /// The number of rows that are permanently shown on the leading horizontal /// edge of the viewport. /// /// If scrolling is enabled, other rows will scroll underneath the pinned /// rows. /// /// Just like for regular rows, [buildRow] will be consulted for /// additional information about the pinned row. The indices of pinned rows /// start at zero and go to `pinnedRowCount - 1`. /// /// The integer returned by this getter must be smaller than (or equal to) the /// integer returned by [rowCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get pinnedRowCount => 0; /// Builds the [TableSpan] that describes the column at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [columnCount]. TableSpan buildColumn(int index); /// Builds the [TableSpan] that describe the row at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [rowCount]. TableSpan buildRow(int index); } /// A delegate that supplies children for a [TableViewport] on demand using a /// builder callback. /// /// Unlike the base [TwoDimensionalChildBuilderDelegate] this delegate does not /// automatically insert repaint boundaries. Instead, repaint boundaries are /// controlled by [TableViewCell.addRepaintBoundaries]. class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate with TableCellDelegateMixin { /// Creates a lazy building delegate to use with a [TableView]. TableCellBuilderDelegate({ required int columnCount, required int rowCount, int pinnedColumnCount = 0, int pinnedRowCount = 0, super.addAutomaticKeepAlives, required TableViewCellBuilder cellBuilder, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, }) : assert(pinnedColumnCount >= 0), assert(pinnedRowCount >= 0), assert(rowCount >= 0), assert(columnCount >= 0), assert(pinnedColumnCount <= columnCount), assert(pinnedRowCount <= rowCount), _rowBuilder = rowBuilder, _columnBuilder = columnBuilder, _pinnedColumnCount = pinnedColumnCount, _pinnedRowCount = pinnedRowCount, super( builder: (BuildContext context, ChildVicinity vicinity) => cellBuilder(context, vicinity as TableVicinity), maxXIndex: columnCount - 1, maxYIndex: rowCount - 1, // repaintBoundaries handled by TableViewCell addRepaintBoundaries: false, ); @override int get columnCount => maxXIndex! + 1; set columnCount(int value) { assert(pinnedColumnCount <= value); maxXIndex = value - 1; } /// Builds the [TableSpan] that describes the column at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [columnCount]. final TableSpanBuilder _columnBuilder; @override TableSpan buildColumn(int index) => _columnBuilder(index); @override int get pinnedColumnCount => _pinnedColumnCount; int _pinnedColumnCount; set pinnedColumnCount(int value) { assert(value >= 0); assert(value <= columnCount); if (pinnedColumnCount == value) { return; } _pinnedColumnCount = value; notifyListeners(); } @override int get rowCount => maxYIndex! + 1; set rowCount(int value) { assert(pinnedRowCount <= value); maxYIndex = value - 1; } /// Builds the [TableSpan] that describes the row at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [rowCount]. final TableSpanBuilder _rowBuilder; @override TableSpan buildRow(int index) => _rowBuilder(index); @override int get pinnedRowCount => _pinnedRowCount; int _pinnedRowCount; set pinnedRowCount(int value) { assert(value >= 0); assert(value <= rowCount); if (pinnedRowCount == value) { return; } _pinnedRowCount = value; notifyListeners(); } } /// A delegate that supplies children for a [TableViewport] using an /// explicit two dimensional array. /// /// The [children] are accessed for each [TableVicinity.row] and /// [TableVicinity.column] of the [TwoDimensionalViewport] as /// `children[vicinity.row][vicinity.column]`. /// /// Unlike the base [TwoDimensionalChildBuilderDelegate] this delegate does not /// automatically insert repaint boundaries. Instead, repaint boundaries are /// controlled by [TableViewCell.addRepaintBoundaries]. class TableCellListDelegate extends TwoDimensionalChildListDelegate with TableCellDelegateMixin { /// Creates a delegate that supplies children for a [TableView]. TableCellListDelegate({ int pinnedColumnCount = 0, int pinnedRowCount = 0, super.addAutomaticKeepAlives, required List<List<TableViewCell>> cells, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, }) : assert(pinnedColumnCount >= 0), assert(pinnedRowCount >= 0), _columnBuilder = columnBuilder, _rowBuilder = rowBuilder, _pinnedColumnCount = pinnedColumnCount, _pinnedRowCount = pinnedRowCount, super( children: cells, // repaintBoundaries handled by TableViewCell addRepaintBoundaries: false, ) { // Even if there are merged cells, they should be represented by the same // child in each cell location. This ensures that no matter which direction // the merged cell scrolls into view from, we can build the correct child // without having to explore all possible vicinities of the merged cell // area. So all arrays of cells should have the same length. assert( children.map((List<Widget> array) => array.length).toSet().length == 1, 'Each list of Widgets within cells must be of the same length.', ); assert(rowCount >= pinnedRowCount); assert(columnCount >= pinnedColumnCount); } @override int get columnCount => children.isEmpty ? 0 : children[0].length; /// Builds the [TableSpan] that describes the column at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [columnCount]. final TableSpanBuilder _columnBuilder; @override TableSpan buildColumn(int index) => _columnBuilder(index); @override int get pinnedColumnCount => _pinnedColumnCount; int _pinnedColumnCount; set pinnedColumnCount(int value) { assert(value >= 0); assert(value <= columnCount); if (pinnedColumnCount == value) { return; } _pinnedColumnCount = value; notifyListeners(); } @override int get rowCount => children.length; /// Builds the [TableSpan] that describes the row at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [rowCount]. final TableSpanBuilder _rowBuilder; @override TableSpan buildRow(int index) => _rowBuilder(index); @override int get pinnedRowCount => _pinnedRowCount; int _pinnedRowCount; set pinnedRowCount(int value) { assert(value >= 0); assert(value <= rowCount); if (pinnedRowCount == value) { return; } _pinnedRowCount = value; notifyListeners(); } @override bool shouldRebuild(covariant TableCellListDelegate oldDelegate) { return columnCount != oldDelegate.columnCount || _columnBuilder != oldDelegate._columnBuilder || pinnedColumnCount != oldDelegate.pinnedColumnCount || rowCount != oldDelegate.rowCount || _rowBuilder != oldDelegate._rowBuilder || pinnedRowCount != oldDelegate.pinnedRowCount || super.shouldRebuild(oldDelegate); } }
packages/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart", "repo_id": "packages", "token_count": 3484 }
1,030
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.urllauncher; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; /** * Plugin implementation that uses the new {@code io.flutter.embedding} package. * * <p>Instantiate this in an add to app scenario to gracefully handle activity and context changes. */ public final class UrlLauncherPlugin implements FlutterPlugin, ActivityAware { private static final String TAG = "UrlLauncherPlugin"; @Nullable private UrlLauncher urlLauncher; /** * Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common} * package. * * <p>Calling this automatically initializes the plugin. However plugins initialized this way * won't react to changes in activity or context, unlike {@link UrlLauncherPlugin}. */ @SuppressWarnings("deprecation") public static void registerWith( @NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) { UrlLauncher handler = new UrlLauncher(registrar.context()); handler.setActivity(registrar.activity()); Messages.UrlLauncherApi.setup(registrar.messenger(), handler); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { urlLauncher = new UrlLauncher(binding.getApplicationContext()); Messages.UrlLauncherApi.setup(binding.getBinaryMessenger(), urlLauncher); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { if (urlLauncher == null) { Log.wtf(TAG, "Already detached from the engine."); return; } Messages.UrlLauncherApi.setup(binding.getBinaryMessenger(), null); urlLauncher = null; } @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { if (urlLauncher == null) { Log.wtf(TAG, "urlLauncher was never set."); return; } urlLauncher.setActivity(binding.getActivity()); } @Override public void onDetachedFromActivity() { if (urlLauncher == null) { Log.wtf(TAG, "urlLauncher was never set."); return; } urlLauncher.setActivity(null); } @Override public void onDetachedFromActivityForConfigChanges() { onDetachedFromActivity(); } @Override public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { onAttachedToActivity(binding); } }
packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncherPlugin.java/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncherPlugin.java", "repo_id": "packages", "token_count": 871 }
1,031
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; /// Possible outcomes of launching a URL. enum LaunchResult { /// The URL was successfully launched (or could be, for `canLaunchUrl`). success, /// There was no handler available for the URL. failure, /// The URL could not be launched because it is invalid. invalidUrl, } /// Possible outcomes of handling a URL within the application. enum InAppLoadResult { /// The URL was successfully loaded. success, /// The URL did not load successfully. failedToLoad, /// The URL could not be launched because it is invalid. invalidUrl, } class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. UrlLauncherApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Checks whether a URL can be loaded. Future<LaunchResult> canLaunchUrl(String arg_url) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.canLaunchUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_url]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return LaunchResult.values[replyList[0]! as int]; } } /// Opens the URL externally, returning the status of launching it. Future<LaunchResult> launchUrl( String arg_url, bool arg_universalLinksOnly) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.launchUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_url, arg_universalLinksOnly]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return LaunchResult.values[replyList[0]! as int]; } } /// Opens the URL in an in-app SFSafariViewController, returning the results /// of loading it. Future<InAppLoadResult> openUrlInSafariViewController(String arg_url) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.openUrlInSafariViewController', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_url]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return InAppLoadResult.values[replyList[0]! as int]; } } /// Closes the view controller opened by [openUrlInSafariViewController]. Future<void> closeSafariViewController() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.closeSafariViewController', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } }
packages/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 2103 }
1,032
## 2.3.0 * Updates web code to package `web: ^0.5.0`. * Updates SDK version to Dart `^3.3.0`. Flutter `^3.19.0`. ## 2.2.3 * Fixes new lint warnings. ## 2.2.2 * Adds documentation that a launch in a new window/tab needs to be triggered by a user action. ## 2.2.1 * Supports Flutter Web + Wasm * Updates minimum supported SDK version to Flutter 3.16.0/Dart 3.2.0. ## 2.2.0 * Implements `supportsMode` and `supportsCloseForMode`. ## 2.1.0 * Adds `launchUrl` implementation. * Prevents _Tabnabbing_ and disallows `javascript:` URLs on `launch` and `launchUrl`. ## 2.0.20 * Migrates to `dart:ui_web` APIs. * Updates minimum supported SDK version to Flutter 3.13.0/Dart 3.1.0. ## 2.0.19 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.0.18 * Removes nested third_party Safari check. ## 2.0.17 * Removes obsolete null checks on non-nullable values. * Updates minimum Flutter version to 3.3. ## 2.0.16 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 2.0.15 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.0.14 * Updates code for stricter lint checks. * Updates minimum Flutter version to 2.10. ## 2.0.13 * Updates `url_launcher_platform_interface` constraint to the correct minimum version. ## 2.0.12 * Fixes call to `setState` after dispose on the `Link` widget. [Issue](https://github.com/flutter/flutter/issues/102741). * Removes unused `BuildContext` from the `LinkViewController`. ## 2.0.11 * Minor fixes for new analysis options. ## 2.0.10 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.0.9 - Fixes invalid routes when opening a `Link` in a new tab ## 2.0.8 * Updates the minimum Flutter version to 2.10, which is required by the change in 2.0.7. ## 2.0.7 * Marks the `Link` widget as invisible so it can be optimized by the engine. ## 2.0.6 * Removes dependency on `meta`. ## 2.0.5 * Updates code for new analysis options. ## 2.0.4 - Add `implements` to pubspec. ## 2.0.3 - Replaced reference to `shared_preferences` plugin with the `url_launcher` in the README. ## 2.0.2 - Updated installation instructions in README. ## 2.0.1 - Change sizing code of `Link` widget's `HtmlElementView` so it works well when slotted. ## 2.0.0 - Migrate to null safety. ## 0.1.5+3 - Fix Link misalignment [issue](https://github.com/flutter/flutter/issues/70053). ## 0.1.5+2 - Update Flutter SDK constraint. ## 0.1.5+1 - Substitute `undefined_prefixed_name: ignore` analyzer setting by a `dart:ui` shim with conditional exports. [Issue](https://github.com/flutter/flutter/issues/69309). ## 0.1.5 - Added the web implementation of the Link widget. ## 0.1.4+2 - Move `lib/third_party` to `lib/src/third_party`. ## 0.1.4+1 - Add a more correct attribution to `package:platform_detect` code. ## 0.1.4 - (Null safety) Remove dependency on `package:platform_detect` - Port unit tests to run with `flutter drive` ## 0.1.3+2 - Fix a typo in a test name and fix some style inconsistencies. ## 0.1.3+1 - Depend explicitly on the `platform_interface` package that adds the `webOnlyWindowName` parameter. ## 0.1.3 - Added webOnlyWindowName parameter to launch() ## 0.1.2+1 - Update docs ## 0.1.2 - Adds "tel" and "sms" support ## 0.1.1+6 - Open "mailto" urls with target set as "\_top" on Safari browsers. - Update lower bound of dart dependency to 2.2.0. ## 0.1.1+5 - Update lower bound of dart dependency to 2.1.0. ## 0.1.1+4 - Declare API stability and compatibility with `1.0.0` (more details at: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0). ## 0.1.1+3 - Refactor tests to not rely on the underlying browser behavior. ## 0.1.1+2 - Open urls with target "\_top" on iOS PWAs. ## 0.1.1+1 - Make the pedantic dev_dependency explicit. ## 0.1.1 - Added support for mailto scheme ## 0.1.0+2 - Remove androidx references from the no-op android implemenation. ## 0.1.0+1 - Add an android/ folder with no-op implementation to workaround https://github.com/flutter/flutter/issues/46304. - Bump the minimal required Flutter version to 1.10.0. ## 0.1.0 - Update docs and pubspec. ## 0.0.2 - Switch to using `url_launcher_platform_interface`. ## 0.0.1 - Initial open-source release.
packages/packages/url_launcher/url_launcher_web/CHANGELOG.md/0
{ "file_path": "packages/packages/url_launcher/url_launcher_web/CHANGELOG.md", "repo_id": "packages", "token_count": 1595 }
1,033
## 2.8.3 * Fixes typo in `README.md`. * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates support matrix in README to indicate that iOS 11 is no longer supported. * Clients on versions of Flutter that still support iOS 11 can continue to use this package with iOS 11, but will not receive any further updates to the iOS implementation. ## 2.8.2 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 2.8.1 * Updates the example app: replaces `ButtonBar` with `OverflowBar` widget. ## 2.8.0 * Adds support for macOS. ## 2.7.2 * Adds `isCompleted` event to `VideoPlayerEvent`. ## 2.7.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.7.0 * Adds an `Uri` typed factory method `VideoPlayerController.networkUrl` to avoid common mistakes with `String` URIs. The method receives an`Uri` instead of a `String` url. * Deprecates `VideoPlayerController.network` factory method. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.6.1 * Synchronizes `VideoPlayerValue.isPlaying` with underlying video player. ## 2.6.0 * Adds option to configure HTTP headers via `VideoPlayerController` to fix access to M3U8 files on Android. * Aligns Dart and Flutter SDK constraints. ## 2.5.3 * Updates iOS minimum version in README. ## 2.5.2 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.5.1 * Updates code for stricter lint checks. ## 2.5.0 * Exposes `VideoScrubber` so it can be used to make custom video progress indicators ## 2.4.10 * Adds compatibilty with version 6.0 of the platform interface. ## 2.4.9 * Fixes file URI construction. ## 2.4.8 * Updates code for new analysis options. * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 2.4.7 * Updates README via code excerpts. * Fixes violations of new analysis option use_named_constants. ## 2.4.6 * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 2.4.5 * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231). * Fixes an exception when a disposed VideoPlayerController is disposed again. ## 2.4.4 * Updates references to the obsolete master branch. ## 2.4.3 * Fixes Android to correctly display videos recorded in landscapeRight ([#60327](https://github.com/flutter/flutter/issues/60327)). * Fixes order-dependent unit tests. ## 2.4.2 * Minor fixes for new analysis options. ## 2.4.1 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.4.0 * Updates minimum Flutter version to 2.10. * Adds OS version support information to README. * Adds `setClosedCaptionFile` method to `VideoPlayerController`. ## 2.3.0 * Adds `allowBackgroundPlayback` to `VideoPlayerOptions`. ## 2.2.19 * Internal code cleanup for stricter analysis options. ## 2.2.18 * Moves Android and iOS implementations to federated packages. * Update audio URL in iOS tests. ## 2.2.17 * Avoid blocking the main thread loading video count on iOS. ## 2.2.16 * Introduces `setCaptionOffset` to offset the caption display based on a Duration. ## 2.2.15 * Updates README discussion of permissions. ## 2.2.14 * Removes KVO observer on AVPlayerItem on iOS. ## 2.2.13 * Fixes persisting of hasError even after successful initialize. ## 2.2.12 * iOS: Validate size only when assets contain video tracks. ## 2.2.11 * Removes dependency on `meta`. ## 2.2.10 * iOS: Updates texture on `seekTo`. ## 2.2.9 * Adds compatibility with `video_player_platform_interface` 5.0, which does not include non-dev test dependencies. ## 2.2.8 * Changes the way the `VideoPlayerPlatform` instance is cached in the controller, so that it's no longer impossible to change after the first use. * Updates unit tests to be self-contained. * Fixes integration tests. * Updates Android compileSdkVersion to 31. * Fixes a flaky integration test. * Integration tests now use WebM on web, to allow running with Chromium. ## 2.2.7 * Fixes a regression where dragging a [VideoProgressIndicator] while playing would restart playback from the start of the video. ## 2.2.6 * Initialize player when size and duration become available on iOS ## 2.2.5 * Support to closed caption WebVTT format added. ## 2.2.4 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 2.2.3 * Fixed empty caption text still showing the caption widget. ## 2.2.2 * Fix a disposed `VideoPlayerController` throwing an exception when being replaced in the `VideoPlayer`. ## 2.2.1 * Specify Java 8 for Android build. ## 2.2.0 * Add `contentUri` based VideoPlayerController. ## 2.1.15 * Ensured seekTo isn't called before video player is initialized. Fixes [#89259](https://github.com/flutter/flutter/issues/89259). * Updated Android lint settings. ## 2.1.14 * Removed dependency on the `flutter_test` package. ## 2.1.13 * Removed obsolete warning about not working in iOS simulators from README. ## 2.1.12 * Update the video url in the readme code sample ## 2.1.11 * Remove references to the Android V1 embedding. ## 2.1.10 * Ensure video pauses correctly when it finishes. ## 2.1.9 * Silenced warnings that may occur during build when using a very recent version of Flutter relating to null safety. ## 2.1.8 * Refactor `FLTCMTimeToMillis` to support indefinite streams. Fixes [#48670](https://github.com/flutter/flutter/issues/48670). ## 2.1.7 * Update exoplayer to 2.14.1, removing dependency on Bintray. ## 2.1.6 * Remove obsolete pre-1.0 warning from README. * Add iOS unit and UI integration test targets. ## 2.1.5 * Update example code in README to fix broken url. ## 2.1.4 * Add an exoplayer URL to the maven repositories to address a possible build regression in 2.1.2. ## 2.1.3 * Fix pointer value to boolean conversion analyzer warnings. ## 2.1.2 * Migrate maven repository from jcenter to mavenCentral. ## 2.1.1 * Update example code in README to reflect API changes. ## 2.1.0 * Add `httpHeaders` option to `VideoPlayerController.network` ## 2.0.2 * Fix `VideoPlayerValue` size and aspect ratio documentation ## 2.0.1 * Remove the deprecated API "exoPlayer.setAudioAttributes". ## 2.0.0 * Migrate to null safety. * Fix an issue where `isBuffering` was not updating on Android. * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) * Fix `VideoPlayerValue toString()` test. * Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets. * Migrate from deprecated `defaultBinaryMessenger`. * Fix an issue where a crash can occur after a closing a video player view on iOS. * Setting the `mixWithOthers` `VideoPlayerOptions` in web now is silently ignored instead of throwing an exception. ## 1.0.2 * Update Flutter SDK constraint. ## 1.0.1 * Android: Dispose video players when app is closed. ## 1.0.0 * Announce 1.0.0. ## 0.11.1+5 * Update Dart SDK constraint in example. * Remove `test` dependency. * Convert disabled driver test to integration_test. ## 0.11.1+4 * Add `toString()` to `Caption`. * Fix a bug on Android when loading videos from assets would crash. ## 0.11.1+3 * Android: Upgrade ExoPlayer to 2.12.1. ## 0.11.1+2 * Update android compileSdkVersion to 29. ## 0.11.1+1 * Fixed uncanceled timers when calling `play` on the controller multiple times before `pause`, which caused value listeners to be called indefinitely (after `pause`) and more often than needed. ## 0.11.1 * Enable TLSv1.1 & TLSv1.2 for API 19 and below. ## 0.11.0 * Added option to set the video playback speed on the video controller. * **Minor breaking change**: fixed `VideoPlayerValue.toString` to insert a comma after `isBuffering`. ## 0.10.12+5 * Depend on `video_player_platform_interface` version that contains the new `TestHostVideoPlayerApi` in order for tests to pass using the latest dependency. ## 0.10.12+4 * Keep handling deprecated Android v1 classes for backward compatibility. ## 0.10.12+3 * Avoiding uses or overrides a deprecated API in `VideoPlayerPlugin` class. ## 0.10.12+2 * Fix `setMixWithOthers` test. ## 0.10.12+1 * Depend on the version of `video_player_platform_interface` that contains the new `VideoPlayerOptions` class. ## 0.10.12 * Introduce VideoPlayerOptions to set the audio mix mode. ## 0.10.11+2 * Fix aspectRatio calculation when size.width or size.height are zero. ## 0.10.11+1 * Post-v2 Android embedding cleanups. ## 0.10.11 * iOS: Fixed crash when detaching from a dying engine. * Android: Fixed exception when detaching from any engine. ## 0.10.10 * Migrated to [pigeon](https://pub.dev/packages/pigeon). ## 0.10.9+2 * Declare API stability and compatibility with `1.0.0` (more details at: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0). ## 0.10.9+1 * Readme updated to include web support and details on how to use for web ## 0.10.9 * Remove Android dependencies fallback. * Require Flutter SDK 1.12.13+hotfix.5 or greater. * Fix CocoaPods podspec lint warnings. ## 0.10.8+2 * Replace deprecated `getFlutterEngine` call on Android. ## 0.10.8+1 * Make the pedantic dev_dependency explicit. ## 0.10.8 * Added support for cleaning up the plugin if used for add-to-app (Flutter v1.15.3 is required for that feature). ## 0.10.7 * `VideoPlayerController` support for reading closed caption files. * `VideoPlayerValue` has a `caption` field for reading the current closed caption at any given time. ## 0.10.6 * `ClosedCaptionFile` and `SubRipCaptionFile` classes added to read [SubRip](https://en.wikipedia.org/wiki/SubRip) files into dart objects. ## 0.10.5+3 * Add integration instructions for the `web` platform. ## 0.10.5+2 * Make sure the plugin is correctly initialized ## 0.10.5+1 * Fixes issue where `initialize()` `Future` stalls when failing to load source data and does not throw an error. ## 0.10.5 * Support `web` by default. * Require Flutter SDK 1.12.13+hotfix.4 or greater. ## 0.10.4+2 * Remove the deprecated `author:` field form pubspec.yaml * Migrate the plugin to the pubspec platforms manifest. * Require Flutter SDK 1.10.0 or greater. ## 0.10.4+1 * Fix pedantic lints. This fixes some potential race conditions in cases where futures within some video_player methods weren't being awaited correctly. ## 0.10.4 * Port plugin code to use the federated Platform Interface, instead of a MethodChannel directly. ## 0.10.3+3 * Add DartDocs and unit tests. ## 0.10.3+2 * Update the homepage to point to the new plugin location ## 0.10.3+1 * Dispose `FLTVideoPlayer` in `onTextureUnregistered` callback on iOS. * Add a temporary fix to dispose the `FLTVideoPlayer` with a delay to avoid race condition. * Updated the example app to include a new page that pop back after video is done playing. ## 0.10.3 * Add support for the v2 Android embedding. This shouldn't impact existing functionality. ## 0.10.2+6 * Remove AndroidX warnings. ## 0.10.2+5 * Update unit test for compatibility with Flutter stable branch. ## 0.10.2+4 * Define clang module for iOS. ## 0.10.2+3 * Fix bug where formatHint was not being pass down to network sources. ## 0.10.2+2 * Update and migrate iOS example project. ## 0.10.2+1 * Use DefaultHttpDataSourceFactory only when network schemas and use DefaultHttpDataSourceFactory by default. ## 0.10.2 * **Android Only** Adds optional VideoFormat used to signal what format the plugin should try. ## 0.10.1+7 * Fix tests by ignoring deprecated member use. ## 0.10.1+6 * [iOS] Fixed a memory leak with notification observing. ## 0.10.1+5 * Fix race condition while disposing the VideoController. ## 0.10.1+4 * Fixed syntax error in README.md. ## 0.10.1+3 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 0.10.1+2 * Example: Fixed tab display and added scroll view ## 0.10.1+1 * iOS: Avoid deprecated `seekToTime` API ## 0.10.1 * iOS: Consider a player only `initialized` once duration is determined. ## 0.10.0+8 * iOS: Fix an issue where the player sends initialization message incorrectly. * Fix a few other IDE warnings. ## 0.10.0+7 * Android: Fix issue where buffering status in percentage instead of milliseconds * Android: Update buffering status everytime we notify for position change ## 0.10.0+6 * Android: Fix missing call to `event.put("event", "completed");` which makes it possible to detect when the video is over. ## 0.10.0+5 * Fixed iOS build warnings about implicit retains. ## 0.10.0+4 * Android: Upgrade ExoPlayer to 2.9.6. ## 0.10.0+3 * Fix divide by zero bug on iOS. ## 0.10.0+2 * Added supported format documentation in README. ## 0.10.0+1 * Log a more detailed warning at build time about the previous AndroidX migration. ## 0.10.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 0.9.0 * Fixed the aspect ratio and orientation of videos. Videos are now properly displayed when recorded in portrait mode both in iOS and Android. ## 0.8.0 * Android: Upgrade ExoPlayer to 2.9.1 * Android: Use current gradle dependencies * Android 9 compatibility fixes for Demo App ## 0.7.2 * Updated to use factories on exoplayer `MediaSource`s for Android instead of the now-deprecated constructors. ## 0.7.1 * Fixed null exception on Android when the video has a width or height of 0. ## 0.7.0 * Add a unit test for controller and texture changes. This is a breaking change since the interface had to be cleaned up to facilitate faking. ## 0.6.6 * Fix the condition where the player doesn't update when attached controller is changed. ## 0.6.5 * Eliminate race conditions around initialization: now initialization events are queued and guaranteed to be delivered to the Dart side. VideoPlayer widget is rebuilt upon completion of initialization. ## 0.6.4 * Android: add support for hls, dash and ss video formats. ## 0.6.3 * iOS: Allow audio playback in silent mode. ## 0.6.2 * `VideoPlayerController.seekTo()` is now frame accurate on both platforms. ## 0.6.1 * iOS: add missing observer removals to prevent crashes on deallocation. ## 0.6.0 * Android: use ExoPlayer instead of MediaPlayer for better video format support. ## 0.5.5 * **Breaking change** `VideoPlayerController.initialize()` now only completes after the controller is initialized. * Updated example in README.md. ## 0.5.4 * Updated Gradle tooling to match Android Studio 3.1.2. ## 0.5.3 * Added video buffering status. ## 0.5.2 * Fixed a bug on iOS that could lead to missing initialization. * Added support for HLS video on iOS. ## 0.5.1 * Fixed bug on video loop feature for iOS. ## 0.5.0 * Added the constructor `VideoPlayerController.file`. * **Breaking change**. Changed `VideoPlayerController.isNetwork` to an enum `VideoPlayerController.dataSourceType`. ## 0.4.1 * Updated Flutter SDK constraint to reflect the changes in v0.4.0. ## 0.4.0 * **Breaking change**. Removed the `VideoPlayerController` constructor * Added two new factory constructors `VideoPlayerController.asset` and `VideoPlayerController.network` to respectively play a video from the Flutter assets and from a network uri. ## 0.3.0 * **Breaking change**. Set SDK constraints to match the Flutter beta release. ## 0.2.1 * Fixed some signatures to account for strong mode runtime errors. * Fixed spelling mistake in toString output. ## 0.2.0 * **Breaking change**. Renamed `VideoPlayerController.isErroneous` to `VideoPlayerController.hasError`. * Updated documentation of when fields are available on `VideoPlayerController`. * Updated links in README.md. ## 0.1.1 * Simplified and upgraded Android project template to Android SDK 27. * Moved Android package to io.flutter.plugins. * Fixed warnings from the Dart 2.0 analyzer. ## 0.1.0 * **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found [here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1). ## 0.0.7 * Added access to the video size. * Made the VideoProgressIndicator render using a LinearProgressIndicator. ## 0.0.6 * Fixed a bug related to hot restart on Android. ## 0.0.5 * Added VideoPlayerValue.toString(). * Added FLT prefix to iOS types. ## 0.0.4 * The player will now pause on app pause, and resume on app resume. * Implemented scrubbing on the progress bar. ## 0.0.3 * Made creating a VideoPlayerController a synchronous operation. Must be followed by a call to initialize(). * Added VideoPlayerController.setVolume(). * Moved the package to flutter/plugins github repo. ## 0.0.2 * Fix meta dependency version. ## 0.0.1 * Initial release
packages/packages/video_player/video_player/CHANGELOG.md/0
{ "file_path": "packages/packages/video_player/video_player/CHANGELOG.md", "repo_id": "packages", "token_count": 5400 }
1,034
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show rootBundle; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path_provider/path_provider.dart'; import 'package:video_player/video_player.dart'; const Duration _playDuration = Duration(seconds: 1); // Use WebM for web to allow CI to use Chromium. const String _videoAssetKey = kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; // Returns the URL to load an asset from this example app as a network source. // // TODO(stuartmorgan): Convert this to a local `HttpServer` that vends the // assets directly, https://github.com/flutter/flutter/issues/95420 String getUrlForAssetAsNetworkSource(String assetKey) { return 'https://github.com/flutter/packages/blob/' // This hash can be rolled forward to pick up newly-added assets. '2e1673307ff7454aff40b47024eaed49a9e77e81' '/packages/video_player/video_player/example/' '$assetKey' '?raw=true'; } void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); late VideoPlayerController controller; tearDown(() async => controller.dispose()); group('asset videos', () { setUp(() { controller = VideoPlayerController.asset(_videoAssetKey); }); testWidgets('can be initialized', (WidgetTester tester) async { await controller.initialize(); expect(controller.value.isInitialized, true); expect(controller.value.position, Duration.zero); expect(controller.value.isPlaying, false); // The WebM version has a slightly different duration than the MP4. expect(controller.value.duration, const Duration(seconds: 7, milliseconds: kIsWeb ? 544 : 540)); }); testWidgets( 'live stream duration != 0', (WidgetTester tester) async { final VideoPlayerController networkController = VideoPlayerController.networkUrl( Uri.parse( 'https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8'), ); await networkController.initialize(); expect(networkController.value.isInitialized, true); // Live streams should have either a positive duration or C.TIME_UNSET if the duration is unknown // See https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/Player.html#getDuration-- expect(networkController.value.duration, (Duration duration) => duration != Duration.zero); }, skip: kIsWeb, ); testWidgets( 'can be played', (WidgetTester tester) async { await controller.initialize(); // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); await controller.play(); await tester.pumpAndSettle(_playDuration); expect(controller.value.isPlaying, true); expect(controller.value.position, (Duration position) => position > Duration.zero); }, ); testWidgets( 'can seek', (WidgetTester tester) async { await controller.initialize(); await controller.seekTo(const Duration(seconds: 3)); expect(controller.value.position, const Duration(seconds: 3)); }, ); testWidgets( 'can be paused', (WidgetTester tester) async { await controller.initialize(); // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); // Play for a second, then pause, and then wait a second. await controller.play(); await tester.pumpAndSettle(_playDuration); await controller.pause(); final Duration pausedPosition = controller.value.position; await tester.pumpAndSettle(_playDuration); // Verify that we stopped playing after the pause. expect(controller.value.isPlaying, false); expect(controller.value.position, pausedPosition); }, ); testWidgets( 'stay paused when seeking after video completed', (WidgetTester tester) async { await controller.initialize(); // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); final Duration tenMillisBeforeEnd = controller.value.duration - const Duration(milliseconds: 10); await controller.seekTo(tenMillisBeforeEnd); await controller.play(); await tester.pumpAndSettle(_playDuration); // Android emulators in our CI have frequent flake where the video // reports as still playing (usually without having advanced at all // past the seek position, but sometimes having advanced some); if that // happens, the thing being tested hasn't even had a chance to happen // due to CI issues, so just report it as skipped. // TODO(stuartmorgan): Remove once // https://github.com/flutter/flutter/issues/141145 is fixed. if ((!kIsWeb && Platform.isAndroid) && controller.value.isPlaying) { markTestSkipped( 'Skipping due to https://github.com/flutter/flutter/issues/141145'); return; } expect(controller.value.isPlaying, false); expect(controller.value.position, controller.value.duration); await controller.seekTo(tenMillisBeforeEnd); await tester.pumpAndSettle(_playDuration); expect(controller.value.isPlaying, false); expect(controller.value.position, tenMillisBeforeEnd); }, // Flaky on web: https://github.com/flutter/flutter/issues/130147 skip: kIsWeb, ); testWidgets( 'do not exceed duration on play after video completed', (WidgetTester tester) async { await controller.initialize(); // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); await controller.seekTo( controller.value.duration - const Duration(milliseconds: 10)); await controller.play(); await tester.pumpAndSettle(_playDuration); // Android emulators in our CI have frequent flake where the video // reports as still playing (usually without having advanced at all // past the seek position, but sometimes having advanced some); if that // happens, the thing being tested hasn't even had a chance to happen // due to CI issues, so just report it as skipped. // TODO(stuartmorgan): Remove once // https://github.com/flutter/flutter/issues/141145 is fixed. if ((!kIsWeb && Platform.isAndroid) && controller.value.isPlaying) { markTestSkipped( 'Skipping due to https://github.com/flutter/flutter/issues/141145'); return; } expect(controller.value.isPlaying, false); expect(controller.value.position, controller.value.duration); await controller.play(); await tester.pumpAndSettle(_playDuration); expect(controller.value.position, lessThanOrEqualTo(controller.value.duration)); }, ); testWidgets('test video player view with local asset', (WidgetTester tester) async { Future<bool> started() async { await controller.initialize(); await controller.play(); return true; } await tester.pumpWidget(Material( child: Directionality( textDirection: TextDirection.ltr, child: Center( child: FutureBuilder<bool>( future: started(), builder: (BuildContext context, AsyncSnapshot<bool> snapshot) { if (snapshot.data ?? false) { return AspectRatio( aspectRatio: controller.value.aspectRatio, child: VideoPlayer(controller), ); } else { return const Text('waiting for video to load'); } }, ), ), ), )); await tester.pumpAndSettle(); expect(controller.value.isPlaying, true); }, skip: kIsWeb || // Web does not support local assets. // Extremely flaky on iOS: https://github.com/flutter/flutter/issues/86915 defaultTargetPlatform == TargetPlatform.iOS); }); group('file-based videos', () { setUp(() async { // Load the data from the asset. final String tempDir = (await getTemporaryDirectory()).path; final ByteData bytes = await rootBundle.load(_videoAssetKey); // Write it to a file to use as a source. final String filename = _videoAssetKey.split('/').last; final File file = File('$tempDir/$filename'); await file.writeAsBytes(bytes.buffer.asInt8List()); controller = VideoPlayerController.file(file); }); testWidgets('test video player using static file() method as constructor', (WidgetTester tester) async { await controller.initialize(); await controller.play(); expect(controller.value.isPlaying, true); await controller.pause(); expect(controller.value.isPlaying, false); }, skip: kIsWeb); }); group('network videos', () { setUp(() { controller = VideoPlayerController.networkUrl( Uri.parse(getUrlForAssetAsNetworkSource(_videoAssetKey))); }); testWidgets( 'reports buffering status', (WidgetTester tester) async { await controller.initialize(); // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); final Completer<void> started = Completer<void>(); final Completer<void> ended = Completer<void>(); controller.addListener(() { if (!started.isCompleted && controller.value.isBuffering) { started.complete(); } if (started.isCompleted && !controller.value.isBuffering && !ended.isCompleted) { ended.complete(); } }); await controller.play(); await controller.seekTo(const Duration(seconds: 5)); await tester.pumpAndSettle(_playDuration); await controller.pause(); expect(controller.value.isPlaying, false); expect(controller.value.position, (Duration position) => position > Duration.zero); await expectLater(started.future, completes); await expectLater(ended.future, completes); }, skip: !(kIsWeb || defaultTargetPlatform == TargetPlatform.android), ); }); // Audio playback is tested to prevent accidental regression, // but could be removed in the future. group('asset audios', () { setUp(() { controller = VideoPlayerController.asset('assets/Audio.mp3'); }); testWidgets('can be initialized', (WidgetTester tester) async { await controller.initialize(); expect(controller.value.isInitialized, true); expect(controller.value.position, Duration.zero); expect(controller.value.isPlaying, false); // Due to the duration calculation accuracy between platforms, // the milliseconds on Web will be a slightly different from natives. // The audio was made with 44100 Hz, 192 Kbps CBR, and 32 bits. expect( controller.value.duration, const Duration(seconds: 5, milliseconds: kIsWeb ? 42 : 41), ); }); testWidgets('can be played', (WidgetTester tester) async { await controller.initialize(); // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); await controller.play(); await tester.pumpAndSettle(_playDuration); expect(controller.value.isPlaying, true); expect( controller.value.position, (Duration position) => position > Duration.zero, ); }); testWidgets('can seek', (WidgetTester tester) async { await controller.initialize(); await controller.seekTo(const Duration(seconds: 3)); expect(controller.value.position, const Duration(seconds: 3)); }); testWidgets('can be paused', (WidgetTester tester) async { await controller.initialize(); // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); // Play for a second, then pause, and then wait a second. await controller.play(); await tester.pumpAndSettle(_playDuration); await controller.pause(); final Duration pausedPosition = controller.value.position; await tester.pumpAndSettle(_playDuration); // Verify that we stopped playing after the pause. expect(controller.value.isPlaying, false); expect(controller.value.position, pausedPosition); }); }); }
packages/packages/video_player/video_player/example/integration_test/video_player_test.dart/0
{ "file_path": "packages/packages/video_player/video_player/example/integration_test/video_player_test.dart", "repo_id": "packages", "token_count": 5162 }
1,035
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/video_player/video_player_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/video_player/video_player_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
1,036
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v13.0.0), do not edit directly. // See also: https://pub.dev/packages/pigeon #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN @class FVPTextureMessage; @class FVPLoopingMessage; @class FVPVolumeMessage; @class FVPPlaybackSpeedMessage; @class FVPPositionMessage; @class FVPCreateMessage; @class FVPMixWithOthersMessage; @interface FVPTextureMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithTextureId:(NSInteger)textureId; @property(nonatomic, assign) NSInteger textureId; @end @interface FVPLoopingMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithTextureId:(NSInteger)textureId isLooping:(BOOL)isLooping; @property(nonatomic, assign) NSInteger textureId; @property(nonatomic, assign) BOOL isLooping; @end @interface FVPVolumeMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithTextureId:(NSInteger)textureId volume:(double)volume; @property(nonatomic, assign) NSInteger textureId; @property(nonatomic, assign) double volume; @end @interface FVPPlaybackSpeedMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithTextureId:(NSInteger)textureId speed:(double)speed; @property(nonatomic, assign) NSInteger textureId; @property(nonatomic, assign) double speed; @end @interface FVPPositionMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithTextureId:(NSInteger)textureId position:(NSInteger)position; @property(nonatomic, assign) NSInteger textureId; @property(nonatomic, assign) NSInteger position; @end @interface FVPCreateMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithAsset:(nullable NSString *)asset uri:(nullable NSString *)uri packageName:(nullable NSString *)packageName formatHint:(nullable NSString *)formatHint httpHeaders:(NSDictionary<NSString *, NSString *> *)httpHeaders; @property(nonatomic, copy, nullable) NSString *asset; @property(nonatomic, copy, nullable) NSString *uri; @property(nonatomic, copy, nullable) NSString *packageName; @property(nonatomic, copy, nullable) NSString *formatHint; @property(nonatomic, copy) NSDictionary<NSString *, NSString *> *httpHeaders; @end @interface FVPMixWithOthersMessage : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithMixWithOthers:(BOOL)mixWithOthers; @property(nonatomic, assign) BOOL mixWithOthers; @end /// The codec used by FVPAVFoundationVideoPlayerApi. NSObject<FlutterMessageCodec> *FVPAVFoundationVideoPlayerApiGetCodec(void); @protocol FVPAVFoundationVideoPlayerApi - (void)initialize:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable FVPTextureMessage *)create:(FVPCreateMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; - (void)dispose:(FVPTextureMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; - (void)setLooping:(FVPLoopingMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; - (void)setVolume:(FVPVolumeMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; - (void)setPlaybackSpeed:(FVPPlaybackSpeedMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; - (void)play:(FVPTextureMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable FVPPositionMessage *)position:(FVPTextureMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; - (void)seekTo:(FVPPositionMessage *)msg completion:(void (^)(FlutterError *_Nullable))completion; - (void)pause:(FVPTextureMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; - (void)setMixWithOthers:(FVPMixWithOthersMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFVPAVFoundationVideoPlayerApi( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FVPAVFoundationVideoPlayerApi> *_Nullable api); NS_ASSUME_NONNULL_END
packages/packages/video_player/video_player_avfoundation/darwin/Classes/messages.g.h/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/messages.g.h", "repo_id": "packages", "token_count": 1718 }
1,037
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; void main() { test( 'VideoPlayerOptions controls defaults to VideoPlayerWebOptionsControls.disabled()', () { const VideoPlayerWebOptions options = VideoPlayerWebOptions(); expect(options.controls, const VideoPlayerWebOptionsControls.disabled()); }, ); test( 'VideoPlayerOptions allowContextMenu defaults to true', () { const VideoPlayerWebOptions options = VideoPlayerWebOptions(); expect(options.allowContextMenu, isTrue); }, ); test( 'VideoPlayerOptions allowRemotePlayback defaults to true', () { const VideoPlayerWebOptions options = VideoPlayerWebOptions(); expect(options.allowRemotePlayback, isTrue); }, ); }
packages/packages/video_player/video_player_platform_interface/test/video_player_web_options_test.dart/0
{ "file_path": "packages/packages/video_player/video_player_platform_interface/test/video_player_web_options_test.dart", "repo_id": "packages", "token_count": 310 }
1,038
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'package:web/web.dart' as web; /// Adds a "disablePictureInPicture" setter to [web.HTMLVideoElement]s. extension NonStandardSettersOnVideoElement on web.HTMLVideoElement { external set disablePictureInPicture(JSBoolean disabled); } /// Adds a "disableRemotePlayback" and "controlsList" setters to [web.HTMLMediaElement]s. extension NonStandardSettersOnMediaElement on web.HTMLMediaElement { external set disableRemotePlayback(JSBoolean disabled); external set controlsList(JSString? controlsList); }
packages/packages/video_player/video_player_web/lib/src/pkg_web_tweaks.dart/0
{ "file_path": "packages/packages/video_player/video_player_web/lib/src/pkg_web_tweaks.dart", "repo_id": "packages", "token_count": 201 }
1,039
// 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 library contains code that's common between the client and the server. /// /// The code must be compilable both as a command-line program and as a web /// program. library web_benchmarks.common; /// The number of samples we use to collect statistics from. const int kMeasuredSampleCount = 100; /// A special value returned by the `/next-benchmark` HTTP POST request when /// all benchmarks have run and there are no more benchmarks to run. const String kEndOfBenchmarks = '__end_of_benchmarks__'; /// The default initial page to load upon opening the benchmark app or reloading /// it in Chrome. const String defaultInitialPage = 'index.html';
packages/packages/web_benchmarks/lib/src/common.dart/0
{ "file_path": "packages/packages/web_benchmarks/lib/src/common.dart", "repo_id": "packages", "token_count": 207 }
1,040
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:web_benchmarks/client.dart'; import '../about_page.dart' show backKey; import '../home_page.dart' show aboutPageKey, textKey; import '../main.dart'; /// A recorder that measures frame building durations. abstract class AppRecorder extends WidgetRecorder { AppRecorder({required this.benchmarkName}) : super(name: benchmarkName); final String benchmarkName; // ignore: unreachable_from_main Future<void> automate(); @override Widget createWidget() { Future<void>.delayed(const Duration(milliseconds: 400), automate); return const MyApp(); } Future<void> animationStops() async { while (WidgetsBinding.instance.hasScheduledFrame) { await Future<void>.delayed(const Duration(milliseconds: 200)); } } } class ScrollRecorder extends AppRecorder { ScrollRecorder() : super(benchmarkName: 'scroll'); @override Future<void> automate() async { final ScrollableState scrollable = Scrollable.of(find.byKey(textKey).evaluate().single); await scrollable.position.animateTo( 30000, curve: Curves.linear, duration: const Duration(seconds: 20), ); } } class PageRecorder extends AppRecorder { PageRecorder() : super(benchmarkName: 'page'); bool _completed = false; @override bool shouldContinue() => profile.shouldContinue() || !_completed; @override Future<void> automate() async { final LiveWidgetController controller = LiveWidgetController(WidgetsBinding.instance); for (int i = 0; i < 10; ++i) { print('Testing round $i...'); await controller.tap(find.byKey(aboutPageKey)); await animationStops(); await controller.tap(find.byKey(backKey)); await animationStops(); } _completed = true; } } class TapRecorder extends AppRecorder { TapRecorder() : super(benchmarkName: 'tap'); bool _completed = false; @override bool shouldContinue() => profile.shouldContinue() || !_completed; @override Future<void> automate() async { final LiveWidgetController controller = LiveWidgetController(WidgetsBinding.instance); for (int i = 0; i < 10; ++i) { print('Testing round $i...'); await controller.tap(find.byIcon(Icons.add)); await animationStops(); } _completed = true; } } Future<void> main() async { await runBenchmarks(<String, RecorderFactory>{ 'scroll': () => ScrollRecorder(), 'page': () => PageRecorder(), 'tap': () => TapRecorder(), }); }
packages/packages/web_benchmarks/testing/test_app/lib/benchmarks/runner.dart/0
{ "file_path": "packages/packages/web_benchmarks/testing/test_app/lib/benchmarks/runner.dart", "repo_id": "packages", "token_count": 941 }
1,041
# WebView for Flutter <?code-excerpt path-base="example/lib"?> [![pub package](https://img.shields.io/pub/v/webview_flutter.svg)](https://pub.dev/packages/webview_flutter) A Flutter plugin that provides a WebView widget. On iOS the WebView widget is backed by a [WKWebView](https://developer.apple.com/documentation/webkit/wkwebview). On Android the WebView widget is backed by a [WebView](https://developer.android.com/reference/android/webkit/WebView). | | Android | iOS | |-------------|----------------|-------| | **Support** | SDK 19+ or 20+ | 12.0+ | ## Usage Add `webview_flutter` as a [dependency in your pubspec.yaml file](https://pub.dev/packages/webview_flutter/install). You can now display a WebView by: 1. Instantiating a [WebViewController](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewController-class.html). <?code-excerpt "simple_example.dart (webview_controller)"?> ```dart controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(const Color(0x00000000)) ..setNavigationDelegate( NavigationDelegate( onProgress: (int progress) { // Update loading bar. }, onPageStarted: (String url) {}, onPageFinished: (String url) {}, onWebResourceError: (WebResourceError error) {}, onNavigationRequest: (NavigationRequest request) { if (request.url.startsWith('https://www.youtube.com/')) { return NavigationDecision.prevent; } return NavigationDecision.navigate; }, ), ) ..loadRequest(Uri.parse('https://flutter.dev')); ``` 2. Passing the controller to a [WebViewWidget](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewWidget-class.html). <?code-excerpt "simple_example.dart (webview_widget)"?> ```dart @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Flutter Simple Example')), body: WebViewWidget(controller: controller), ); } ``` See the Dartdocs for [WebViewController](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewController-class.html) and [WebViewWidget](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewWidget-class.html) for more details. ### Android Platform Views This plugin uses [Platform Views](https://flutter.dev/docs/development/platform-integration/platform-views) to embed the Android’s WebView within the Flutter app. You should however make sure to set the correct `minSdkVersion` in `android/app/build.gradle` if it was previously lower than 19: ```groovy android { defaultConfig { minSdkVersion 19 } } ``` ### Platform-Specific Features Many classes have a subclass or an underlying implementation that provides access to platform-specific features. To access platform-specific features, start by adding the platform implementation packages to your app or package: * **Android**: [webview_flutter_android](https://pub.dev/packages/webview_flutter_android/install) * **iOS**: [webview_flutter_wkwebview](https://pub.dev/packages/webview_flutter_wkwebview/install) Next, add the imports of the implementation packages to your app or package: <?code-excerpt "main.dart (platform_imports)"?> ```dart // Import for Android features. import 'package:webview_flutter_android/webview_flutter_android.dart'; // Import for iOS features. import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; ``` Now, additional features can be accessed through the platform implementations. Classes [WebViewController], [WebViewWidget], [NavigationDelegate], and [WebViewCookieManager] pass their functionality to a class provided by the current platform. Below are a couple of ways to access additional functionality provided by the platform and is followed by an example. 1. Pass a creation params class provided by a platform implementation to a `fromPlatformCreationParams` constructor (e.g. `WebViewController.fromPlatformCreationParams`, `WebViewWidget.fromPlatformCreationParams`, etc.). 2. Call methods on a platform implementation of a class by using the `platform` field (e.g. `WebViewController.platform`, `WebViewWidget.platform`, etc.). Below is an example of setting additional iOS and Android parameters on the `WebViewController`. <?code-excerpt "main.dart (platform_features)"?> ```dart late final PlatformWebViewControllerCreationParams params; if (WebViewPlatform.instance is WebKitWebViewPlatform) { params = WebKitWebViewControllerCreationParams( allowsInlineMediaPlayback: true, mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{}, ); } else { params = const PlatformWebViewControllerCreationParams(); } final WebViewController controller = WebViewController.fromPlatformCreationParams(params); // ··· if (controller.platform is AndroidWebViewController) { AndroidWebViewController.enableDebugging(true); (controller.platform as AndroidWebViewController) .setMediaPlaybackRequiresUserGesture(false); } ``` See https://pub.dev/documentation/webview_flutter_android/latest/webview_flutter_android/webview_flutter_android-library.html for more details on Android features. See https://pub.dev/documentation/webview_flutter_wkwebview/latest/webview_flutter_wkwebview/webview_flutter_wkwebview-library.html for more details on iOS features. ### Enable Material Components for Android To use Material Components when the user interacts with input elements in the WebView, follow the steps described in the [Enabling Material Components instructions](https://flutter.dev/docs/deployment/android#enabling-material-components). ### Setting custom headers on POST requests Currently, setting custom headers when making a post request with the WebViewController's `loadRequest` method is not supported on Android. If you require this functionality, a workaround is to make the request manually, and then load the response data using `loadHtmlString` instead. ## Migrating from 3.0 to 4.0 ### Instantiating WebViewController In version 3.0 and below, `WebViewController` could only be retrieved in a callback after the `WebView` was added to the widget tree. Now, `WebViewController` must be instantiated and can be used before it is added to the widget tree. See `Usage` section above for an example. ### Replacing WebView Functionality The `WebView` class has been removed and its functionality has been split into `WebViewController` and `WebViewWidget`. `WebViewController` handles all functionality that is associated with the underlying web view provided by each platform. (e.g., loading a url, setting the background color of the underlying platform view, or clearing the cache). `WebViewWidget` takes a `WebViewController` and handles all Flutter widget related functionality (e.g., layout direction, gesture recognizers). See the Dartdocs for [WebViewController](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewController-class.html) and [WebViewWidget](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewWidget-class.html) for more details. ### PlatformView Implementation on Android The PlatformView implementation for Android uses Texture Layer Hybrid Composition on versions 23+ and automatically fallbacks to Hybrid Composition for version 19-23. See section `Platform-Specific Features` and [AndroidWebViewWidgetCreationParams.displayWithHybridComposition](https://pub.dev/documentation/webview_flutter_android/latest/webview_flutter_android/AndroidWebViewWidgetCreationParams/displayWithHybridComposition.html) to manually switch to Hybrid Composition on versions 23+. ### API Changes Below is a non-exhaustive list of changes to the API: * `WebViewController.clearCache` no longer clears local storage. Please use `WebViewController.clearLocalStorage`. * `WebViewController.clearCache` no longer reloads the page. * `WebViewController.loadUrl` has been removed. Please use `WebViewController.loadRequest`. * `WebViewController.evaluateJavascript` has been removed. Please use `WebViewController.runJavaScript` or `WebViewController.runJavaScriptReturningResult`. * `WebViewController.getScrollX` and `WebViewController.getScrollY` have been removed and have been replaced by `WebViewController.getScrollPosition`. * `WebViewController.runJavaScriptReturningResult` now returns an `Object` and not a `String`. This will attempt to return a `bool` or `num` if the return value can be parsed. * `WebView.initialCookies` has been removed. Use `WebViewCookieManager.setCookie` before calling `WebViewController.loadRequest`. * `CookieManager` is replaced by `WebViewCookieManager`. * `NavigationDelegate.onWebResourceError` callback includes errors that are not from the main frame. Use the `WebResourceError.isForMainFrame` field to filter errors. * The following fields from `WebView` have been moved to `NavigationDelegate`. They can be added to a WebView with `WebViewController.setNavigationDelegate`. * `WebView.navigationDelegate` -> `NavigationDelegate.onNavigationRequest` * `WebView.onPageStarted` -> `NavigationDelegate.onPageStarted` * `WebView.onPageFinished` -> `NavigationDelegate.onPageFinished` * `WebView.onProgress` -> `NavigationDelegate.onProgress` * `WebView.onWebResourceError` -> `NavigationDelegate.onWebResourceError` * The following fields from `WebView` have been moved to `WebViewController`: * `WebView.javascriptMode` -> `WebViewController.setJavaScriptMode` * `WebView.javascriptChannels` -> `WebViewController.addJavaScriptChannel`/`WebViewController.removeJavaScriptChannel` * `WebView.zoomEnabled` -> `WebViewController.enableZoom` * `WebView.userAgent` -> `WebViewController.setUserAgent` * `WebView.backgroundColor` -> `WebViewController.setBackgroundColor` * The following features have been moved to an Android implementation class. See section `Platform-Specific Features` for details on accessing Android platform-specific features. * `WebView.debuggingEnabled` -> `static AndroidWebViewController.enableDebugging` * `WebView.initialMediaPlaybackPolicy` -> `AndroidWebViewController.setMediaPlaybackRequiresUserGesture` * The following features have been moved to an iOS implementation class. See section `Platform-Specific Features` for details on accessing iOS platform-specific features. * `WebView.gestureNavigationEnabled` -> `WebKitWebViewController.setAllowsBackForwardNavigationGestures` * `WebView.initialMediaPlaybackPolicy` -> `WebKitWebViewControllerCreationParams.mediaTypesRequiringUserAction` * `WebView.allowsInlineMediaPlayback` -> `WebKitWebViewControllerCreationParams.allowsInlineMediaPlayback` <!-- Links --> [WebViewController]: https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewController-class.html [WebViewWidget]: https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewWidget-class.html [NavigationDelegate]: https://pub.dev/documentation/webview_flutter/latest/webview_flutter/NavigationDelegate-class.html [WebViewCookieManager]: https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewCookieManager-class.html
packages/packages/webview_flutter/webview_flutter/README.md/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/README.md", "repo_id": "packages", "token_count": 3250 }
1,042
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; import 'package:webview_flutter/webview_flutter.dart'; // #docregion platform_imports // Import for Android features. import 'package:webview_flutter_android/webview_flutter_android.dart'; // Import for iOS features. import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; // #enddocregion platform_imports void main() => runApp(const MaterialApp(home: WebViewExample())); const String kNavigationExamplePage = ''' <!DOCTYPE html><html> <head><title>Navigation Delegate Example</title></head> <body> <p> The navigation delegate is set to block navigation to the youtube website. </p> <ul> <ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul> <ul><a href="https://www.google.com/">https://www.google.com/</a></ul> </ul> </body> </html> '''; const String kLocalExamplePage = ''' <!DOCTYPE html> <html lang="en"> <head> <title>Load file or HTML string example</title> </head> <body> <h1>Local demo page</h1> <p> This is an example page used to demonstrate how to load a local file or HTML string using the <a href="https://pub.dev/packages/webview_flutter">Flutter webview</a> plugin. </p> </body> </html> '''; const String kTransparentBackgroundPage = ''' <!DOCTYPE html> <html> <head> <title>Transparent background test</title> </head> <style type="text/css"> body { background: transparent; margin: 0; padding: 0; } #container { position: relative; margin: 0; padding: 0; width: 100vw; height: 100vh; } #shape { background: red; width: 200px; height: 200px; margin: 0; padding: 0; position: absolute; top: calc(50% - 100px); left: calc(50% - 100px); } p { text-align: center; } </style> <body> <div id="container"> <p>Transparent background test</p> <div id="shape"></div> </div> </body> </html> '''; const String kLogExamplePage = ''' <!DOCTYPE html> <html lang="en"> <head> <title>Load file or HTML string example</title> </head> <body onload="console.log('Logging that the page is loading.')"> <h1>Local demo page</h1> <p> This page is used to test the forwarding of console logs to Dart. </p> <style> .btn-group button { padding: 24px; 24px; display: block; width: 25%; margin: 5px 0px 0px 0px; } </style> <div class="btn-group"> <button onclick="console.error('This is an error message.')">Error</button> <button onclick="console.warn('This is a warning message.')">Warning</button> <button onclick="console.info('This is a info message.')">Info</button> <button onclick="console.debug('This is a debug message.')">Debug</button> <button onclick="console.log('This is a log message.')">Log</button> </div> </body> </html> '''; class WebViewExample extends StatefulWidget { const WebViewExample({super.key}); @override State<WebViewExample> createState() => _WebViewExampleState(); } class _WebViewExampleState extends State<WebViewExample> { late final WebViewController _controller; @override void initState() { super.initState(); // #docregion platform_features late final PlatformWebViewControllerCreationParams params; if (WebViewPlatform.instance is WebKitWebViewPlatform) { params = WebKitWebViewControllerCreationParams( allowsInlineMediaPlayback: true, mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{}, ); } else { params = const PlatformWebViewControllerCreationParams(); } final WebViewController controller = WebViewController.fromPlatformCreationParams(params); // #enddocregion platform_features controller ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(const Color(0x00000000)) ..setNavigationDelegate( NavigationDelegate( onProgress: (int progress) { debugPrint('WebView is loading (progress : $progress%)'); }, onPageStarted: (String url) { debugPrint('Page started loading: $url'); }, onPageFinished: (String url) { debugPrint('Page finished loading: $url'); }, onWebResourceError: (WebResourceError error) { debugPrint(''' Page resource error: code: ${error.errorCode} description: ${error.description} errorType: ${error.errorType} isForMainFrame: ${error.isForMainFrame} '''); }, onNavigationRequest: (NavigationRequest request) { if (request.url.startsWith('https://www.youtube.com/')) { debugPrint('blocking navigation to ${request.url}'); return NavigationDecision.prevent; } debugPrint('allowing navigation to ${request.url}'); return NavigationDecision.navigate; }, onUrlChange: (UrlChange change) { debugPrint('url change to ${change.url}'); }, onHttpAuthRequest: (HttpAuthRequest request) { openDialog(request); }, ), ) ..addJavaScriptChannel( 'Toaster', onMessageReceived: (JavaScriptMessage message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(message.message)), ); }, ) ..loadRequest(Uri.parse('https://flutter.dev')); // #docregion platform_features if (controller.platform is AndroidWebViewController) { AndroidWebViewController.enableDebugging(true); (controller.platform as AndroidWebViewController) .setMediaPlaybackRequiresUserGesture(false); } // #enddocregion platform_features _controller = controller; } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.green, appBar: AppBar( title: const Text('Flutter WebView example'), // This drop down menu demonstrates that Flutter widgets can be shown over the web view. actions: <Widget>[ NavigationControls(webViewController: _controller), SampleMenu(webViewController: _controller), ], ), body: WebViewWidget(controller: _controller), floatingActionButton: favoriteButton(), ); } Widget favoriteButton() { return FloatingActionButton( onPressed: () async { final String? url = await _controller.currentUrl(); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Favorited $url')), ); } }, child: const Icon(Icons.favorite), ); } Future<void> openDialog(HttpAuthRequest httpRequest) async { final TextEditingController usernameTextController = TextEditingController(); final TextEditingController passwordTextController = TextEditingController(); return showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { return AlertDialog( title: Text('${httpRequest.host}: ${httpRequest.realm ?? '-'}'), content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextField( decoration: const InputDecoration(labelText: 'Username'), autofocus: true, controller: usernameTextController, ), TextField( decoration: const InputDecoration(labelText: 'Password'), controller: passwordTextController, ), ], ), ), actions: <Widget>[ // Explicitly cancel the request on iOS as the OS does not emit new // requests when a previous request is pending. TextButton( onPressed: () { httpRequest.onCancel(); Navigator.of(context).pop(); }, child: const Text('Cancel'), ), TextButton( onPressed: () { httpRequest.onProceed( WebViewCredential( user: usernameTextController.text, password: passwordTextController.text, ), ); Navigator.of(context).pop(); }, child: const Text('Authenticate'), ), ], ); }, ); } } enum MenuOptions { showUserAgent, listCookies, clearCookies, addToCache, listCache, clearCache, navigationDelegate, doPostRequest, loadLocalFile, loadFlutterAsset, loadHtmlString, transparentBackground, setCookie, logExample, basicAuthentication, } class SampleMenu extends StatelessWidget { SampleMenu({ super.key, required this.webViewController, }); final WebViewController webViewController; late final WebViewCookieManager cookieManager = WebViewCookieManager(); @override Widget build(BuildContext context) { return PopupMenuButton<MenuOptions>( key: const ValueKey<String>('ShowPopupMenu'), onSelected: (MenuOptions value) { switch (value) { case MenuOptions.showUserAgent: _onShowUserAgent(); case MenuOptions.listCookies: _onListCookies(context); case MenuOptions.clearCookies: _onClearCookies(context); case MenuOptions.addToCache: _onAddToCache(context); case MenuOptions.listCache: _onListCache(); case MenuOptions.clearCache: _onClearCache(context); case MenuOptions.navigationDelegate: _onNavigationDelegateExample(); case MenuOptions.doPostRequest: _onDoPostRequest(); case MenuOptions.loadLocalFile: _onLoadLocalFileExample(); case MenuOptions.loadFlutterAsset: _onLoadFlutterAssetExample(); case MenuOptions.loadHtmlString: _onLoadHtmlStringExample(); case MenuOptions.transparentBackground: _onTransparentBackground(); case MenuOptions.setCookie: _onSetCookie(); case MenuOptions.logExample: _onLogExample(); case MenuOptions.basicAuthentication: _promptForUrl(context); } }, itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[ const PopupMenuItem<MenuOptions>( value: MenuOptions.showUserAgent, child: Text('Show user agent'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.listCookies, child: Text('List cookies'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.clearCookies, child: Text('Clear cookies'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.addToCache, child: Text('Add to cache'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.listCache, child: Text('List cache'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.clearCache, child: Text('Clear cache'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.navigationDelegate, child: Text('Navigation Delegate example'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.doPostRequest, child: Text('Post Request'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.loadHtmlString, child: Text('Load HTML string'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.loadLocalFile, child: Text('Load local file'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.loadFlutterAsset, child: Text('Load Flutter Asset'), ), const PopupMenuItem<MenuOptions>( key: ValueKey<String>('ShowTransparentBackgroundExample'), value: MenuOptions.transparentBackground, child: Text('Transparent background example'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.setCookie, child: Text('Set cookie'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.logExample, child: Text('Log example'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.basicAuthentication, child: Text('Basic Authentication Example'), ), ], ); } Future<void> _onShowUserAgent() { // Send a message with the user agent string to the Toaster JavaScript channel we registered // with the WebView. return webViewController.runJavaScript( 'Toaster.postMessage("User Agent: " + navigator.userAgent);', ); } Future<void> _onListCookies(BuildContext context) async { final String cookies = await webViewController .runJavaScriptReturningResult('document.cookie') as String; if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('Cookies:'), _getCookieList(cookies), ], ), )); } } Future<void> _onAddToCache(BuildContext context) async { await webViewController.runJavaScript( 'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";', ); if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Added a test entry to cache.'), )); } } Future<void> _onListCache() { return webViewController.runJavaScript('caches.keys()' // ignore: missing_whitespace_between_adjacent_strings '.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))' '.then((caches) => Toaster.postMessage(caches))'); } Future<void> _onClearCache(BuildContext context) async { await webViewController.clearCache(); await webViewController.clearLocalStorage(); if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Cache cleared.'), )); } } Future<void> _onClearCookies(BuildContext context) async { final bool hadCookies = await cookieManager.clearCookies(); String message = 'There were cookies. Now, they are gone!'; if (!hadCookies) { message = 'There are no cookies.'; } if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text(message), )); } } Future<void> _onNavigationDelegateExample() { final String contentBase64 = base64Encode( const Utf8Encoder().convert(kNavigationExamplePage), ); return webViewController.loadRequest( Uri.parse('data:text/html;base64,$contentBase64'), ); } Future<void> _onSetCookie() async { await cookieManager.setCookie( const WebViewCookie( name: 'foo', value: 'bar', domain: 'httpbin.org', path: '/anything', ), ); await webViewController.loadRequest(Uri.parse( 'https://httpbin.org/anything', )); } Future<void> _onDoPostRequest() { return webViewController.loadRequest( Uri.parse('https://httpbin.org/post'), method: LoadRequestMethod.post, headers: <String, String>{'foo': 'bar', 'Content-Type': 'text/plain'}, body: Uint8List.fromList('Test Body'.codeUnits), ); } Future<void> _onLoadLocalFileExample() async { final String pathToIndex = await _prepareLocalFile(); await webViewController.loadFile(pathToIndex); } Future<void> _onLoadFlutterAssetExample() { return webViewController.loadFlutterAsset('assets/www/index.html'); } Future<void> _onLoadHtmlStringExample() { return webViewController.loadHtmlString(kLocalExamplePage); } Future<void> _onTransparentBackground() { return webViewController.loadHtmlString(kTransparentBackgroundPage); } Widget _getCookieList(String cookies) { if (cookies == '""') { return Container(); } final List<String> cookieList = cookies.split(';'); final Iterable<Text> cookieWidgets = cookieList.map((String cookie) => Text(cookie)); return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: cookieWidgets.toList(), ); } static Future<String> _prepareLocalFile() async { final String tmpDir = (await getTemporaryDirectory()).path; final File indexFile = File( <String>{tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator)); await indexFile.create(recursive: true); await indexFile.writeAsString(kLocalExamplePage); return indexFile.path; } Future<void> _onLogExample() { webViewController .setOnConsoleMessage((JavaScriptConsoleMessage consoleMessage) { debugPrint( '== JS == ${consoleMessage.level.name}: ${consoleMessage.message}'); }); return webViewController.loadHtmlString(kLogExamplePage); } Future<void> _promptForUrl(BuildContext context) { final TextEditingController urlTextController = TextEditingController(); return showDialog<String>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Input URL to visit'), content: TextField( decoration: const InputDecoration(labelText: 'URL'), autofocus: true, controller: urlTextController, ), actions: <Widget>[ TextButton( onPressed: () { if (urlTextController.text.isNotEmpty) { final Uri? uri = Uri.tryParse(urlTextController.text); if (uri != null && uri.scheme.isNotEmpty) { webViewController.loadRequest(uri); Navigator.pop(context); } } }, child: const Text('Visit'), ), ], ); }, ); } } class NavigationControls extends StatelessWidget { const NavigationControls({super.key, required this.webViewController}); final WebViewController webViewController; @override Widget build(BuildContext context) { return Row( children: <Widget>[ IconButton( icon: const Icon(Icons.arrow_back_ios), onPressed: () async { if (await webViewController.canGoBack()) { await webViewController.goBack(); } else { if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('No back history item')), ); } } }, ), IconButton( icon: const Icon(Icons.arrow_forward_ios), onPressed: () async { if (await webViewController.canGoForward()) { await webViewController.goForward(); } else { if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('No forward history item')), ); } } }, ), IconButton( icon: const Icon(Icons.replay), onPressed: () => webViewController.reload(), ), ], ); } }
packages/packages/webview_flutter/webview_flutter/example/lib/main.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/example/lib/main.dart", "repo_id": "packages", "token_count": 8401 }
1,043
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.os.Build; import android.webkit.CookieManager; import androidx.annotation.ChecksSdkIntAtLeast; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.CookieManagerHostApi; import java.util.Objects; /** * Host API implementation for `CookieManager`. * * <p>This class may handle instantiating and adding native object instances that are attached to a * Dart instance or handle method calls on the associated native class or an instance of the class. */ public class CookieManagerHostApiImpl implements CookieManagerHostApi { // To ease adding additional methods, this value is added prematurely. @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private final CookieManagerProxy proxy; private final @NonNull AndroidSdkChecker sdkChecker; // Interface for an injectable SDK version checker. @VisibleForTesting interface AndroidSdkChecker { @ChecksSdkIntAtLeast(parameter = 0) boolean sdkIsAtLeast(int version); } /** Proxy for constructors and static method of `CookieManager`. */ @VisibleForTesting static class CookieManagerProxy { /** Handles the Dart static method `MyClass.myStaticMethod`. */ @NonNull public CookieManager getInstance() { return CookieManager.getInstance(); } } /** * Constructs a {@link CookieManagerHostApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public CookieManagerHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this(binaryMessenger, instanceManager, new CookieManagerProxy()); } @VisibleForTesting CookieManagerHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull CookieManagerProxy proxy) { this( binaryMessenger, instanceManager, proxy, (int version) -> Build.VERSION.SDK_INT >= version); } @VisibleForTesting CookieManagerHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull CookieManagerProxy proxy, @NonNull AndroidSdkChecker sdkChecker) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; this.proxy = proxy; this.sdkChecker = sdkChecker; } @Override public void attachInstance(@NonNull Long instanceIdentifier) { instanceManager.addDartCreatedInstance(proxy.getInstance(), instanceIdentifier); } @Override public void setCookie(@NonNull Long identifier, @NonNull String url, @NonNull String value) { getCookieManagerInstance(identifier).setCookie(url, value); } @Override public void removeAllCookies( @NonNull Long identifier, @NonNull GeneratedAndroidWebView.Result<Boolean> result) { if (sdkChecker.sdkIsAtLeast(Build.VERSION_CODES.LOLLIPOP)) { getCookieManagerInstance(identifier).removeAllCookies(result::success); } else { result.success(removeCookiesPreL(getCookieManagerInstance(identifier))); } } @Override public void setAcceptThirdPartyCookies( @NonNull Long identifier, @NonNull Long webViewIdentifier, @NonNull Boolean accept) { if (sdkChecker.sdkIsAtLeast(Build.VERSION_CODES.LOLLIPOP)) { getCookieManagerInstance(identifier) .setAcceptThirdPartyCookies( Objects.requireNonNull(instanceManager.getInstance(webViewIdentifier)), accept); } else { throw new UnsupportedOperationException( "`setAcceptThirdPartyCookies` is unsupported on versions below `Build.VERSION_CODES.LOLLIPOP`."); } } /** * Removes all cookies from the given cookie manager, using the deprecated (pre-Lollipop) * implementation. * * @param cookieManager The cookie manager to clear all cookies from. * @return Whether any cookies were removed. */ @SuppressWarnings("deprecation") private boolean removeCookiesPreL(CookieManager cookieManager) { final boolean hasCookies = cookieManager.hasCookies(); if (hasCookies) { cookieManager.removeAllCookie(); } return hasCookies; } @NonNull private CookieManager getCookieManagerInstance(@NonNull Long identifier) { return Objects.requireNonNull(instanceManager.getInstance(identifier)); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/CookieManagerHostApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/CookieManagerHostApiImpl.java", "repo_id": "packages", "token_count": 1496 }
1,044
// 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.content.Context; import android.hardware.display.DisplayManager; import android.os.Build; import android.view.View; import android.view.ViewParent; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.annotation.ChecksSdkIntAtLeast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.android.FlutterView; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebViewHostApi; import java.util.Map; import java.util.Objects; /** * Host api implementation for {@link WebView}. * * <p>Handles creating {@link WebView}s that intercommunicate with a paired Dart object. */ public class WebViewHostApiImpl implements WebViewHostApi { private final InstanceManager instanceManager; private final WebViewProxy webViewProxy; private final BinaryMessenger binaryMessenger; private Context context; /** Handles creating and calling static methods for {@link WebView}s. */ public static class WebViewProxy { /** * Creates a {@link WebViewPlatformView}. * * @param context an Activity Context to access application assets * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager mangages instances used to communicate with the corresponding objects * in Dart * @return the created {@link WebViewPlatformView} */ @NonNull public WebViewPlatformView createWebView( @NonNull Context context, @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { return new WebViewPlatformView(context, binaryMessenger, instanceManager); } /** * Forwards call to {@link WebView#setWebContentsDebuggingEnabled}. * * @param enabled whether debugging should be enabled */ public void setWebContentsDebuggingEnabled(boolean enabled) { WebView.setWebContentsDebuggingEnabled(enabled); } } /** Implementation of {@link WebView} that can be used as a Flutter {@link PlatformView}s. */ @SuppressLint("ViewConstructor") public static class WebViewPlatformView extends WebView implements PlatformView { // To ease adding callback methods, this value is added prematurely. @SuppressWarnings("unused") private WebViewFlutterApiImpl api; private WebViewClient currentWebViewClient; private WebChromeClientHostApiImpl.SecureWebChromeClient currentWebChromeClient; private final @NonNull AndroidSdkChecker sdkChecker; // Interface for an injectable SDK version checker. @VisibleForTesting interface AndroidSdkChecker { @ChecksSdkIntAtLeast(parameter = 0) boolean sdkIsAtLeast(int version); } /** * Creates a {@link WebViewPlatformView}. * * @param context an Activity Context to access application assets. This value cannot be null. */ public WebViewPlatformView( @NonNull Context context, @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this( context, binaryMessenger, instanceManager, (int version) -> Build.VERSION.SDK_INT >= version); } @VisibleForTesting WebViewPlatformView( @NonNull Context context, @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager, @NonNull AndroidSdkChecker sdkChecker) { super(context); currentWebViewClient = new WebViewClient(); currentWebChromeClient = new WebChromeClientHostApiImpl.SecureWebChromeClient(); api = new WebViewFlutterApiImpl(binaryMessenger, instanceManager); this.sdkChecker = sdkChecker; setWebViewClient(currentWebViewClient); setWebChromeClient(currentWebChromeClient); } @Nullable @Override public View getView() { return this; } @Override public void dispose() {} // TODO(bparrishMines): This should be removed once https://github.com/flutter/engine/pull/40771 makes it to stable. // Temporary fix for https://github.com/flutter/flutter/issues/92165. The FlutterView is setting // setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS) which prevents this // view from automatically being traversed for autofill. @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (sdkChecker.sdkIsAtLeast(Build.VERSION_CODES.O)) { final FlutterView flutterView = tryFindFlutterView(); if (flutterView != null) { flutterView.setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES); } } } // Attempt to traverse the parents of this view until a FlutterView is found. private FlutterView tryFindFlutterView() { ViewParent currentView = this; while (currentView.getParent() != null) { currentView = currentView.getParent(); if (currentView instanceof FlutterView) { return (FlutterView) currentView; } } return null; } @Override public void setWebViewClient(@NonNull WebViewClient webViewClient) { super.setWebViewClient(webViewClient); currentWebViewClient = webViewClient; currentWebChromeClient.setWebViewClient(webViewClient); } @Override public void setWebChromeClient(@Nullable WebChromeClient client) { super.setWebChromeClient(client); if (!(client instanceof WebChromeClientHostApiImpl.SecureWebChromeClient)) { throw new AssertionError("Client must be a SecureWebChromeClient."); } currentWebChromeClient = (WebChromeClientHostApiImpl.SecureWebChromeClient) client; currentWebChromeClient.setWebViewClient(currentWebViewClient); } // When running unit tests, the parent `WebView` class is replaced by a stub that returns null // for every method. This is overridden so that this returns the current WebChromeClient during // unit tests. This should only remain overridden as long as `setWebChromeClient` is overridden. @Nullable @Override public WebChromeClient getWebChromeClient() { return currentWebChromeClient; } @Override protected void onScrollChanged(int left, int top, int oldLeft, int oldTop) { super.onScrollChanged(left, top, oldLeft, oldTop); api.onScrollChanged( this, (long) left, (long) top, (long) oldLeft, (long) oldTop, reply -> {}); } /** * Flutter API used to send messages back to Dart. * * <p>This is only visible for testing. */ @SuppressWarnings("unused") @VisibleForTesting void setApi(WebViewFlutterApiImpl api) { this.api = api; } } /** * Creates a host API that handles creating {@link WebView}s and invoking its methods. * * @param instanceManager maintains instances stored to communicate with Dart objects * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param webViewProxy handles creating {@link WebView}s and calling its static methods * @param context an Activity Context to access application assets. This value cannot be null. */ public WebViewHostApiImpl( @NonNull InstanceManager instanceManager, @NonNull BinaryMessenger binaryMessenger, @NonNull WebViewProxy webViewProxy, @Nullable Context context) { this.instanceManager = instanceManager; this.binaryMessenger = binaryMessenger; this.webViewProxy = webViewProxy; this.context = context; } /** * Sets the context to construct {@link WebView}s. * * @param context the new context. */ public void setContext(@Nullable Context context) { this.context = context; } @Override public void create(@NonNull Long instanceId) { DisplayListenerProxy displayListenerProxy = new DisplayListenerProxy(); DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); displayListenerProxy.onPreWebViewInitialization(displayManager); final WebView webView = webViewProxy.createWebView(context, binaryMessenger, instanceManager); displayListenerProxy.onPostWebViewInitialization(displayManager); instanceManager.addDartCreatedInstance(webView, instanceId); } @Override public void loadData( @NonNull Long instanceId, @NonNull String data, @Nullable String mimeType, @Nullable String encoding) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.loadData(data, mimeType, encoding); } @Override public void loadDataWithBaseUrl( @NonNull Long instanceId, @Nullable String baseUrl, @NonNull String data, @Nullable String mimeType, @Nullable String encoding, @Nullable String historyUrl) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); } @Override public void loadUrl( @NonNull Long instanceId, @NonNull String url, @NonNull Map<String, String> headers) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.loadUrl(url, headers); } @Override public void postUrl(@NonNull Long instanceId, @NonNull String url, @NonNull byte[] data) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.postUrl(url, data); } @Nullable @Override public String getUrl(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return webView.getUrl(); } @NonNull @Override public Boolean canGoBack(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return webView.canGoBack(); } @NonNull @Override public Boolean canGoForward(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return webView.canGoForward(); } @Override public void goBack(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.goBack(); } @Override public void goForward(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.goForward(); } @Override public void reload(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.reload(); } @Override public void clearCache(@NonNull Long instanceId, @NonNull Boolean includeDiskFiles) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.clearCache(includeDiskFiles); } @Override public void evaluateJavascript( @NonNull Long instanceId, @NonNull String javascriptString, @NonNull GeneratedAndroidWebView.Result<String> result) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.evaluateJavascript(javascriptString, result::success); } @Nullable @Override public String getTitle(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return webView.getTitle(); } @Override public void scrollTo(@NonNull Long instanceId, @NonNull Long x, @NonNull Long y) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.scrollTo(x.intValue(), y.intValue()); } @Override public void scrollBy(@NonNull Long instanceId, @NonNull Long x, @NonNull Long y) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.scrollBy(x.intValue(), y.intValue()); } @NonNull @Override public Long getScrollX(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return (long) webView.getScrollX(); } @NonNull @Override public Long getScrollY(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return (long) webView.getScrollY(); } @NonNull @Override public GeneratedAndroidWebView.WebViewPoint getScrollPosition(@NonNull Long instanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return new GeneratedAndroidWebView.WebViewPoint.Builder() .setX((long) webView.getScrollX()) .setY((long) webView.getScrollY()) .build(); } @Override public void setWebContentsDebuggingEnabled(@NonNull Boolean enabled) { webViewProxy.setWebContentsDebuggingEnabled(enabled); } @Override public void setWebViewClient(@NonNull Long instanceId, @NonNull Long webViewClientInstanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.setWebViewClient(instanceManager.getInstance(webViewClientInstanceId)); } @SuppressLint("JavascriptInterface") @Override public void addJavaScriptChannel( @NonNull Long instanceId, @NonNull Long javaScriptChannelInstanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); final JavaScriptChannel javaScriptChannel = Objects.requireNonNull(instanceManager.getInstance(javaScriptChannelInstanceId)); webView.addJavascriptInterface(javaScriptChannel, javaScriptChannel.javaScriptChannelName); } @Override public void removeJavaScriptChannel( @NonNull Long instanceId, @NonNull Long javaScriptChannelInstanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); final JavaScriptChannel javaScriptChannel = Objects.requireNonNull((instanceManager.getInstance(javaScriptChannelInstanceId))); webView.removeJavascriptInterface(javaScriptChannel.javaScriptChannelName); } @Override public void setDownloadListener(@NonNull Long instanceId, @Nullable Long listenerInstanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.setDownloadListener( instanceManager.getInstance(Objects.requireNonNull(listenerInstanceId))); } @Override public void setWebChromeClient(@NonNull Long instanceId, @Nullable Long clientInstanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.setWebChromeClient( instanceManager.getInstance(Objects.requireNonNull(clientInstanceId))); } @Override public void setBackgroundColor(@NonNull Long instanceId, @NonNull Long color) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webView.setBackgroundColor(color.intValue()); } /** Maintains instances used to communicate with the corresponding WebView Dart object. */ @NonNull public InstanceManager getInstanceManager() { return instanceManager; } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewHostApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewHostApiImpl.java", "repo_id": "packages", "token_count": 5051 }
1,045
// 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.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.net.Uri; import android.os.Message; import android.view.View; import android.webkit.ConsoleMessage; import android.webkit.GeolocationPermissions; import android.webkit.PermissionRequest; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebView.WebViewTransport; import android.webkit.WebViewClient; import androidx.annotation.NonNull; import io.flutter.plugins.webviewflutter.WebChromeClientHostApiImpl.WebChromeClientCreator; import io.flutter.plugins.webviewflutter.WebChromeClientHostApiImpl.WebChromeClientImpl; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class WebChromeClientTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public WebChromeClientFlutterApiImpl mockFlutterApi; @Mock public WebView mockWebView; @Mock public WebViewClient mockWebViewClient; InstanceManager instanceManager; WebChromeClientHostApiImpl hostApiImpl; WebChromeClientImpl webChromeClient; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); final WebChromeClientCreator webChromeClientCreator = new WebChromeClientCreator() { @Override @NonNull public WebChromeClientImpl createWebChromeClient( @NonNull WebChromeClientFlutterApiImpl flutterApi) { webChromeClient = super.createWebChromeClient(flutterApi); return webChromeClient; } }; hostApiImpl = new WebChromeClientHostApiImpl(instanceManager, webChromeClientCreator, mockFlutterApi); hostApiImpl.create(2L); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test public void onProgressChanged() { webChromeClient.onProgressChanged(mockWebView, 23); verify(mockFlutterApi).onProgressChanged(eq(webChromeClient), eq(mockWebView), eq(23L), any()); } @Test public void onCreateWindow() { final WebView mockOnCreateWindowWebView = mock(WebView.class); // Create a fake message to transport requests to onCreateWindowWebView. final Message message = new Message(); message.obj = mock(WebViewTransport.class); webChromeClient.setWebViewClient(mockWebViewClient); assertTrue(webChromeClient.onCreateWindow(mockWebView, message, mockOnCreateWindowWebView)); /// Capture the WebViewClient used with onCreateWindow WebView. final ArgumentCaptor<WebViewClient> webViewClientCaptor = ArgumentCaptor.forClass(WebViewClient.class); verify(mockOnCreateWindowWebView).setWebViewClient(webViewClientCaptor.capture()); final WebViewClient onCreateWindowWebViewClient = webViewClientCaptor.getValue(); assertNotNull(onCreateWindowWebViewClient); /// Create a WebResourceRequest with a Uri. final WebResourceRequest mockRequest = mock(WebResourceRequest.class); when(mockRequest.getUrl()).thenReturn(mock(Uri.class)); when(mockRequest.getUrl().toString()).thenReturn("https://www.google.com"); // Test when the forwarding WebViewClient is overriding all url loading. when(mockWebViewClient.shouldOverrideUrlLoading(any(), any(WebResourceRequest.class))) .thenReturn(true); assertTrue( onCreateWindowWebViewClient.shouldOverrideUrlLoading( mockOnCreateWindowWebView, mockRequest)); verify(mockWebView, never()).loadUrl(any()); // Test when the forwarding WebViewClient is NOT overriding all url loading. when(mockWebViewClient.shouldOverrideUrlLoading(any(), any(WebResourceRequest.class))) .thenReturn(false); assertTrue( onCreateWindowWebViewClient.shouldOverrideUrlLoading( mockOnCreateWindowWebView, mockRequest)); verify(mockWebView).loadUrl("https://www.google.com"); } @Test public void onPermissionRequest() { final PermissionRequest mockRequest = mock(PermissionRequest.class); instanceManager.addDartCreatedInstance(mockRequest, 10); webChromeClient.onPermissionRequest(mockRequest); verify(mockFlutterApi).onPermissionRequest(eq(webChromeClient), eq(mockRequest), any()); } @Test public void onShowCustomView() { final View mockView = mock(View.class); instanceManager.addDartCreatedInstance(mockView, 10); final WebChromeClient.CustomViewCallback mockCustomViewCallback = mock(WebChromeClient.CustomViewCallback.class); instanceManager.addDartCreatedInstance(mockView, 12); webChromeClient.onShowCustomView(mockView, mockCustomViewCallback); verify(mockFlutterApi) .onShowCustomView(eq(webChromeClient), eq(mockView), eq(mockCustomViewCallback), any()); } @Test public void onHideCustomView() { webChromeClient.onHideCustomView(); verify(mockFlutterApi).onHideCustomView(eq(webChromeClient), any()); } public void onGeolocationPermissionsShowPrompt() { final GeolocationPermissions.Callback mockCallback = mock(GeolocationPermissions.Callback.class); webChromeClient.onGeolocationPermissionsShowPrompt("https://flutter.dev", mockCallback); verify(mockFlutterApi) .onGeolocationPermissionsShowPrompt( eq(webChromeClient), eq("https://flutter.dev"), eq(mockCallback), any()); } @Test public void onGeolocationPermissionsHidePrompt() { webChromeClient.onGeolocationPermissionsHidePrompt(); verify(mockFlutterApi).onGeolocationPermissionsHidePrompt(eq(webChromeClient), any()); } @Test public void onConsoleMessage() { webChromeClient.onConsoleMessage( new ConsoleMessage("message", "sourceId", 23, ConsoleMessage.MessageLevel.ERROR)); verify(mockFlutterApi).onConsoleMessage(eq(webChromeClient), any(), any()); } @Test public void setReturnValueForOnConsoleMessage() { webChromeClient.setReturnValueForOnConsoleMessage(true); assertTrue(webChromeClient.onConsoleMessage(null)); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebChromeClientTest.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebChromeClientTest.java", "repo_id": "packages", "token_count": 2254 }
1,046
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'android_webview.dart'; import 'android_webview_controller.dart'; /// Object specifying creation parameters for creating a [AndroidWebViewCookieManager]. /// /// When adding additional fields make sure they can be null or have a default /// value to avoid breaking changes. See [PlatformWebViewCookieManagerCreationParams] for /// more information. @immutable class AndroidWebViewCookieManagerCreationParams extends PlatformWebViewCookieManagerCreationParams { /// Creates a new [AndroidWebViewCookieManagerCreationParams] instance. const AndroidWebViewCookieManagerCreationParams._( // This parameter prevents breaking changes later. // ignore: avoid_unused_constructor_parameters PlatformWebViewCookieManagerCreationParams params, ) : super(); /// Creates a [AndroidWebViewCookieManagerCreationParams] instance based on [PlatformWebViewCookieManagerCreationParams]. factory AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( PlatformWebViewCookieManagerCreationParams params) { return AndroidWebViewCookieManagerCreationParams._(params); } } /// Handles all cookie operations for the Android platform. class AndroidWebViewCookieManager extends PlatformWebViewCookieManager { /// Creates a new [AndroidWebViewCookieManager]. AndroidWebViewCookieManager( PlatformWebViewCookieManagerCreationParams params, { CookieManager? cookieManager, }) : _cookieManager = cookieManager ?? CookieManager.instance, super.implementation( params is AndroidWebViewCookieManagerCreationParams ? params : AndroidWebViewCookieManagerCreationParams .fromPlatformWebViewCookieManagerCreationParams(params), ); final CookieManager _cookieManager; @override Future<bool> clearCookies() { return _cookieManager.removeAllCookies(); } @override Future<void> setCookie(WebViewCookie cookie) { if (!_isValidPath(cookie.path)) { throw ArgumentError( 'The path property for the provided cookie was not given a legal value.'); } return _cookieManager.setCookie( cookie.domain, '${Uri.encodeComponent(cookie.name)}=${Uri.encodeComponent(cookie.value)}; path=${cookie.path}', ); } bool _isValidPath(String path) { // Permitted ranges based on RFC6265bis: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1 for (final int char in path.codeUnits) { if ((char < 0x20 || char > 0x3A) && (char < 0x3C || char > 0x7E)) { return false; } } return true; } /// Sets whether the WebView should allow third party cookies to be set. /// /// Apps that target `Build.VERSION_CODES.KITKAT` or below default to allowing /// third party cookies. Apps targeting `Build.VERSION_CODES.LOLLIPOP` or /// later default to disallowing third party cookies. Future<void> setAcceptThirdPartyCookies( AndroidWebViewController controller, bool accept, ) { // ignore: invalid_use_of_visible_for_testing_member final WebView webView = WebView.api.instanceManager .getInstanceWithWeakReference(controller.webViewIdentifier)!; return _cookieManager.setAcceptThirdPartyCookies(webView, accept); } }
packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart", "repo_id": "packages", "token_count": 1156 }
1,047
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Object specifying creation parameters for creating a [PlatformNavigationDelegate]. /// /// Platform specific implementations can add additional fields by extending /// this class. /// /// {@tool sample} /// This example demonstrates how to extend the [PlatformNavigationDelegateCreationParams] to /// provide additional platform specific parameters. /// /// When extending [PlatformNavigationDelegateCreationParams] additional /// parameters should always accept `null` or have a default value to prevent /// breaking changes. /// /// ```dart /// class AndroidNavigationDelegateCreationParams extends PlatformNavigationDelegateCreationParams { /// AndroidNavigationDelegateCreationParams._( /// // This parameter prevents breaking changes later. /// // ignore: avoid_unused_constructor_parameters /// PlatformNavigationDelegateCreationParams params, { /// this.filter, /// }) : super(); /// /// factory AndroidNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams( /// PlatformNavigationDelegateCreationParams params, { /// String? filter, /// }) { /// return AndroidNavigationDelegateCreationParams._(params, filter: filter); /// } /// /// final String? filter; /// } /// ``` /// {@end-tool} @immutable class PlatformNavigationDelegateCreationParams { /// Used by the platform implementation to create a new [PlatformNavigationkDelegate]. const PlatformNavigationDelegateCreationParams(); }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_navigation_delegate_creation_params.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_navigation_delegate_creation_params.dart", "repo_id": "packages", "token_count": 454 }
1,048
name: webview_flutter_platform_interface description: A common platform interface for the webview_flutter plugin. repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview_flutter%22 # NOTE: We strongly prefer non-breaking changes, even at the expense of a # less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes version: 2.10.0 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter meta: ^1.7.0 plugin_platform_interface: ^2.1.7 dev_dependencies: build_runner: ^2.1.8 flutter_test: sdk: flutter mockito: 5.4.4 topics: - html - webview - webview-flutter
packages/packages/webview_flutter/webview_flutter_platform_interface/pubspec.yaml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/pubspec.yaml", "repo_id": "packages", "token_count": 306 }
1,049
## 3.13.0 * Adds `decidePolicyForNavigationResponse` to internal WKNavigationDelegate to support the `PlatformNavigationDelegate.onHttpError` callback. ## 3.12.0 * Adds support for `setOnScrollPositionChange` method to the `WebKitWebViewController`. ## 3.11.0 * Adds support to show JavaScript dialog. See `PlatformWebViewController.setOnJavaScriptAlertDialog`, `PlatformWebViewController.setOnJavaScriptConfirmDialog` and `PlatformWebViewController.setOnJavaScriptTextInputDialog`. ## 3.10.3 * Adds a check that throws an `ArgumentError` when `WebKitWebViewController.addJavaScriptChannel` receives a `JavaScriptChannelParams` with a name that is not unique. * Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6. ## 3.10.2 * Adds privacy manifest. ## 3.10.1 * Fixes new lint warnings. ## 3.10.0 * Adds support for `PlatformNavigationDelegate.setOnHttpAuthRequest`. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 3.9.4 * Updates to Pigeon 13. ## 3.9.3 * Fixes `use_build_context_synchronously` lint violations in the example app. ## 3.9.2 * Fixes error caused by calling `WKWebViewConfiguration.limitsNavigationsToAppBoundDomains` on versions below 14. ## 3.9.1 * Fixes bug where `WebkitWebViewController.getUserAgent` was incorrectly returning an empty String. ## 3.9.0 * Adds support for `PlatformWebViewController.getUserAgent`. ## 3.8.0 * Adds support to register a callback to receive JavaScript console messages. See `WebKitWebViewController.setOnConsoleMessage`. ## 3.7.4 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 3.7.3 * Fixes bug where the `PlatformWebViewWidget` was rebuilt unnecessarily. ## 3.7.2 * Fixes bug where `PlatformWebViewWidget` doesn't rebuild when the controller changes. ## 3.7.1 * Updates pigeon version to `10.1.4`. ## 3.7.0 * Adds support for `WebResouceError.url`. ## 3.6.3 * Introduces `NSError.toString` for better diagnostics. ## 3.6.2 * Fixes unawaited_futures violations. ## 3.6.1 * Fixes bug where a native `NSURL` could be removed from an `InstanceManager` if it is equal to an already present `NSURL`. * Fixes compile-time error from using `WKWebView.inspectable` on unsupported Xcode versions. ## 3.6.0 * Adds support to enable debugging of web contents on the latest versions of WebKit. See `WebKitWebViewController.setInspectable`. ## 3.5.0 * Adds support to limit navigation to pages within the app’s domain. See `WebKitWebViewControllerCreationParams.limitsNavigationsToAppBoundDomains`. ## 3.4.4 * Removes obsolete null checks on non-nullable values. ## 3.4.3 * Replace `describeEnum` with the `name` getter. ## 3.4.2 * Fixes an exception caused by the `onUrlChange` callback passing a null `NSUrl`. ## 3.4.1 * Fixes internal type conversion error. * Adds internal unknown enum values to handle api updates. ## 3.4.0 * Adds support for `PlatformWebViewController.setOnPlatformPermissionRequest`. ## 3.3.0 * Adds support for `PlatformNavigationDelegate.onUrlChange`. ## 3.2.4 * Updates pigeon to fix warnings with clang 15. * Updates minimum Flutter version to 3.3. * Fixes common typos in tests and documentation. ## 3.2.3 * Updates to `pigeon` version 7. ## 3.2.2 * Changes Objective-C to use relative imports. ## 3.2.1 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 3.2.0 * Updates minimum Flutter version to 3.3 and iOS 11. ## 3.1.1 * Updates links for the merge of flutter/plugins into flutter/packages. ## 3.1.0 * Adds support to access native `WKWebView`. ## 3.0.5 * Renames Pigeon output files. ## 3.0.4 * Fixes bug that prevented the web view from being garbage collected. ## 3.0.3 * Updates example code for `use_build_context_synchronously` lint. ## 3.0.2 * Updates code for stricter lint checks. ## 3.0.1 * Adds support for retrieving navigation type with internal class. * Updates README with details on contributing. * Updates pigeon dev dependency to `4.2.13`. ## 3.0.0 * **BREAKING CHANGE** Updates platform implementation to `2.0.0` release of `webview_flutter_platform_interface`. See [webview_flutter](https://pub.dev/packages/webview_flutter/versions/4.0.0) for updated usage. * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 2.9.5 * Updates imports for `prefer_relative_imports`. ## 2.9.4 * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Fixes typo in an internal method name, from `setCookieForInsances` to `setCookieForInstances`. ## 2.9.3 * Updates `webview_flutter_platform_interface` constraint to the correct minimum version. ## 2.9.2 * Fixes crash when an Objective-C object in `FWFInstanceManager` is released, but the dealloc callback is no longer available. ## 2.9.1 * Fixes regression where the behavior for the `UIScrollView` insets were removed. ## 2.9.0 * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316). * Replaces platform implementation with WebKit API built with pigeon. ## 2.8.1 * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231). ## 2.8.0 * Raises minimum Dart version to 2.17 and Flutter version to 3.0.0. ## 2.7.5 * Minor fixes for new analysis options. ## 2.7.4 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.7.3 * Removes two occurrences of the compiler warning: "'RequiresUserActionForMediaPlayback' is deprecated: first deprecated in ios 10.0". ## 2.7.2 * Fixes an integration test race condition. * Migrates deprecated `Scaffold.showSnackBar` to `ScaffoldMessenger` in example app. ## 2.7.1 * Fixes header import for cookie manager to be relative only. ## 2.7.0 * Adds implementation of the `loadFlutterAsset` method from the platform interface. ## 2.6.0 * Implements new cookie manager for setting cookies and providing initial cookies. ## 2.5.0 * Adds an option to set the background color of the webview. * Migrates from `analysis_options_legacy.yaml` to `analysis_options.yaml`. * Integration test fixes. * Updates to webview_flutter_platform_interface version 1.5.2. ## 2.4.0 * Implemented new `loadFile` and `loadHtmlString` methods from the platform interface. ## 2.3.0 * Implemented new `loadRequest` method from platform interface. ## 2.2.0 * Implemented new `runJavascript` and `runJavascriptReturningResult` methods in platform interface. ## 2.1.0 * Add `zoomEnabled` functionality. ## 2.0.14 * Update example App so navigation menu loads immediatly but only becomes available when `WebViewController` is available (same behavior as example App in webview_flutter package). ## 2.0.13 * Extract WKWebView implementation from `webview_flutter`.
packages/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md", "repo_id": "packages", "token_count": 2212 }
1,050
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import XCTest; #import <XCTest/XCTest.h> @interface FWFErrorTests : XCTestCase @end @implementation FWFErrorTests - (void)testNSErrorUserInfoKey { // These MUST match the String values in the Dart class NSErrorUserInfoKey. XCTAssertEqualObjects(NSLocalizedDescriptionKey, @"NSLocalizedDescription"); XCTAssertEqualObjects(NSURLErrorFailingURLStringErrorKey, @"NSErrorFailingURLStringKey"); } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFErrorTests.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFErrorTests.m", "repo_id": "packages", "token_count": 190 }
1,051
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFGeneratedWebKitApis.h" #import <WebKit/WebKit.h> NS_ASSUME_NONNULL_BEGIN /// Converts an FWFNSUrlRequestData to an NSURLRequest. /// /// @param data The data object containing information to create an NSURLRequest. /// /// @return An NSURLRequest or nil if data could not be converted. extern NSURLRequest *_Nullable FWFNativeNSURLRequestFromRequestData(FWFNSUrlRequestData *data); /// Converts an FWFNSHttpCookieData to an NSHTTPCookie. /// /// @param data The data object containing information to create an NSHTTPCookie. /// /// @return An NSHTTPCookie or nil if data could not be converted. extern NSHTTPCookie *_Nullable FWFNativeNSHTTPCookieFromCookieData(FWFNSHttpCookieData *data); /// Converts an FWFNSKeyValueObservingOptionsEnumData to an NSKeyValueObservingOptions. /// /// @param data The data object containing information to create an NSKeyValueObservingOptions. /// /// @return An NSKeyValueObservingOptions or -1 if data could not be converted. extern NSKeyValueObservingOptions FWFNativeNSKeyValueObservingOptionsFromEnumData( FWFNSKeyValueObservingOptionsEnumData *data); /// Converts an FWFNSHTTPCookiePropertyKeyEnumData to an NSHTTPCookiePropertyKey. /// /// @param data The data object containing information to create an NSHTTPCookiePropertyKey. /// /// @return An NSHttpCookiePropertyKey or nil if data could not be converted. extern NSHTTPCookiePropertyKey _Nullable FWFNativeNSHTTPCookiePropertyKeyFromEnumData( FWFNSHttpCookiePropertyKeyEnumData *data); /// Converts a WKUserScriptData to a WKUserScript. /// /// @param data The data object containing information to create a WKUserScript. /// /// @return A WKUserScript or nil if data could not be converted. extern WKUserScript *FWFNativeWKUserScriptFromScriptData(FWFWKUserScriptData *data); /// Converts an FWFWKUserScriptInjectionTimeEnumData to a WKUserScriptInjectionTime. /// /// @param data The data object containing information to create a WKUserScriptInjectionTime. /// /// @return A WKUserScriptInjectionTime or -1 if data could not be converted. extern WKUserScriptInjectionTime FWFNativeWKUserScriptInjectionTimeFromEnumData( FWFWKUserScriptInjectionTimeEnumData *data); /// Converts an FWFWKAudiovisualMediaTypeEnumData to a WKAudiovisualMediaTypes. /// /// @param data The data object containing information to create a WKAudiovisualMediaTypes. /// /// @return A WKAudiovisualMediaType or -1 if data could not be converted. extern WKAudiovisualMediaTypes FWFNativeWKAudiovisualMediaTypeFromEnumData( FWFWKAudiovisualMediaTypeEnumData *data); /// Converts an FWFWKWebsiteDataTypeEnumData to a WKWebsiteDataType. /// /// @param data The data object containing information to create a WKWebsiteDataType. /// /// @return A WKWebsiteDataType or nil if data could not be converted. extern NSString *_Nullable FWFNativeWKWebsiteDataTypeFromEnumData( FWFWKWebsiteDataTypeEnumData *data); /// Converts a WKNavigationAction to an FWFWKNavigationActionData. /// /// @param action The object containing information to create a WKNavigationActionData. /// /// @return A FWFWKNavigationActionData. extern FWFWKNavigationActionData *FWFWKNavigationActionDataFromNativeWKNavigationAction( WKNavigationAction *action); /// Converts a NSURLRequest to an FWFNSUrlRequestData. /// /// @param request The object containing information to create a WKNavigationActionData. /// /// @return A FWFNSUrlRequestData. extern FWFNSUrlRequestData *FWFNSUrlRequestDataFromNativeNSURLRequest(NSURLRequest *request); /** * Converts a WKNavigationResponse to an FWFWKNavigationResponseData. * * @param response The object containing information to create a WKNavigationResponseData. * * @return A FWFWKNavigationResponseData. */ extern FWFWKNavigationResponseData *FWFWKNavigationResponseDataFromNativeNavigationResponse( WKNavigationResponse *response); /** * Converts a NSURLResponse to an FWFNSHttpUrlResponseData. * * @param response The object containing information to create a WKNavigationActionData. * * @return A FWFNSHttpUrlResponseData. */ extern FWFNSHttpUrlResponseData *FWFNSHttpUrlResponseDataFromNativeNSURLResponse( NSURLResponse *response); /** * Converts a WKFrameInfo to an FWFWKFrameInfoData. * * @param info The object containing information to create a FWFWKFrameInfoData. * * @return A FWFWKFrameInfoData. */ extern FWFWKFrameInfoData *FWFWKFrameInfoDataFromNativeWKFrameInfo(WKFrameInfo *info); /// Converts an FWFWKNavigationActionPolicyEnumData to a WKNavigationActionPolicy. /// /// @param data The data object containing information to create a WKNavigationActionPolicy. /// /// @return A WKNavigationActionPolicy or -1 if data could not be converted. extern WKNavigationActionPolicy FWFNativeWKNavigationActionPolicyFromEnumData( FWFWKNavigationActionPolicyEnumData *data); /** * Converts an FWFWKNavigationResponsePolicyEnumData to a WKNavigationResponsePolicy. * * @param policy The data object containing information to create a WKNavigationResponsePolicy. * * @return A WKNavigationResponsePolicy or -1 if data could not be converted. */ extern WKNavigationResponsePolicy FWFNativeWKNavigationResponsePolicyFromEnum( FWFWKNavigationResponsePolicyEnum policy); /** * Converts a NSError to an FWFNSErrorData. * * @param error The object containing information to create a FWFNSErrorData. * * @return A FWFNSErrorData. */ extern FWFNSErrorData *FWFNSErrorDataFromNativeNSError(NSError *error); /// Converts an NSKeyValueChangeKey to a FWFNSKeyValueChangeKeyEnumData. /// /// @param key The data object containing information to create a FWFNSKeyValueChangeKeyEnumData. /// /// @return A FWFNSKeyValueChangeKeyEnumData. extern FWFNSKeyValueChangeKeyEnumData *FWFNSKeyValueChangeKeyEnumDataFromNativeNSKeyValueChangeKey( NSKeyValueChangeKey key); /// Converts a WKScriptMessage to an FWFWKScriptMessageData. /// /// @param message The object containing information to create a FWFWKScriptMessageData. /// /// @return A FWFWKScriptMessageData. extern FWFWKScriptMessageData *FWFWKScriptMessageDataFromNativeWKScriptMessage( WKScriptMessage *message); /// Converts a WKNavigationType to an FWFWKNavigationType. /// /// @param type The object containing information to create a FWFWKNavigationType /// /// @return A FWFWKNavigationType. extern FWFWKNavigationType FWFWKNavigationTypeFromNativeWKNavigationType(WKNavigationType type); /// Converts a WKSecurityOrigin to an FWFWKSecurityOriginData. /// /// @param origin The object containing information to create an FWFWKSecurityOriginData. /// /// @return An FWFWKSecurityOriginData. extern FWFWKSecurityOriginData *FWFWKSecurityOriginDataFromNativeWKSecurityOrigin( WKSecurityOrigin *origin); /// Converts an FWFWKPermissionDecisionData to a WKPermissionDecision. /// /// @param data The data object containing information to create a WKPermissionDecision. /// /// @return A WKPermissionDecision or -1 if data could not be converted. API_AVAILABLE(ios(15.0)) extern WKPermissionDecision FWFNativeWKPermissionDecisionFromData( FWFWKPermissionDecisionData *data); /// Converts an WKMediaCaptureType to a FWFWKMediaCaptureTypeData. /// /// @param type The data object containing information to create a FWFWKMediaCaptureTypeData. /// /// @return A FWFWKMediaCaptureTypeData or nil if data could not be converted. API_AVAILABLE(ios(15.0)) extern FWFWKMediaCaptureTypeData *FWFWKMediaCaptureTypeDataFromNativeWKMediaCaptureType( WKMediaCaptureType type); /// Converts an FWFNSUrlSessionAuthChallengeDisposition to an NSURLSessionAuthChallengeDisposition. /// /// @param value The object containing information to create an /// NSURLSessionAuthChallengeDisposition. /// /// @return A NSURLSessionAuthChallengeDisposition or -1 if data could not be converted. extern NSURLSessionAuthChallengeDisposition FWFNativeNSURLSessionAuthChallengeDispositionFromFWFNSUrlSessionAuthChallengeDisposition( FWFNSUrlSessionAuthChallengeDisposition value); /// Converts an FWFNSUrlCredentialPersistence to an NSURLCredentialPersistence. /// /// @param value The object containing information to create an NSURLCredentialPersistence. /// /// @return A NSURLCredentialPersistence or -1 if data could not be converted. extern NSURLCredentialPersistence FWFNativeNSURLCredentialPersistenceFromFWFNSUrlCredentialPersistence( FWFNSUrlCredentialPersistence value); NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.h", "repo_id": "packages", "token_count": 2560 }
1,052
// 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 "FWFScriptMessageHandlerHostApi.h" #import "FWFDataConverters.h" @interface FWFScriptMessageHandlerFlutterApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFScriptMessageHandlerFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self initWithBinaryMessenger:binaryMessenger]; if (self) { _instanceManager = instanceManager; } return self; } - (long)identifierForHandler:(FWFScriptMessageHandler *)instance { return [self.instanceManager identifierWithStrongReferenceForInstance:instance]; } - (void)didReceiveScriptMessageForHandler:(FWFScriptMessageHandler *)instance userContentController:(WKUserContentController *)userContentController message:(WKScriptMessage *)message completion:(void (^)(FlutterError *_Nullable))completion { NSInteger userContentControllerIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:userContentController]; FWFWKScriptMessageData *messageData = FWFWKScriptMessageDataFromNativeWKScriptMessage(message); [self didReceiveScriptMessageForHandlerWithIdentifier:[self identifierForHandler:instance] userContentControllerIdentifier:userContentControllerIdentifier message:messageData completion:completion]; } @end @implementation FWFScriptMessageHandler - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [super initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; if (self) { _scriptMessageHandlerAPI = [[FWFScriptMessageHandlerFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; } return self; } - (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message { [self.scriptMessageHandlerAPI didReceiveScriptMessageForHandler:self userContentController:userContentController message:message completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } @end @interface FWFScriptMessageHandlerHostApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFScriptMessageHandlerHostApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (FWFScriptMessageHandler *)scriptMessageHandlerForIdentifier:(NSNumber *)identifier { return (FWFScriptMessageHandler *)[self.instanceManager instanceForIdentifier:identifier.longValue]; } - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error { FWFScriptMessageHandler *scriptMessageHandler = [[FWFScriptMessageHandler alloc] initWithBinaryMessenger:self.binaryMessenger instanceManager:self.instanceManager]; [self.instanceManager addDartCreatedInstance:scriptMessageHandler withIdentifier:identifier]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScriptMessageHandlerHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScriptMessageHandlerHostApi.m", "repo_id": "packages", "token_count": 1675 }
1,053
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFURLProtectionSpaceHostApi.h" @interface FWFURLProtectionSpaceFlutterApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFURLProtectionSpaceFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; _api = [[FWFNSUrlProtectionSpaceFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; } return self; } - (void)createWithInstance:(NSURLProtectionSpace *)instance host:(nullable NSString *)host realm:(nullable NSString *)realm authenticationMethod:(nullable NSString *)authenticationMethod completion:(void (^)(FlutterError *_Nullable))completion { if (![self.instanceManager containsInstance:instance]) { [self.api createWithIdentifier:[self.instanceManager addHostCreatedInstance:instance] host:host realm:realm authenticationMethod:authenticationMethod completion:completion]; } } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLProtectionSpaceHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLProtectionSpaceHostApi.m", "repo_id": "packages", "token_count": 548 }
1,054
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart'; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart'; import 'package:webview_flutter_wkwebview/src/webkit_proxy.dart'; import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); group('WebKitNavigationDelegate', () { test('WebKitNavigationDelegate uses params field in constructor', () async { await runZonedGuarded( () async => WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ), (Object error, __) { expect(error, isNot(isA<TypeError>())); }, ); }); test('setOnPageFinished', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final String callbackUrl; webKitDelegate.setOnPageFinished((String url) => callbackUrl = url); CapturingNavigationDelegate.lastCreatedDelegate.didFinishNavigation!( WKWebView.detached(), 'https://www.google.com', ); expect(callbackUrl, 'https://www.google.com'); }); test('setOnPageStarted', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final String callbackUrl; webKitDelegate.setOnPageStarted((String url) => callbackUrl = url); CapturingNavigationDelegate .lastCreatedDelegate.didStartProvisionalNavigation!( WKWebView.detached(), 'https://www.google.com', ); expect(callbackUrl, 'https://www.google.com'); }); test('setOnHttpError from decidePolicyForNavigationResponse', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final HttpResponseError callbackError; void onHttpError(HttpResponseError error) { callbackError = error; } webKitDelegate.setOnHttpError(onHttpError); CapturingNavigationDelegate .lastCreatedDelegate.decidePolicyForNavigationResponse!( WKWebView.detached(), const WKNavigationResponse( response: NSHttpUrlResponse(statusCode: 401), forMainFrame: true), ); expect(callbackError.response?.statusCode, 401); }); test('setOnHttpError is not called for error codes < 400', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); HttpResponseError? callbackError; void onHttpError(HttpResponseError error) { callbackError = error; } webKitDelegate.setOnHttpError(onHttpError); CapturingNavigationDelegate .lastCreatedDelegate.decidePolicyForNavigationResponse!( WKWebView.detached(), const WKNavigationResponse( response: NSHttpUrlResponse(statusCode: 399), forMainFrame: true), ); expect(callbackError, isNull); }); test('onWebResourceError from didFailNavigation', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final WebKitWebResourceError callbackError; void onWebResourceError(WebResourceError error) { callbackError = error as WebKitWebResourceError; } webKitDelegate.setOnWebResourceError(onWebResourceError); CapturingNavigationDelegate.lastCreatedDelegate.didFailNavigation!( WKWebView.detached(), const NSError( code: WKErrorCode.webViewInvalidated, domain: 'domain', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSURLErrorFailingURLStringError: 'www.flutter.dev', NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); expect(callbackError.description, 'my desc'); expect(callbackError.errorCode, WKErrorCode.webViewInvalidated); expect(callbackError.url, 'www.flutter.dev'); expect(callbackError.domain, 'domain'); expect(callbackError.errorType, WebResourceErrorType.webViewInvalidated); expect(callbackError.isForMainFrame, true); }); test('onWebResourceError from didFailProvisionalNavigation', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final WebKitWebResourceError callbackError; void onWebResourceError(WebResourceError error) { callbackError = error as WebKitWebResourceError; } webKitDelegate.setOnWebResourceError(onWebResourceError); CapturingNavigationDelegate .lastCreatedDelegate.didFailProvisionalNavigation!( WKWebView.detached(), const NSError( code: WKErrorCode.webViewInvalidated, domain: 'domain', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSURLErrorFailingURLStringError: 'www.flutter.dev', NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); expect(callbackError.description, 'my desc'); expect(callbackError.url, 'www.flutter.dev'); expect(callbackError.errorCode, WKErrorCode.webViewInvalidated); expect(callbackError.domain, 'domain'); expect(callbackError.errorType, WebResourceErrorType.webViewInvalidated); expect(callbackError.isForMainFrame, true); }); test('onWebResourceError from webViewWebContentProcessDidTerminate', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final WebKitWebResourceError callbackError; void onWebResourceError(WebResourceError error) { callbackError = error as WebKitWebResourceError; } webKitDelegate.setOnWebResourceError(onWebResourceError); CapturingNavigationDelegate .lastCreatedDelegate.webViewWebContentProcessDidTerminate!( WKWebView.detached(), ); expect(callbackError.description, ''); expect(callbackError.errorCode, WKErrorCode.webContentProcessTerminated); expect(callbackError.domain, 'WKErrorDomain'); expect( callbackError.errorType, WebResourceErrorType.webContentProcessTerminated, ); expect(callbackError.isForMainFrame, true); }); test('onNavigationRequest from decidePolicyForNavigationAction', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final NavigationRequest callbackRequest; FutureOr<NavigationDecision> onNavigationRequest( NavigationRequest request) { callbackRequest = request; return NavigationDecision.navigate; } webKitDelegate.setOnNavigationRequest(onNavigationRequest); expect( CapturingNavigationDelegate .lastCreatedDelegate.decidePolicyForNavigationAction!( WKWebView.detached(), const WKNavigationAction( request: NSUrlRequest(url: 'https://www.google.com'), targetFrame: WKFrameInfo( isMainFrame: false, request: NSUrlRequest(url: 'https://google.com')), navigationType: WKNavigationType.linkActivated, ), ), completion(WKNavigationActionPolicy.allow), ); expect(callbackRequest.url, 'https://www.google.com'); expect(callbackRequest.isMainFrame, isFalse); }); test('onHttpBasicAuthRequest emits host and realm', () { final WebKitNavigationDelegate iosNavigationDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, ), ), ); String? callbackHost; String? callbackRealm; iosNavigationDelegate.setOnHttpAuthRequest((HttpAuthRequest request) { callbackHost = request.host; callbackRealm = request.realm; }); const String expectedHost = 'expectedHost'; const String expectedRealm = 'expectedRealm'; CapturingNavigationDelegate .lastCreatedDelegate.didReceiveAuthenticationChallenge!( WKWebView.detached(), NSUrlAuthenticationChallenge.detached( protectionSpace: NSUrlProtectionSpace.detached( host: expectedHost, realm: expectedRealm, authenticationMethod: NSUrlAuthenticationMethod.httpBasic, ), ), (NSUrlSessionAuthChallengeDisposition disposition, NSUrlCredential? credential) {}); expect(callbackHost, expectedHost); expect(callbackRealm, expectedRealm); }); }); } // Records the last created instance of itself. class CapturingNavigationDelegate extends WKNavigationDelegate { CapturingNavigationDelegate({ super.didFinishNavigation, super.didStartProvisionalNavigation, super.decidePolicyForNavigationResponse, super.didFailNavigation, super.didFailProvisionalNavigation, super.decidePolicyForNavigationAction, super.webViewWebContentProcessDidTerminate, super.didReceiveAuthenticationChallenge, }) : super.detached() { lastCreatedDelegate = this; } static CapturingNavigationDelegate lastCreatedDelegate = CapturingNavigationDelegate(); } // Records the last created instance of itself. class CapturingUIDelegate extends WKUIDelegate { CapturingUIDelegate({ super.onCreateWebView, super.requestMediaCapturePermission, super.runJavaScriptAlertDialog, super.runJavaScriptConfirmDialog, super.runJavaScriptTextInputDialog, super.instanceManager, }) : super.detached() { lastCreatedDelegate = this; } static CapturingUIDelegate lastCreatedDelegate = CapturingUIDelegate(); }
packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.dart", "repo_id": "packages", "token_count": 4814 }
1,055
# XDG Directories Demo ## Description This is a simple demo of the xdg_directories package.
packages/packages/xdg_directories/example/README.md/0
{ "file_path": "packages/packages/xdg_directories/example/README.md", "repo_id": "packages", "token_count": 28 }
1,056
# The list of external dependencies that are allowed as pinned dependencies. # See https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#Dependencies # # All entries here should have an explanation for why they are here. # TODO(stuartmorgan): Eliminate this in favor of standardizing on # mockito. See https://github.com/flutter/flutter/issues/130757 - mocktail # Test-only dependency, so does not impact package clients, and # has limited impact so could be easily removed if there are # ever maintenance issues in the future. - lcov_parser # This should be removed; see # https://github.com/flutter/flutter/issues/130897 - provider ## Allowed by default # Dart-owned - dart_style - mockito # Google-owned - file_testing
packages/script/configs/allowed_pinned_deps.yaml/0
{ "file_path": "packages/script/configs/allowed_pinned_deps.yaml", "repo_id": "packages", "token_count": 219 }
1,057
# Packages that are excluded from dart unit test on Windows. # Exclude flutter_image because its tests need a test server, so are run via custom_package_tests. - flutter_image # This test is very slow, so isn't worth running a second time # on Windows; the Linux run is enough coverage. - flutter_migrate # TODO(stuartmorgan): Fix these tests to run correctly on a # Windows host and enable them. - path_provider_linux - webview_flutter_android # Unit tests for plugins that support web currently run in # Chrome, which isn't currently supported by web infrastructure. # TODO(ditman): Fix this in the repo tooling. - camera_web - file_selector_web - google_maps_flutter_web - google_sign_in_web - image_picker_for_web - shared_preferences_web - url_launcher_web - video_player_web - webview_flutter_web
packages/script/configs/windows_unit_tests_exceptions.yaml/0
{ "file_path": "packages/script/configs/windows_unit_tests_exceptions.yaml", "repo_id": "packages", "token_count": 240 }
1,058
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:yaml/yaml.dart'; import 'core.dart'; import 'repository_package.dart'; /// Possible plugin support options for a platform. enum PlatformSupport { /// The platform has an implementation in the package. inline, /// The platform has an endorsed federated implementation in another package. federated, } /// Returns true if [package] is a Flutter plugin. bool isFlutterPlugin(RepositoryPackage package) { return _readPluginPubspecSection(package) != null; } /// Returns true if [package] is a Flutter [platform] plugin. /// /// It checks this by looking for the following pattern in the pubspec: /// /// flutter: /// plugin: /// platforms: /// [platform]: /// /// If [requiredMode] is provided, the plugin must have the given type of /// implementation in order to return true. bool pluginSupportsPlatform( String platform, RepositoryPackage plugin, { PlatformSupport? requiredMode, }) { assert(platform == platformIOS || platform == platformAndroid || platform == platformWeb || platform == platformMacOS || platform == platformWindows || platform == platformLinux); final YamlMap? platformEntry = _readPlatformPubspecSectionForPlugin(platform, plugin); if (platformEntry == null) { return false; } // If the platform entry is present, then it supports the platform. Check // for required mode if specified. if (requiredMode != null) { final bool federated = platformEntry.containsKey('default_package'); if (federated != (requiredMode == PlatformSupport.federated)) { return false; } } return true; } /// Returns true if [plugin] includes native code for [platform], as opposed to /// being implemented entirely in Dart. bool pluginHasNativeCodeForPlatform(String platform, RepositoryPackage plugin) { if (platform == platformWeb) { // Web plugins are always Dart-only. return false; } final YamlMap? platformEntry = _readPlatformPubspecSectionForPlugin(platform, plugin); if (platformEntry == null) { return false; } // All other platforms currently use pluginClass for indicating the native // code in the plugin. final String? pluginClass = platformEntry['pluginClass'] as String?; // TODO(stuartmorgan): Remove the check for 'none' once none of the plugins // in the repository use that workaround. See // https://github.com/flutter/flutter/issues/57497 for context. return pluginClass != null && pluginClass != 'none'; } /// Returns the /// flutter: /// plugin: /// platforms: /// [platform]: /// section from [plugin]'s pubspec.yaml, or null if either it is not present, /// or the pubspec couldn't be read. YamlMap? _readPlatformPubspecSectionForPlugin( String platform, RepositoryPackage plugin) { final YamlMap? pluginSection = _readPluginPubspecSection(plugin); if (pluginSection == null) { return null; } final YamlMap? platforms = pluginSection['platforms'] as YamlMap?; if (platforms == null) { return null; } return platforms[platform] as YamlMap?; } /// Returns the /// flutter: /// plugin: /// platforms: /// section from [plugin]'s pubspec.yaml, or null if either it is not present, /// or the pubspec couldn't be read. YamlMap? _readPluginPubspecSection(RepositoryPackage package) { final Pubspec pubspec = package.parsePubspec(); final Map<String, dynamic>? flutterSection = pubspec.flutter; if (flutterSection == null) { return null; } return flutterSection['plugin'] as YamlMap?; }
packages/script/tool/lib/src/common/plugin_utils.dart/0
{ "file_path": "packages/script/tool/lib/src/common/plugin_utils.dart", "repo_id": "packages", "token_count": 1129 }
1,059
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:meta/meta.dart'; import 'package:pub_semver/pub_semver.dart'; import 'common/core.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/plugin_utils.dart'; import 'common/repository_package.dart'; /// The lowest `ext.kotlin_version` that example apps are allowed to use. @visibleForTesting final Version minKotlinVersion = Version(1, 7, 10); /// A command to enforce gradle file conventions and best practices. class GradleCheckCommand extends PackageLoopingCommand { /// Creates an instance of the gradle check command. GradleCheckCommand(super.packagesDir); @override final String name = 'gradle-check'; @override List<String> get aliases => <String>['check-gradle']; @override final String description = 'Checks that gradle files follow repository conventions.'; @override bool get hasLongOutput => false; @override PackageLoopingType get packageLoopingType => PackageLoopingType.includeAllSubpackages; @override Future<PackageResult> runForPackage(RepositoryPackage package) async { if (!package.platformDirectory(FlutterPlatform.android).existsSync()) { return PackageResult.skip('No android/ directory.'); } const String exampleDirName = 'example'; final bool isExample = package.directory.basename == exampleDirName || package.directory.parent.basename == exampleDirName; if (!_validateBuildGradles(package, isExample: isExample)) { return PackageResult.fail(); } return PackageResult.success(); } bool _validateBuildGradles(RepositoryPackage package, {required bool isExample}) { final Directory androidDir = package.platformDirectory(FlutterPlatform.android); final File topLevelGradleFile = _getBuildGradleFile(androidDir); // This is tracked as a variable rather than a sequence of &&s so that all // failures are reported at once, not just the first one. bool succeeded = true; if (isExample) { if (!_validateExampleTopLevelBuildGradle(package, topLevelGradleFile)) { succeeded = false; } final File topLevelSettingsGradleFile = _getSettingsGradleFile(androidDir); if (!_validateExampleTopLevelSettingsGradle( package, topLevelSettingsGradleFile)) { succeeded = false; } final File appGradleFile = _getBuildGradleFile(androidDir.childDirectory('app')); if (!_validateExampleAppBuildGradle(package, appGradleFile)) { succeeded = false; } } else { succeeded = _validatePluginBuildGradle(package, topLevelGradleFile); } return succeeded; } // Returns the gradle file in the given directory. File _getBuildGradleFile(Directory dir) => dir.childFile('build.gradle'); // Returns the settings gradle file in the given directory. File _getSettingsGradleFile(Directory dir) => dir.childFile('settings.gradle'); // Returns the main/AndroidManifest.xml file for the given package. File _getMainAndroidManifest(RepositoryPackage package, {required bool isExample}) { final Directory androidDir = package.platformDirectory(FlutterPlatform.android); final Directory baseDir = isExample ? androidDir.childDirectory('app') : androidDir; return baseDir .childDirectory('src') .childDirectory('main') .childFile('AndroidManifest.xml'); } bool _isCommented(String line) => line.trim().startsWith('//'); /// Validates the build.gradle file for a plugin /// (some_plugin/android/build.gradle). bool _validatePluginBuildGradle(RepositoryPackage package, File gradleFile) { print('${indentation}Validating ' '${getRelativePosixPath(gradleFile, from: package.directory)}.'); final String contents = gradleFile.readAsStringSync(); final List<String> lines = contents.split('\n'); // This is tracked as a variable rather than a sequence of &&s so that all // failures are reported at once, not just the first one. bool succeeded = true; if (!_validateNamespace(package, contents, isExample: false)) { succeeded = false; } if (!_validateCompatibilityVersions(lines)) { succeeded = false; } if (!_validateGradleDrivenLintConfig(package, lines)) { succeeded = false; } return succeeded; } /// Documentation url for Artifact hub implementation in flutter repo's. @visibleForTesting static const String artifactHubDocumentationString = r'https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure'; /// String printed as example of valid example root build.gradle repository /// configuration that enables artifact hub env variable. @visibleForTesting static const String exampleRootGradleArtifactHubString = ''' // See $artifactHubDocumentationString for more info. def artifactRepoKey = 'ARTIFACT_HUB_REPOSITORY' if (System.getenv().containsKey(artifactRepoKey)) { println "Using artifact hub" maven { url System.getenv(artifactRepoKey) } } '''; /// Validates that [gradleLines] reads and uses a artifiact hub repository /// when ARTIFACT_HUB_REPOSITORY is set. /// /// Required in root gradle file. bool _validateArtifactHubUsage( RepositoryPackage example, List<String> gradleLines) { // Gradle variable name used to hold environment variable string. const String keyVariable = 'artifactRepoKey'; final RegExp keyPresentRegex = RegExp('$keyVariable' r"\s+=\s+'ARTIFACT_HUB_REPOSITORY'"); final RegExp documentationPresentRegex = RegExp( r'github\.com.*wiki.*Plugins-and-Packages-repository-structure.*gradle-structure'); final RegExp keyReadRegex = RegExp(r'if.*System\.getenv.*\.containsKey.*' '$keyVariable'); final RegExp keyUsedRegex = RegExp(r'maven.*url.*System\.getenv\(' '$keyVariable'); final bool keyPresent = gradleLines.any((String line) => keyPresentRegex.hasMatch(line)); final bool documentationPresent = gradleLines .any((String line) => documentationPresentRegex.hasMatch(line)); final bool keyRead = gradleLines.any((String line) => keyReadRegex.hasMatch(line)); final bool keyUsed = gradleLines.any((String line) => keyUsedRegex.hasMatch(line)); if (!(documentationPresent && keyPresent && keyRead && keyUsed)) { printError('Failed Artifact Hub validation. Include the following in ' 'example root build.gradle:\n$exampleRootGradleArtifactHubString'); } return keyPresent && documentationPresent && keyRead && keyUsed; } /// Validates the top-level settings.gradle for an example app (e.g., /// some_package/example/android/settings.gradle). bool _validateExampleTopLevelSettingsGradle( RepositoryPackage package, File gradleSettingsFile) { print('${indentation}Validating ' '${getRelativePosixPath(gradleSettingsFile, from: package.directory)}.'); final String contents = gradleSettingsFile.readAsStringSync(); final List<String> lines = contents.split('\n'); // This is tracked as a variable rather than a sequence of &&s so that all // failures are reported at once, not just the first one. bool succeeded = true; if (!_validateArtifactHubSettingsUsage(package, lines)) { succeeded = false; } return succeeded; } /// String printed as example of valid example root settings.gradle repository /// configuration that enables artifact hub env variable. @visibleForTesting static String exampleRootSettingsArtifactHubString = ''' // See $artifactHubDocumentationString for more info. buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath "gradle.plugin.com.google.cloud.artifactregistry:artifactregistry-gradle-plugin:2.2.1" } } apply plugin: "com.google.cloud.artifactregistry.gradle-plugin" '''; /// Validates that [gradleLines] reads and uses a artifiact hub repository /// when ARTIFACT_HUB_REPOSITORY is set. /// /// Required in root gradle file. bool _validateArtifactHubSettingsUsage( RepositoryPackage example, List<String> gradleLines) { final RegExp documentationPresentRegex = RegExp( r'github\.com.*wiki.*Plugins-and-Packages-repository-structure.*gradle-structure'); final RegExp artifactRegistryDefinitionRegex = RegExp( r'classpath.*gradle\.plugin\.com\.google\.cloud\.artifactregistry:artifactregistry-gradle-plugin'); final RegExp artifactRegistryPluginApplyRegex = RegExp( r'apply.*plugin.*com\.google\.cloud\.artifactregistry\.gradle-plugin'); final bool documentationPresent = gradleLines .any((String line) => documentationPresentRegex.hasMatch(line)); final bool artifactRegistryDefined = gradleLines .any((String line) => artifactRegistryDefinitionRegex.hasMatch(line)); final bool artifactRegistryPluginApplied = gradleLines .any((String line) => artifactRegistryPluginApplyRegex.hasMatch(line)); if (!(documentationPresent && artifactRegistryDefined && artifactRegistryPluginApplied)) { printError('Failed Artifact Hub validation. Include the following in ' 'example root settings.gradle:\n$exampleRootSettingsArtifactHubString'); } return documentationPresent && artifactRegistryDefined && artifactRegistryPluginApplied; } /// Validates the top-level build.gradle for an example app (e.g., /// some_package/example/android/build.gradle). bool _validateExampleTopLevelBuildGradle( RepositoryPackage package, File gradleFile) { print('${indentation}Validating ' '${getRelativePosixPath(gradleFile, from: package.directory)}.'); final String contents = gradleFile.readAsStringSync(); final List<String> lines = contents.split('\n'); // This is tracked as a variable rather than a sequence of &&s so that all // failures are reported at once, not just the first one. bool succeeded = true; if (!_validateJavacLintConfig(package, lines)) { succeeded = false; } if (!_validateKotlinVersion(package, lines)) { succeeded = false; } if (!_validateArtifactHubUsage(package, lines)) { succeeded = false; } return succeeded; } /// Validates the app-level build.gradle for an example app (e.g., /// some_package/example/android/app/build.gradle). bool _validateExampleAppBuildGradle( RepositoryPackage package, File gradleFile) { print('${indentation}Validating ' '${getRelativePosixPath(gradleFile, from: package.directory)}.'); final String contents = gradleFile.readAsStringSync(); // This is tracked as a variable rather than a sequence of &&s so that all // failures are reported at once, not just the first one. bool succeeded = true; if (!_validateNamespace(package, contents, isExample: true)) { succeeded = false; } return succeeded; } /// Validates that [gradleContents] sets a namespace, which is required for /// compatibility with apps that use AGP 8+. bool _validateNamespace(RepositoryPackage package, String gradleContents, {required bool isExample}) { final RegExp namespaceRegex = RegExp('^\\s*namespace\\s+[\'"](.*?)[\'"]', multiLine: true); final RegExpMatch? namespaceMatch = namespaceRegex.firstMatch(gradleContents); // For plugins, make sure the namespace is conditionalized so that it // doesn't break client apps using AGP 4.1 and earlier (which don't have // a namespace property, and will fail to build if it's set). const String namespaceConditional = 'if (project.android.hasProperty("namespace"))'; String exampleSetNamespace = "namespace 'dev.flutter.foo'"; if (!isExample) { exampleSetNamespace = ''' $namespaceConditional { $exampleSetNamespace }'''; } // Wrap the namespace command in an `android` block, adding the indentation // to make it line up correctly. final String exampleAndroidNamespaceBlock = ''' android { ${exampleSetNamespace.split('\n').join('\n ')} } '''; if (namespaceMatch == null) { final String errorMessage = ''' build.gradle must set a "namespace": $exampleAndroidNamespaceBlock The value must match the "package" attribute in AndroidManifest.xml, if one is present. For more information, see: https://developer.android.com/build/publish-library/prep-lib-release#choose-namespace '''; printError( '$indentation${errorMessage.split('\n').join('\n$indentation')}'); return false; } else { if (!isExample && !gradleContents.contains(namespaceConditional)) { final String errorMessage = ''' build.gradle for a plugin must conditionalize "namespace": $exampleAndroidNamespaceBlock '''; printError( '$indentation${errorMessage.split('\n').join('\n$indentation')}'); return false; } return _validateNamespaceMatchesManifest(package, isExample: isExample, namespace: namespaceMatch.group(1)!); } } /// Validates that the given namespace matches the manifest package of /// [package] (if any; a package does not need to be in the manifest in cases /// where compatibility with AGP <7 is no longer required). /// /// Prints an error and returns false if validation fails. bool _validateNamespaceMatchesManifest(RepositoryPackage package, {required bool isExample, required String namespace}) { final RegExp manifestPackageRegex = RegExp(r'package\s*=\s*"(.*?)"'); final String manifestContents = _getMainAndroidManifest(package, isExample: isExample) .readAsStringSync(); final RegExpMatch? packageMatch = manifestPackageRegex.firstMatch(manifestContents); if (packageMatch != null && namespace != packageMatch.group(1)) { final String errorMessage = ''' build.gradle "namespace" must match the "package" attribute in AndroidManifest.xml, if one is present. build.gradle namespace: "$namespace" AndroidMastifest.xml package: "${packageMatch.group(1)}" '''; printError( '$indentation${errorMessage.split('\n').join('\n$indentation')}'); return false; } return true; } /// Checks for a source compatibiltiy version, so that it's explicit rather /// than using whatever the client's local toolchaing defaults to (which can /// lead to compile errors that show up for clients, but not in CI). bool _validateCompatibilityVersions(List<String> gradleLines) { final bool hasLanguageVersion = gradleLines.any((String line) => line.contains('languageVersion') && !_isCommented(line)); final bool hasCompabilityVersions = gradleLines.any((String line) => line.contains('sourceCompatibility') && !_isCommented(line)) && // Newer toolchains default targetCompatibility to the same value as // sourceCompatibility, but older toolchains require it to be set // explicitly. The exact version cutoff (and of which piece of the // toolchain; likely AGP) is unknown; for context see // https://github.com/flutter/flutter/issues/125482 gradleLines.any((String line) => line.contains('targetCompatibility') && !_isCommented(line)); if (!hasLanguageVersion && !hasCompabilityVersions) { const String errorMessage = ''' build.gradle must set an explicit Java compatibility version. This can be done either via "sourceCompatibility"/"targetCompatibility": android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } or "toolchain": java { toolchain { languageVersion = JavaLanguageVersion.of(8) } } See: https://docs.gradle.org/current/userguide/java_plugin.html#toolchain_and_compatibility for more details.'''; printError( '$indentation${errorMessage.split('\n').join('\n$indentation')}'); return false; } return true; } /// Returns whether the given gradle content is configured to enable all /// Gradle-driven lints (those checked by ./gradlew lint) and treat them as /// errors. bool _validateGradleDrivenLintConfig( RepositoryPackage package, List<String> gradleLines) { final List<String> gradleBuildContents = package .platformDirectory(FlutterPlatform.android) .childFile('build.gradle') .readAsLinesSync(); if (!gradleBuildContents.any((String line) => line.contains('checkAllWarnings true') && !_isCommented(line)) || !gradleBuildContents.any((String line) => line.contains('warningsAsErrors true') && !_isCommented(line))) { printError('${indentation}This package is not configured to enable all ' 'Gradle-driven lint warnings and treat them as errors. ' 'Please add the following to the lintOptions section of ' 'android/build.gradle:'); print(''' checkAllWarnings true warningsAsErrors true '''); return false; } return true; } /// Validates whether the given [example]'s gradle content is configured to /// build its plugin target with javac lints enabled and treated as errors, /// if the enclosing package is a plugin. /// /// This can only be called on example packages. (Plugin packages should not /// be configured this way, since it would affect clients.) /// /// If [example]'s enclosing package is not a plugin package, this just /// returns true. bool _validateJavacLintConfig( RepositoryPackage example, List<String> gradleLines) { final RepositoryPackage enclosingPackage = example.getEnclosingPackage()!; if (!pluginSupportsPlatform(platformAndroid, enclosingPackage, requiredMode: PlatformSupport.inline)) { return true; } final String enclosingPackageName = enclosingPackage.directory.basename; // The check here is intentionally somewhat loose, to allow for the // possibility of variations (e.g., not using Xlint:all in some cases, or // passing other arguments). if (!(gradleLines.any((String line) => line.contains('project(":$enclosingPackageName")')) && gradleLines.any((String line) => line.contains('options.compilerArgs') && line.contains('-Xlint') && line.contains('-Werror')))) { printError('The example ' '"${getRelativePosixPath(example.directory, from: enclosingPackage.directory)}" ' 'is not configured to treat javac lints and warnings as errors. ' 'Please add the following to its build.gradle:'); print(''' gradle.projectsEvaluated { project(":$enclosingPackageName") { tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:all" << "-Werror" } } } '''); return false; } return true; } /// Validates whether the given [example] has its Kotlin version set to at /// least a minimum value, if it is set at all. bool _validateKotlinVersion( RepositoryPackage example, List<String> gradleLines) { final RegExp kotlinVersionRegex = RegExp(r"ext\.kotlin_version\s*=\s*'([\d.]+)'"); RegExpMatch? match; if (gradleLines.any((String line) { match = kotlinVersionRegex.firstMatch(line); return match != null; })) { final Version version = Version.parse(match!.group(1)!); if (version < minKotlinVersion) { printError('build.gradle sets "ext.kotlin_version" to "$version". The ' 'minimum Kotlin version that can be specified is ' '$minKotlinVersion, for compatibility with modern dependencies.'); return false; } } return true; } }
packages/script/tool/lib/src/gradle_check_command.dart/0
{ "file_path": "packages/script/tool/lib/src/gradle_check_command.dart", "repo_id": "packages", "token_count": 6896 }
1,060
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pub_semver/pub_semver.dart'; import 'package:yaml_edit/yaml_edit.dart'; import 'common/core.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/repository_package.dart'; const int _exitUnknownVersion = 3; /// A command to update the minimum Flutter and Dart SDKs of packages. class UpdateMinSdkCommand extends PackageLoopingCommand { /// Creates a publish metadata updater command instance. UpdateMinSdkCommand(super.packagesDir) { argParser.addOption(_flutterMinFlag, mandatory: true, help: 'The minimum version of Flutter to set SDK constraints to.'); } static const String _flutterMinFlag = 'flutter-min'; late final Version _flutterMinVersion; late final Version _dartMinVersion; @override final String name = 'update-min-sdk'; @override final String description = 'Updates the Flutter and Dart SDK minimums ' 'in pubspec.yaml to match the given Flutter version.'; @override final PackageLoopingType packageLoopingType = PackageLoopingType.includeAllSubpackages; @override bool get hasLongOutput => false; @override Future<void> initializeRun() async { _flutterMinVersion = Version.parse(getStringArg(_flutterMinFlag)); final Version? dartMinVersion = getDartSdkForFlutterSdk(_flutterMinVersion); if (dartMinVersion == null) { printError('Dart SDK version for Fluter SDK version ' '$_flutterMinVersion is unknown. ' 'Please update the map for getDartSdkForFlutterSdk with the ' 'corresponding Dart version.'); throw ToolExit(_exitUnknownVersion); } _dartMinVersion = dartMinVersion; } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final Pubspec pubspec = package.parsePubspec(); const String environmentKey = 'environment'; const String dartSdkKey = 'sdk'; const String flutterSdkKey = 'flutter'; final VersionRange? dartRange = _sdkRange(pubspec, dartSdkKey); final VersionRange? flutterRange = _sdkRange(pubspec, flutterSdkKey); final YamlEditor editablePubspec = YamlEditor(package.pubspecFile.readAsStringSync()); if (dartRange != null && (dartRange.min ?? Version.none) < _dartMinVersion) { editablePubspec .update(<String>[environmentKey, dartSdkKey], '^$_dartMinVersion'); print('${indentation}Updating Dart minimum to $_dartMinVersion'); } if (flutterRange != null && (flutterRange.min ?? Version.none) < _flutterMinVersion) { editablePubspec.update(<String>[environmentKey, flutterSdkKey], VersionRange(min: _flutterMinVersion, includeMin: true).toString()); print('${indentation}Updating Flutter minimum to $_flutterMinVersion'); } package.pubspecFile.writeAsStringSync(editablePubspec.toString()); return PackageResult.success(); } /// Returns the given "environment" section's [key] constraint as a range, /// if the key is present and has a range. VersionRange? _sdkRange(Pubspec pubspec, String key) { final VersionConstraint? constraint = pubspec.environment?[key]; if (constraint is VersionRange) { return constraint; } return null; } }
packages/script/tool/lib/src/update_min_sdk_command.dart/0
{ "file_path": "packages/script/tool/lib/src/update_min_sdk_command.dart", "repo_id": "packages", "token_count": 1156 }
1,061
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/pub_utils.dart'; import 'package:test/test.dart'; import '../mocks.dart'; import '../util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); }); test('runs with Dart for a non-Flutter package by default', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); await runPubGet(package, processRunner, platform); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('dart', const <String>['pub', 'get'], package.path), ])); }); test('runs with Flutter for a Flutter package by default', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, isFlutter: true); final MockPlatform platform = MockPlatform(); await runPubGet(package, processRunner, platform); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('flutter', const <String>['pub', 'get'], package.path), ])); }); test('runs with Flutter for a Dart package when requested', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); await runPubGet(package, processRunner, platform, alwaysUseFlutter: true); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('flutter', const <String>['pub', 'get'], package.path), ])); }); test('uses the correct Flutter command on Windows', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, isFlutter: true); final MockPlatform platform = MockPlatform(isWindows: true); await runPubGet(package, processRunner, platform); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'flutter.bat', const <String>['pub', 'get'], package.path), ])); }); test('reports success', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); final bool result = await runPubGet(package, processRunner, platform); expect(result, true); }); test('reports failure', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get']) ]; final bool result = await runPubGet(package, processRunner, platform); expect(result, false); }); }
packages/script/tool/test/common/pub_utils_test.dart/0
{ "file_path": "packages/script/tool/test/common/pub_utils_test.dart", "repo_id": "packages", "token_count": 1095 }
1,062
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/lint_android_command.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { group('LintAndroidCommand', () { FileSystem fileSystem; late Directory packagesDir; late CommandRunner<void> runner; late MockPlatform mockPlatform; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); mockPlatform = MockPlatform(); processRunner = RecordingProcessRunner(); final LintAndroidCommand command = LintAndroidCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>( 'lint_android_test', 'Test for $LintAndroidCommand'); runner.addCommand(command); }); test('runs gradle lint', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, extraFiles: <String>[ 'example/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Directory androidDir = plugin.getExamples().first.platformDirectory(FlutterPlatform.android); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidDir.childFile('gradlew').path, const <String>['plugin1:lintDebug'], androidDir.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('runs on all examples', () async { final List<String> examples = <String>['example1', 'example2']; final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, examples: examples, extraFiles: <String>[ 'example/example1/android/gradlew', 'example/example2/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Iterable<Directory> exampleAndroidDirs = plugin.getExamples().map( (RepositoryPackage example) => example.platformDirectory(FlutterPlatform.android)); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ for (final Directory directory in exampleAndroidDirs) ProcessCall( directory.childFile('gradlew').path, const <String>['plugin1:lintDebug'], directory.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('runs --config-only build if gradlew is missing', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Directory androidDir = plugin.getExamples().first.platformDirectory(FlutterPlatform.android); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'apk', '--config-only'], plugin.getExamples().first.directory.path, ), ProcessCall( androidDir.childFile('gradlew').path, const <String>['plugin1:lintDebug'], androidDir.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('fails if gradlew generation fails', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['lint-android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('Unable to configure Gradle project'), ], )); }); test('fails if linting finds issues', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, extraFiles: <String>[ 'example/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final String gradlewPath = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path; processRunner.mockProcessesForExecutable[gradlewPath] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['lint-android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('The following packages had errors:'), ], )); }); test('skips non-Android plugins', () async { createFakePlugin('plugin1', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( output, containsAllInOrder( <Matcher>[ contains( 'SKIPPING: Plugin does not have an Android implementation.') ], )); }); test('skips non-inline plugins', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.federated) }); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( output, containsAllInOrder( <Matcher>[ contains( 'SKIPPING: Plugin does not have an Android implementation.') ], )); }); }); }
packages/script/tool/test/lint_android_command_test.dart/0
{ "file_path": "packages/script/tool/test/lint_android_command_test.dart", "repo_id": "packages", "token_count": 3266 }
1,063
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/file_utils.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/common/process_runner.dart'; import 'package:flutter_plugin_tools/src/common/repository_package.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:platform/platform.dart'; import 'package:quiver/collection.dart'; import 'mocks.dart'; export 'package:flutter_plugin_tools/src/common/repository_package.dart'; const String _defaultDartConstraint = '>=2.14.0 <4.0.0'; const String _defaultFlutterConstraint = '>=2.5.0'; /// Returns the exe name that command will use when running Flutter on /// [platform]. String getFlutterCommand(Platform platform) => platform.isWindows ? 'flutter.bat' : 'flutter'; /// Creates a packages directory in the given location. /// /// If [parentDir] is set the packages directory will be created there, /// otherwise [fileSystem] must be provided and it will be created an arbitrary /// location in that filesystem. Directory createPackagesDirectory( {Directory? parentDir, FileSystem? fileSystem}) { assert(parentDir != null || fileSystem != null, 'One of parentDir or fileSystem must be provided'); assert(fileSystem == null || fileSystem is MemoryFileSystem, 'If using a real filesystem, parentDir must be provided'); final Directory packagesDir = (parentDir ?? fileSystem!.currentDirectory).childDirectory('packages'); packagesDir.createSync(); return packagesDir; } /// Details for platform support in a plugin. @immutable class PlatformDetails { const PlatformDetails( this.type, { this.hasNativeCode = true, this.hasDartCode = false, }); /// The type of support for the platform. final PlatformSupport type; /// Whether or not the plugin includes native code. /// /// Ignored for web, which does not have native code. final bool hasNativeCode; /// Whether or not the plugin includes Dart code. /// /// Ignored for web, which always has native code. final bool hasDartCode; } /// Returns the 'example' directory for [package]. /// /// This is deliberately not a method on [RepositoryPackage] since actual tool /// code should essentially never need this, and instead be using /// [RepositoryPackage.getExamples] to avoid assuming there's a single example /// directory. However, needing to construct paths with the example directory /// is very common in test code. /// /// This returns a Directory rather than a RepositoryPackage because there is no /// guarantee that the returned directory is a package. Directory getExampleDir(RepositoryPackage package) { return package.directory.childDirectory('example'); } /// Creates a plugin package with the given [name] in [packagesDirectory]. /// /// [platformSupport] is a map of platform string to the support details for /// that platform. /// /// [extraFiles] is an optional list of plugin-relative paths, using Posix /// separators, of extra files to create in the plugin. RepositoryPackage createFakePlugin( String name, Directory parentDirectory, { List<String> examples = const <String>['example'], List<String> extraFiles = const <String>[], Map<String, PlatformDetails> platformSupport = const <String, PlatformDetails>{}, String? version = '0.0.1', String flutterConstraint = _defaultFlutterConstraint, String dartConstraint = _defaultDartConstraint, }) { final RepositoryPackage package = createFakePackage( name, parentDirectory, isFlutter: true, examples: examples, extraFiles: extraFiles, version: version, flutterConstraint: flutterConstraint, dartConstraint: dartConstraint, ); createFakePubspec( package, name: name, isPlugin: true, platformSupport: platformSupport, version: version, flutterConstraint: flutterConstraint, dartConstraint: dartConstraint, ); return package; } /// Creates a plugin package with the given [name] in [packagesDirectory]. /// /// [extraFiles] is an optional list of package-relative paths, using unix-style /// separators, of extra files to create in the package. /// /// If [includeCommonFiles] is true, common but non-critical files like /// CHANGELOG.md, README.md, and AUTHORS will be included. /// /// If non-null, [directoryName] will be used for the directory instead of /// [name]. RepositoryPackage createFakePackage( String name, Directory parentDirectory, { List<String> examples = const <String>['example'], List<String> extraFiles = const <String>[], bool isFlutter = false, String? version = '0.0.1', String flutterConstraint = _defaultFlutterConstraint, String dartConstraint = _defaultDartConstraint, bool includeCommonFiles = true, String? directoryName, String? publishTo, }) { final RepositoryPackage package = RepositoryPackage(parentDirectory.childDirectory(directoryName ?? name)); package.directory.createSync(recursive: true); package.libDirectory.createSync(); createFakePubspec(package, name: name, isFlutter: isFlutter, version: version, flutterConstraint: flutterConstraint, dartConstraint: dartConstraint, publishTo: publishTo); if (includeCommonFiles) { package.changelogFile.writeAsStringSync(''' ## $version * Some changes. '''); package.readmeFile.writeAsStringSync('A very useful package'); package.authorsFile.writeAsStringSync('Google Inc.'); } if (examples.length == 1) { createFakePackage('${name}_example', package.directory, directoryName: examples.first, examples: <String>[], includeCommonFiles: false, isFlutter: isFlutter, publishTo: 'none', flutterConstraint: flutterConstraint, dartConstraint: dartConstraint); } else if (examples.isNotEmpty) { final Directory examplesDirectory = getExampleDir(package)..createSync(); for (final String exampleName in examples) { createFakePackage(exampleName, examplesDirectory, examples: <String>[], includeCommonFiles: false, isFlutter: isFlutter, publishTo: 'none', flutterConstraint: flutterConstraint, dartConstraint: dartConstraint); } } final p.Context posixContext = p.posix; for (final String file in extraFiles) { childFileWithSubcomponents(package.directory, posixContext.split(file)) .createSync(recursive: true); } return package; } /// Creates a `pubspec.yaml` file for [package]. /// /// [platformSupport] is a map of platform string to the support details for /// that platform. If empty, no `plugin` entry will be created unless `isPlugin` /// is set to `true`. void createFakePubspec( RepositoryPackage package, { String name = 'fake_package', bool isFlutter = true, bool isPlugin = false, Map<String, PlatformDetails> platformSupport = const <String, PlatformDetails>{}, String? publishTo, String? version, String dartConstraint = _defaultDartConstraint, String flutterConstraint = _defaultFlutterConstraint, }) { isPlugin |= platformSupport.isNotEmpty; String environmentSection = ''' environment: sdk: "$dartConstraint" '''; String dependenciesSection = ''' dependencies: '''; String pluginSection = ''; // Add Flutter-specific entries if requested. if (isFlutter) { environmentSection += ''' flutter: "$flutterConstraint" '''; dependenciesSection += ''' flutter: sdk: flutter '''; if (isPlugin) { pluginSection += ''' flutter: plugin: platforms: '''; for (final MapEntry<String, PlatformDetails> platform in platformSupport.entries) { pluginSection += _pluginPlatformSection(platform.key, platform.value, name); } } } // Default to a fake server to avoid ever accidentally publishing something // from a test. Does not use 'none' since that changes the behavior of some // commands. final String publishToSection = 'publish_to: ${publishTo ?? 'http://no_pub_server.com'}'; final String yaml = ''' name: $name ${(version != null) ? 'version: $version' : ''} $publishToSection $environmentSection $dependenciesSection $pluginSection '''; package.pubspecFile.createSync(); package.pubspecFile.writeAsStringSync(yaml); } String _pluginPlatformSection( String platform, PlatformDetails support, String packageName) { String entry = ''; // Build the main plugin entry. if (support.type == PlatformSupport.federated) { entry = ''' $platform: default_package: ${packageName}_$platform '''; } else { final List<String> lines = <String>[ ' $platform:', ]; switch (platform) { case platformAndroid: lines.add(' package: io.flutter.plugins.fake'); continue nativeByDefault; nativeByDefault: case platformIOS: case platformLinux: case platformMacOS: case platformWindows: if (support.hasNativeCode) { final String className = platform == platformIOS ? 'FLTFakePlugin' : 'FakePlugin'; lines.add(' pluginClass: $className'); } if (support.hasDartCode) { lines.add(' dartPluginClass: FakeDartPlugin'); } case platformWeb: lines.addAll(<String>[ ' pluginClass: FakePlugin', ' fileName: ${packageName}_web.dart', ]); default: assert(false, 'Unrecognized platform: $platform'); break; } entry = '${lines.join('\n')}\n'; } return entry; } /// Run the command [runner] with the given [args] and return /// what was printed. /// A custom [errorHandler] can be used to handle the runner error as desired without throwing. Future<List<String>> runCapturingPrint( CommandRunner<void> runner, List<String> args, { void Function(Error error)? errorHandler, void Function(Exception error)? exceptionHandler, }) async { final List<String> prints = <String>[]; final ZoneSpecification spec = ZoneSpecification( print: (_, __, ___, String message) { prints.add(message); }, ); try { await Zone.current .fork(specification: spec) .run<Future<void>>(() => runner.run(args)); } on Error catch (e) { if (errorHandler == null) { rethrow; } errorHandler(e); } on Exception catch (e) { if (exceptionHandler == null) { rethrow; } exceptionHandler(e); } return prints; } /// Information about a process to return from [RecordingProcessRunner]. class FakeProcessInfo { const FakeProcessInfo(this.process, [this.expectedInitialArgs = const <String>[]]); /// The process to return. final io.Process process; /// The expected start of the argument array for the call. /// /// This does not have to be a full list of arguments, only enough of the /// start to ensure that the call is as expected. final List<String> expectedInitialArgs; } /// A mock [ProcessRunner] which records process calls. class RecordingProcessRunner extends ProcessRunner { final List<ProcessCall> recordedCalls = <ProcessCall>[]; /// Maps an executable to a list of processes that should be used for each /// successive call to it via [run], [runAndStream], or [start]. /// /// If `expectedInitialArgs` are provided for a fake process, trying to /// return that process when the arguments don't match will throw a /// [StateError]. This allows tests to enforce that the fake results are /// for the expected calls when the process name itself isn't enough to tell /// (e.g., multiple different `dart` or `flutter` calls), without going all /// the way to a complex argument matching scheme that can make tests /// difficult to write and debug. final Map<String, List<FakeProcessInfo>> mockProcessesForExecutable = <String, List<FakeProcessInfo>>{}; @override Future<int> runAndStream( String executable, List<String> args, { Directory? workingDir, Map<String, String>? environment, bool exitOnError = false, }) async { recordedCalls.add(ProcessCall(executable, args, workingDir?.path)); final io.Process? processToReturn = _getProcessToReturn(executable, args); final int exitCode = processToReturn == null ? 0 : await processToReturn.exitCode; if (exitOnError && (exitCode != 0)) { throw io.ProcessException(executable, args); } return Future<int>.value(exitCode); } /// Returns [io.ProcessResult] created from [mockProcessesForExecutable]. @override Future<io.ProcessResult> run( String executable, List<String> args, { Directory? workingDir, Map<String, String>? environment, bool exitOnError = false, bool logOnError = false, Encoding stdoutEncoding = io.systemEncoding, Encoding stderrEncoding = io.systemEncoding, }) async { recordedCalls.add(ProcessCall(executable, args, workingDir?.path)); final io.Process? process = _getProcessToReturn(executable, args); final List<String>? processStdout = await process?.stdout.transform(stdoutEncoding.decoder).toList(); final String stdout = processStdout?.join() ?? ''; final List<String>? processStderr = await process?.stderr.transform(stderrEncoding.decoder).toList(); final String stderr = processStderr?.join() ?? ''; final io.ProcessResult result = process == null ? io.ProcessResult(1, 0, '', '') : io.ProcessResult(process.pid, await process.exitCode, stdout, stderr); if (exitOnError && (result.exitCode != 0)) { throw io.ProcessException(executable, args); } return Future<io.ProcessResult>.value(result); } @override Future<io.Process> start(String executable, List<String> args, {Directory? workingDirectory}) async { recordedCalls.add(ProcessCall(executable, args, workingDirectory?.path)); return Future<io.Process>.value( _getProcessToReturn(executable, args) ?? MockProcess()); } io.Process? _getProcessToReturn(String executable, List<String> args) { final List<FakeProcessInfo> fakes = mockProcessesForExecutable[executable] ?? <FakeProcessInfo>[]; if (fakes.isNotEmpty) { final FakeProcessInfo fake = fakes.removeAt(0); if (args.length < fake.expectedInitialArgs.length || !listsEqual(args.sublist(0, fake.expectedInitialArgs.length), fake.expectedInitialArgs)) { throw StateError('Next fake process for $executable expects arguments ' '[${fake.expectedInitialArgs.join(', ')}] but was called with ' 'arguments [${args.join(', ')}]'); } return fake.process; } return null; } } /// A recorded process call. @immutable class ProcessCall { const ProcessCall(this.executable, this.args, this.workingDir); /// The executable that was called. final String executable; /// The arguments passed to [executable] in the call. final List<String> args; /// The working directory this process was called from. final String? workingDir; @override bool operator ==(Object other) { return other is ProcessCall && executable == other.executable && listsEqual(args, other.args) && workingDir == other.workingDir; } @override int get hashCode => Object.hash(executable, args, workingDir); @override String toString() { final List<String> command = <String>[executable, ...args]; return '"${command.join(' ')}" in $workingDir'; } }
packages/script/tool/test/util.dart/0
{ "file_path": "packages/script/tool/test/util.dart", "repo_id": "packages", "token_count": 5302 }
1,064
{ "projects": { "default": "io-photobooth-dev" } }
photobooth/.firebaserc/0
{ "file_path": "photobooth/.firebaserc", "repo_id": "photobooth", "token_count": 29 }
1,065
{ "name": "io-photobooth-api", "private": true, "main": "lib/index.js", "engines": { "node": "14" }, "scripts": { "build": "tsc", "deploy": "firebase deploy --only functions", "dev": "tsc -w & firebase emulators:start --only functions", "lint": "eslint --ext .js,.ts .", "lint:fix": "eslint --fix --ext .js,.ts .", "logs": "firebase functions:log", "serve": "npm run build && firebase emulators:start --only functions", "shell": "npm run build && firebase functions:shell", "start": "npm run shell", "test:coverage": "jest --collect-coverage", "test:ts": "mocha -r ts-node/register --reporter spec tests/**/*.js", "test:upload": "gsutil cp testdata/upload.jpeg gs://io-photobooth-dev.appspot.com/uploads", "test": "jest", "watch": "tsc --watch" }, "dependencies": { "firebase-admin": "^9.6.0", "firebase-functions": "^3.13.2", "mustache": "^4.2.0" }, "devDependencies": { "@types/jest": "^26.0.22", "@types/mustache": "^4.1.1", "@typescript-eslint/eslint-plugin": "^4.21.0", "@typescript-eslint/parser": "^4.21.0", "eslint": "^7.23.0", "eslint-config-google": "^0.14.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jest": "^24.1.3", "jest": "^26.6.3", "prettier": "~2.2.1", "prettier-eslint": "~12.0.0", "ts-jest": "^26.5.4", "typescript": "^4.2.3" }, "jest": { "preset": "ts-jest", "testEnvironment": "node", "testPathIgnorePatterns": [ "lib" ] } }
photobooth/functions/package.json/0
{ "file_path": "photobooth/functions/package.json", "repo_id": "photobooth", "token_count": 735 }
1,066
import 'package:photobooth_ui/photobooth_ui.dart'; const googleIOExternalLink = 'https://events.google.com/io/'; const flutterDevExternalLink = 'https://flutter.dev'; const firebaseExternalLink = 'https://firebase.google.com'; const photoboothEmail = 'mailto:[email protected]'; const openSourceLink = 'https://github.com/flutter/photobooth'; Future<void> launchGoogleIOLink() => openLink(googleIOExternalLink); Future<void> launchFlutterDevLink() => openLink(flutterDevExternalLink); Future<void> launchFirebaseLink() => openLink(firebaseExternalLink); Future<void> launchPhotoboothEmail() => openLink(photoboothEmail); Future<void> launchOpenSourceLink() => openLink(openSourceLink);
photobooth/lib/external_links/external_links.dart/0
{ "file_path": "photobooth/lib/external_links/external_links.dart", "repo_id": "photobooth", "token_count": 215 }
1,067
import 'dart:async'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; const _videoConstraints = VideoConstraints( facingMode: FacingMode( type: CameraType.user, constrain: Constrain.ideal, ), width: VideoSize(ideal: 1920, maximum: 1920), height: VideoSize(ideal: 1080, maximum: 1080), ); class PhotoboothPage extends StatelessWidget { const PhotoboothPage({super.key}); static Route<void> route() { return AppPageRoute(builder: (_) => const PhotoboothPage()); } @override Widget build(BuildContext context) { return BlocProvider( create: (_) => PhotoboothBloc(), child: Navigator( onGenerateRoute: (_) => AppPageRoute( builder: (_) => const PhotoboothView(), ), ), ); } } class PhotoboothView extends StatefulWidget { const PhotoboothView({super.key}); @override State<PhotoboothView> createState() => _PhotoboothViewState(); } class _PhotoboothViewState extends State<PhotoboothView> { final _controller = CameraController( options: const CameraOptions( audio: AudioConstraints(), video: _videoConstraints, ), ); bool get _isCameraAvailable => _controller.value.status == CameraStatus.available; Future<void> _play() async { if (!_isCameraAvailable) return; return _controller.play(); } Future<void> _stop() async { if (!_isCameraAvailable) return; return _controller.stop(); } @override void initState() { super.initState(); _initializeCameraController(); } @override void dispose() { _controller.dispose(); super.dispose(); } Future<void> _initializeCameraController() async { await _controller.initialize(); await _play(); } Future<void> _onSnapPressed({required double aspectRatio}) async { final navigator = Navigator.of(context); final photoboothBloc = context.read<PhotoboothBloc>(); final picture = await _controller.takePicture(); photoboothBloc.add(PhotoCaptured(aspectRatio: aspectRatio, image: picture)); final stickersPage = StickersPage.route(); await _stop(); unawaited(navigator.pushReplacement(stickersPage)); } @override Widget build(BuildContext context) { final orientation = MediaQuery.of(context).orientation; final aspectRatio = orientation == Orientation.portrait ? PhotoboothAspectRatio.portrait : PhotoboothAspectRatio.landscape; return Scaffold( body: _PhotoboothBackground( aspectRatio: aspectRatio, child: Camera( controller: _controller, placeholder: (_) => const SizedBox(), preview: (context, preview) => PhotoboothPreview( preview: preview, onSnapPressed: () => _onSnapPressed(aspectRatio: aspectRatio), ), error: (context, error) => PhotoboothError(error: error), ), ), ); } } class _PhotoboothBackground extends StatelessWidget { const _PhotoboothBackground({ required this.aspectRatio, required this.child, }); final double aspectRatio; final Widget child; @override Widget build(BuildContext context) { return Stack( children: [ const PhotoboothBackground(), Center( child: AspectRatio( aspectRatio: aspectRatio, child: ColoredBox( color: PhotoboothColors.black, child: child, ), ), ), ], ); } }
photobooth/lib/photobooth/view/photobooth_page.dart/0
{ "file_path": "photobooth/lib/photobooth/view/photobooth_page.dart", "repo_id": "photobooth", "token_count": 1424 }
1,068
import 'dart:async'; import 'dart:typed_data'; import 'package:bloc/bloc.dart'; import 'package:camera/camera.dart'; import 'package:cross_file/cross_file.dart'; import 'package:equatable/equatable.dart'; import 'package:image_compositor/image_compositor.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:photos_repository/photos_repository.dart'; part 'share_event.dart'; part 'share_state.dart'; class ShareBloc extends Bloc<ShareEvent, ShareState> { ShareBloc({ required PhotosRepository photosRepository, required this.imageId, required this.image, required this.assets, required this.aspectRatio, required this.shareText, bool isSharingEnabled = const bool.fromEnvironment('SHARING_ENABLED'), }) : _photosRepository = photosRepository, _isSharingEnabled = isSharingEnabled, super(const ShareState()) { on<ShareViewLoaded>(_onShareViewLoaded); on<ShareTapped>(_onShareTapped); on<_ShareCompositeSucceeded>(_onShareCompositeSucceeded); on<_ShareCompositeFailed>( (event, emit) => emit( state.copyWith( compositeStatus: ShareStatus.failure, ), ), ); } final PhotosRepository _photosRepository; final String imageId; final CameraImage image; final List<PhotoAsset> assets; final double aspectRatio; final bool _isSharingEnabled; final String shareText; void _onShareViewLoaded( ShareViewLoaded event, Emitter<ShareState> emit, ) { emit(state.copyWith(compositeStatus: ShareStatus.loading)); unawaited( _composite().then( (value) => add(_ShareCompositeSucceeded(bytes: value)), onError: (_) => add(const _ShareCompositeFailed()), ), ); } Future<void> _onShareTapped( ShareTapped event, Emitter<ShareState> emit, ) async { if (!_isSharingEnabled) return; final shareUrl = event is ShareOnTwitterTapped ? ShareUrl.twitter : ShareUrl.facebook; emit( state.copyWith( uploadStatus: ShareStatus.initial, isDownloadRequested: false, isUploadRequested: true, shareUrl: shareUrl, ), ); if (state.compositeStatus.isLoading) return; if (state.uploadStatus.isLoading) return; if (state.uploadStatus.isSuccess) return; if (state.compositeStatus.isFailure) { emit( state.copyWith( compositeStatus: ShareStatus.loading, uploadStatus: ShareStatus.initial, isDownloadRequested: false, isUploadRequested: true, shareUrl: shareUrl, ), ); unawaited( _composite().then( (value) => add(_ShareCompositeSucceeded(bytes: value)), onError: (_) => add(const _ShareCompositeFailed()), ), ); } else if (state.compositeStatus.isSuccess) { emit( state.copyWith( uploadStatus: ShareStatus.loading, isDownloadRequested: false, isUploadRequested: true, shareUrl: shareUrl, ), ); try { final shareUrls = await _photosRepository.sharePhoto( fileName: _getPhotoFileName(imageId), data: state.bytes!, shareText: shareText, ); emit( state.copyWith( uploadStatus: ShareStatus.success, isDownloadRequested: false, isUploadRequested: true, file: state.file, bytes: state.bytes, explicitShareUrl: shareUrls.explicitShareUrl, facebookShareUrl: shareUrls.facebookShareUrl, twitterShareUrl: shareUrls.twitterShareUrl, shareUrl: shareUrl, ), ); } catch (_) { emit( state.copyWith( uploadStatus: ShareStatus.failure, isDownloadRequested: false, shareUrl: shareUrl, ), ); } } } Future<void> _onShareCompositeSucceeded( _ShareCompositeSucceeded event, Emitter<ShareState> emit, ) async { final file = XFile.fromData( event.bytes, mimeType: 'image/png', name: _getPhotoFileName(imageId), ); final bytes = event.bytes; emit( state.copyWith( compositeStatus: ShareStatus.success, bytes: bytes, file: file, ), ); if (state.isUploadRequested) { emit( state.copyWith( uploadStatus: ShareStatus.loading, bytes: bytes, file: file, isDownloadRequested: false, isUploadRequested: true, ), ); try { final shareUrls = await _photosRepository.sharePhoto( fileName: _getPhotoFileName(imageId), data: event.bytes, shareText: shareText, ); emit( state.copyWith( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, isDownloadRequested: false, isUploadRequested: true, bytes: bytes, file: file, explicitShareUrl: shareUrls.explicitShareUrl, facebookShareUrl: shareUrls.facebookShareUrl, twitterShareUrl: shareUrls.twitterShareUrl, ), ); } catch (_) { emit( state.copyWith( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.failure, bytes: bytes, file: file, isDownloadRequested: false, ), ); } } } Future<Uint8List> _composite() async { final composite = await _photosRepository.composite( aspectRatio: aspectRatio, data: image.data, width: image.width, height: image.height, layers: [ ...assets.map( (l) => CompositeLayer( angle: l.angle, assetPath: 'assets/${l.asset.path}', constraints: Vector2D(l.constraint.width, l.constraint.height), position: Vector2D(l.position.dx, l.position.dy), size: Vector2D(l.size.width, l.size.height), ), ) ], ); return Uint8List.fromList(composite); } String _getPhotoFileName(String photoName) => '$photoName.png'; }
photobooth/lib/share/bloc/share_bloc.dart/0
{ "file_path": "photobooth/lib/share/bloc/share_bloc.dart", "repo_id": "photobooth", "token_count": 2845 }
1,069
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:io_photobooth/external_links/external_links.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class ShareSuccessCaption extends StatelessWidget { const ShareSuccessCaption({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return SelectableText.rich( TextSpan( style: theme.textTheme.bodySmall?.copyWith( color: PhotoboothColors.white, ), children: <TextSpan>[ TextSpan(text: l10n.sharePageSuccessCaption1), TextSpan( text: l10n.sharePageSuccessCaption2, recognizer: TapGestureRecognizer()..onTap = launchPhotoboothEmail, style: const TextStyle( decoration: TextDecoration.underline, ), ), TextSpan(text: l10n.sharePageSuccessCaption3), ], ), textAlign: TextAlign.center, ); } }
photobooth/lib/share/widgets/share_caption.dart/0
{ "file_path": "photobooth/lib/share/widgets/share_caption.dart", "repo_id": "photobooth", "token_count": 479 }
1,070