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. 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.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebView.WebViewTransport; import android.webkit.WebViewClient; 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.open(identifier -> {}); instanceManager.addDartCreatedInstance(mockWebView, 0L); final WebChromeClientCreator webChromeClientCreator = new WebChromeClientCreator() { @Override public WebChromeClientImpl createWebChromeClient( WebChromeClientFlutterApiImpl flutterApi) { webChromeClient = super.createWebChromeClient(flutterApi); return webChromeClient; } }; hostApiImpl = new WebChromeClientHostApiImpl(instanceManager, webChromeClientCreator, mockFlutterApi); hostApiImpl.create(2L); } @After public void tearDown() { instanceManager.close(); } @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"); } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebChromeClientTest.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebChromeClientTest.java", "repo_id": "plugins", "token_count": 1484 }
1,250
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'android_webview_controller.dart'; import 'android_webview_cookie_manager.dart'; /// Implementation of [WebViewPlatform] using the WebKit API. class AndroidWebViewPlatform extends WebViewPlatform { /// Registers this class as the default instance of [WebViewPlatform]. static void registerWith() { WebViewPlatform.instance = AndroidWebViewPlatform(); } @override AndroidWebViewController createPlatformWebViewController( PlatformWebViewControllerCreationParams params, ) { return AndroidWebViewController(params); } @override AndroidNavigationDelegate createPlatformNavigationDelegate( PlatformNavigationDelegateCreationParams params, ) { return AndroidNavigationDelegate(params); } @override AndroidWebViewWidget createPlatformWebViewWidget( PlatformWebViewWidgetCreationParams params, ) { return AndroidWebViewWidget(params); } @override AndroidWebViewCookieManager createPlatformCookieManager( PlatformWebViewCookieManagerCreationParams params, ) { return AndroidWebViewCookieManager(params); } }
plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_platform.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_platform.dart", "repo_id": "plugins", "token_count": 381 }
1,251
// Mocks generated by Mockito 5.3.2 from annotations // in webview_flutter_android/test/android_webview_cookie_manager_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_android/src/android_webview.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [CookieManager]. /// /// See the documentation for Mockito's code generation for more information. class MockCookieManager extends _i1.Mock implements _i2.CookieManager { MockCookieManager() { _i1.throwOnMissingStub(this); } @override _i3.Future<void> setCookie( String? url, String? value, ) => (super.noSuchMethod( Invocation.method( #setCookie, [ url, value, ], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<bool> clearCookies() => (super.noSuchMethod( Invocation.method( #clearCookies, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); }
plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart", "repo_id": "plugins", "token_count": 685 }
1,252
// 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:plugin_platform_interface/plugin_platform_interface.dart'; import '../types/webview_cookie.dart'; /// Interface for a platform implementation of a cookie manager. /// /// Platform implementations should extend this class rather than implement it as `webview_flutter` /// does not consider newly added methods to be breaking changes. Extending this class /// (using `extends`) ensures that the subclass will get the default implementation, while /// platform implementations that `implements` this interface will be broken by newly added /// [WebViewCookieManagerPlatform] methods. abstract class WebViewCookieManagerPlatform extends PlatformInterface { /// Constructs a WebViewCookieManagerPlatform. WebViewCookieManagerPlatform() : super(token: _token); static final Object _token = Object(); static WebViewCookieManagerPlatform? _instance; /// The instance of [WebViewCookieManagerPlatform] to use. static WebViewCookieManagerPlatform? get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [WebViewCookieManagerPlatform] when they register themselves. static set instance(WebViewCookieManagerPlatform? instance) { if (instance == null) { throw AssertionError( 'Platform interfaces can only be set to a non-null instance'); } PlatformInterface.verify(instance, _token); _instance = instance; } /// Clears all cookies for all [WebView] instances. /// /// Returns true if cookies were present before clearing, else false. Future<bool> clearCookies() { throw UnimplementedError( 'clearCookies is not implemented on the current platform'); } /// Sets a cookie for all [WebView] instances. Future<void> setCookie(WebViewCookie cookie) { throw UnimplementedError( 'setCookie is not implemented on the current platform'); } }
plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_cookie_manager.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_cookie_manager.dart", "repo_id": "plugins", "token_count": 554 }
1,253
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import '../../src/platform_navigation_delegate.dart'; import 'webview_platform.dart'; /// Interface for a platform implementation of a web view controller. /// /// Platform implementations should extend this class rather than implement it /// as `webview_flutter` does not consider newly added methods to be breaking /// changes. Extending this class (using `extends`) ensures that the subclass /// will get the default implementation, while platform implementations that /// `implements` this interface will be broken by newly added /// [PlatformWebViewCookieManager] methods. abstract class PlatformWebViewController extends PlatformInterface { /// Creates a new [PlatformWebViewController] factory PlatformWebViewController( PlatformWebViewControllerCreationParams params) { assert( WebViewPlatform.instance != null, 'A platform implementation for `webview_flutter` has not been set. Please ' 'ensure that an implementation of `WebViewPlatform` has been set to ' '`WebViewPlatform.instance` before use. For unit testing, ' '`WebViewPlatform.instance` can be set with your own test implementation.', ); final PlatformWebViewController webViewControllerDelegate = WebViewPlatform.instance!.createPlatformWebViewController(params); PlatformInterface.verify(webViewControllerDelegate, _token); return webViewControllerDelegate; } /// Used by the platform implementation to create a new [PlatformWebViewController]. /// /// Should only be used by platform implementations because they can't extend /// a class that only contains a factory constructor. @protected PlatformWebViewController.implementation(this.params) : super(token: _token); static final Object _token = Object(); /// The parameters used to initialize the [PlatformWebViewController]. final PlatformWebViewControllerCreationParams params; /// Loads the file located on the specified [absoluteFilePath]. /// /// The [absoluteFilePath] parameter should contain the absolute path to the /// file as it is stored on the device. For example: /// `/Users/username/Documents/www/index.html`. /// /// Throws an ArgumentError if the [absoluteFilePath] does not exist. Future<void> loadFile( String absoluteFilePath, ) { throw UnimplementedError( 'loadFile is not implemented on the current platform'); } /// Loads the Flutter asset specified in the pubspec.yaml file. /// /// Throws an ArgumentError if [key] is not part of the specified assets /// in the pubspec.yaml file. Future<void> loadFlutterAsset( String key, ) { throw UnimplementedError( 'loadFlutterAsset is not implemented on the current platform'); } /// Loads the supplied HTML string. /// /// The [baseUrl] parameter is used when resolving relative URLs within the /// HTML string. Future<void> loadHtmlString( String html, { String? baseUrl, }) { throw UnimplementedError( 'loadHtmlString is not implemented on the current platform'); } /// Makes a specific HTTP request ands loads the response in the webview. /// /// [WebViewRequest.method] must be one of the supported HTTP methods /// in [WebViewRequestMethod]. /// /// If [WebViewRequest.headers] is not empty, its key-value pairs will be /// added as the headers for the request. /// /// If [WebViewRequest.body] is not null, it will be added as the body /// for the request. /// /// Throws an ArgumentError if [WebViewRequest.uri] has empty scheme. Future<void> loadRequest( LoadRequestParams params, ) { throw UnimplementedError( 'loadRequest is not implemented on the current platform'); } /// Accessor to the current URL that the WebView is displaying. /// /// If no URL was ever loaded, returns `null`. Future<String?> currentUrl() { throw UnimplementedError( 'currentUrl is not implemented on the current platform'); } /// Checks whether there's a back history item. Future<bool> canGoBack() { throw UnimplementedError( 'canGoBack is not implemented on the current platform'); } /// Checks whether there's a forward history item. Future<bool> canGoForward() { throw UnimplementedError( 'canGoForward is not implemented on the current platform'); } /// Goes back in the history of this WebView. /// /// If there is no back history item this is a no-op. Future<void> goBack() { throw UnimplementedError( 'goBack is not implemented on the current platform'); } /// Goes forward in the history of this WebView. /// /// If there is no forward history item this is a no-op. Future<void> goForward() { throw UnimplementedError( 'goForward is not implemented on the current platform'); } /// Reloads the current URL. Future<void> reload() { throw UnimplementedError( 'reload is not implemented on the current platform'); } /// Clears all caches used by the [WebView]. /// /// The following caches are cleared: /// 1. Browser HTTP Cache. /// 2. [Cache API](https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/cache-api) caches. /// These are not yet supported in iOS WkWebView. Service workers tend to use this cache. /// 3. Application cache. Future<void> clearCache() { throw UnimplementedError( 'clearCache is not implemented on the current platform'); } /// Clears the local storage used by the [WebView]. Future<void> clearLocalStorage() { throw UnimplementedError( 'clearLocalStorage is not implemented on the current platform'); } /// Sets the [PlatformNavigationDelegate] containing the callback methods that /// are called during navigation events. Future<void> setPlatformNavigationDelegate( PlatformNavigationDelegate handler) { throw UnimplementedError( 'setPlatformNavigationDelegate is not implemented on the current platform'); } /// Runs the given JavaScript in the context of the current page. /// /// The Future completes with an error if a JavaScript error occurred. Future<void> runJavaScript(String javaScript) { throw UnimplementedError( 'runJavaScript is not implemented on the current platform'); } /// Runs the given JavaScript in the context of the current page, and returns the result. /// /// The Future completes with an error if a JavaScript error occurred, or if the /// type the given expression evaluates to is unsupported. Unsupported values include /// certain non-primitive types on iOS, as well as `undefined` or `null` on iOS 14+. Future<Object> runJavaScriptReturningResult(String javaScript) { throw UnimplementedError( 'runJavaScriptReturningResult is not implemented on the current platform'); } /// Adds a new JavaScript channel to the set of enabled channels. Future<void> addJavaScriptChannel( JavaScriptChannelParams javaScriptChannelParams, ) { throw UnimplementedError( 'addJavaScriptChannel is not implemented on the current platform'); } /// Removes the JavaScript channel with the matching name from the set of /// enabled channels. /// /// This disables the channel with the matching name if it was previously /// enabled through the [addJavaScriptChannel]. Future<void> removeJavaScriptChannel(String javaScriptChannelName) { throw UnimplementedError( 'removeJavaScriptChannel is not implemented on the current platform'); } /// Returns the title of the currently loaded page. Future<String?> getTitle() { throw UnimplementedError( 'getTitle is not implemented on the current platform'); } /// Set the scrolled position of this view. /// /// The parameters `x` and `y` specify the position to scroll to in WebView pixels. Future<void> scrollTo(int x, int y) { throw UnimplementedError( 'scrollTo is not implemented on the current platform'); } /// Move the scrolled position of this view. /// /// The parameters `x` and `y` specify the amount of WebView pixels to scroll by. Future<void> scrollBy(int x, int y) { throw UnimplementedError( 'scrollBy is not implemented on the current platform'); } /// Return the current scroll position of this view. /// /// Scroll position is measured from the top left. Future<Offset> getScrollPosition() { throw UnimplementedError( 'getScrollPosition is not implemented on the current platform'); } /// Whether to support zooming using its on-screen zoom controls and gestures. Future<void> enableZoom(bool enabled) { throw UnimplementedError( 'enableZoom is not implemented on the current platform'); } /// Set the current background color of this view. Future<void> setBackgroundColor(Color color) { throw UnimplementedError( 'setBackgroundColor is not implemented on the current platform'); } /// Sets the JavaScript execution mode to be used by the webview. Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) { throw UnimplementedError( 'setJavaScriptMode is not implemented on the current platform'); } /// Sets the value used for the HTTP `User-Agent:` request header. Future<void> setUserAgent(String? userAgent) { throw UnimplementedError( 'setUserAgent is not implemented on the current platform'); } } /// Describes the parameters necessary for registering a JavaScript channel. @immutable class JavaScriptChannelParams { /// Creates a new [JavaScriptChannelParams] object. const JavaScriptChannelParams({ required this.name, required this.onMessageReceived, }); /// The name that identifies the JavaScript channel. final String name; /// The callback method that is invoked when a [JavaScriptMessage] is /// received. final void Function(JavaScriptMessage) onMessageReceived; }
plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_controller.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_controller.dart", "repo_id": "plugins", "token_count": 2934 }
1,254
// 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:plugin_platform_interface/plugin_platform_interface.dart'; import '../../src/platform_navigation_delegate.dart'; import 'platform_webview_controller.dart'; import 'platform_webview_cookie_manager.dart'; import 'platform_webview_widget.dart'; import 'types/types.dart'; export 'types/types.dart'; /// Interface for a platform implementation of a WebView. abstract class WebViewPlatform extends PlatformInterface { /// Creates a new [WebViewPlatform]. WebViewPlatform() : super(token: _token); static final Object _token = Object(); static WebViewPlatform? _instance; /// The instance of [WebViewPlatform] to use. static WebViewPlatform? get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [WebViewPlatform] when they register themselves. static set instance(WebViewPlatform? instance) { if (instance == null) { throw AssertionError( 'Platform interfaces can only be set to a non-null instance'); } PlatformInterface.verify(instance, _token); _instance = instance; } /// Creates a new [PlatformWebViewCookieManager]. /// /// This function should only be called by the app-facing package. /// Look at using [WebViewCookieManager] in `webview_flutter` instead. PlatformWebViewCookieManager createPlatformCookieManager( PlatformWebViewCookieManagerCreationParams params, ) { throw UnimplementedError( 'createPlatformCookieManager is not implemented on the current platform.'); } /// Creates a new [PlatformNavigationDelegate]. /// /// This function should only be called by the app-facing package. /// Look at using [NavigationDelegate] in `webview_flutter` instead. PlatformNavigationDelegate createPlatformNavigationDelegate( PlatformNavigationDelegateCreationParams params, ) { throw UnimplementedError( 'createPlatformNavigationDelegate is not implemented on the current platform.'); } /// Create a new [PlatformWebViewController]. /// /// This function should only be called by the app-facing package. /// Look at using [WebViewController] in `webview_flutter` instead. PlatformWebViewController createPlatformWebViewController( PlatformWebViewControllerCreationParams params, ) { throw UnimplementedError( 'createPlatformWebViewController is not implemented on the current platform.'); } /// Create a new [PlatformWebViewWidget]. /// /// This function should only be called by the app-facing package. /// Look at using [WebViewWidget] in `webview_flutter` instead. PlatformWebViewWidget createPlatformWebViewWidget( PlatformWebViewWidgetCreationParams params, ) { throw UnimplementedError( 'createPlatformWebViewWidget is not implemented on the current platform.'); } }
plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/webview_platform.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/webview_platform.dart", "repo_id": "plugins", "token_count": 858 }
1,255
// Mocks generated by Mockito 5.3.2 from annotations // in webview_flutter_web/test/web_webview_controller_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'dart:html' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_web/src/http_request_factory.dart' as _i4; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeHttpRequestUpload_0 extends _i1.SmartFake implements _i2.HttpRequestUpload { _FakeHttpRequestUpload_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeEvents_1 extends _i1.SmartFake implements _i2.Events { _FakeEvents_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeHttpRequest_2 extends _i1.SmartFake implements _i2.HttpRequest { _FakeHttpRequest_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [HttpRequest]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpRequest extends _i1.Mock implements _i2.HttpRequest { @override Map<String, String> get responseHeaders => (super.noSuchMethod( Invocation.getter(#responseHeaders), returnValue: <String, String>{}, returnValueForMissingStub: <String, String>{}, ) as Map<String, String>); @override int get readyState => (super.noSuchMethod( Invocation.getter(#readyState), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override String get responseType => (super.noSuchMethod( Invocation.getter(#responseType), returnValue: '', returnValueForMissingStub: '', ) as String); @override set responseType(String? value) => super.noSuchMethod( Invocation.setter( #responseType, value, ), returnValueForMissingStub: null, ); @override set timeout(int? value) => super.noSuchMethod( Invocation.setter( #timeout, value, ), returnValueForMissingStub: null, ); @override _i2.HttpRequestUpload get upload => (super.noSuchMethod( Invocation.getter(#upload), returnValue: _FakeHttpRequestUpload_0( this, Invocation.getter(#upload), ), returnValueForMissingStub: _FakeHttpRequestUpload_0( this, Invocation.getter(#upload), ), ) as _i2.HttpRequestUpload); @override set withCredentials(bool? value) => super.noSuchMethod( Invocation.setter( #withCredentials, value, ), returnValueForMissingStub: null, ); @override _i3.Stream<_i2.Event> get onReadyStateChange => (super.noSuchMethod( Invocation.getter(#onReadyStateChange), returnValue: _i3.Stream<_i2.Event>.empty(), returnValueForMissingStub: _i3.Stream<_i2.Event>.empty(), ) as _i3.Stream<_i2.Event>); @override _i3.Stream<_i2.ProgressEvent> get onAbort => (super.noSuchMethod( Invocation.getter(#onAbort), returnValue: _i3.Stream<_i2.ProgressEvent>.empty(), returnValueForMissingStub: _i3.Stream<_i2.ProgressEvent>.empty(), ) as _i3.Stream<_i2.ProgressEvent>); @override _i3.Stream<_i2.ProgressEvent> get onError => (super.noSuchMethod( Invocation.getter(#onError), returnValue: _i3.Stream<_i2.ProgressEvent>.empty(), returnValueForMissingStub: _i3.Stream<_i2.ProgressEvent>.empty(), ) as _i3.Stream<_i2.ProgressEvent>); @override _i3.Stream<_i2.ProgressEvent> get onLoad => (super.noSuchMethod( Invocation.getter(#onLoad), returnValue: _i3.Stream<_i2.ProgressEvent>.empty(), returnValueForMissingStub: _i3.Stream<_i2.ProgressEvent>.empty(), ) as _i3.Stream<_i2.ProgressEvent>); @override _i3.Stream<_i2.ProgressEvent> get onLoadEnd => (super.noSuchMethod( Invocation.getter(#onLoadEnd), returnValue: _i3.Stream<_i2.ProgressEvent>.empty(), returnValueForMissingStub: _i3.Stream<_i2.ProgressEvent>.empty(), ) as _i3.Stream<_i2.ProgressEvent>); @override _i3.Stream<_i2.ProgressEvent> get onLoadStart => (super.noSuchMethod( Invocation.getter(#onLoadStart), returnValue: _i3.Stream<_i2.ProgressEvent>.empty(), returnValueForMissingStub: _i3.Stream<_i2.ProgressEvent>.empty(), ) as _i3.Stream<_i2.ProgressEvent>); @override _i3.Stream<_i2.ProgressEvent> get onProgress => (super.noSuchMethod( Invocation.getter(#onProgress), returnValue: _i3.Stream<_i2.ProgressEvent>.empty(), returnValueForMissingStub: _i3.Stream<_i2.ProgressEvent>.empty(), ) as _i3.Stream<_i2.ProgressEvent>); @override _i3.Stream<_i2.ProgressEvent> get onTimeout => (super.noSuchMethod( Invocation.getter(#onTimeout), returnValue: _i3.Stream<_i2.ProgressEvent>.empty(), returnValueForMissingStub: _i3.Stream<_i2.ProgressEvent>.empty(), ) as _i3.Stream<_i2.ProgressEvent>); @override _i2.Events get on => (super.noSuchMethod( Invocation.getter(#on), returnValue: _FakeEvents_1( this, Invocation.getter(#on), ), returnValueForMissingStub: _FakeEvents_1( this, Invocation.getter(#on), ), ) as _i2.Events); @override void open( String? method, String? url, { bool? async, String? user, String? password, }) => super.noSuchMethod( Invocation.method( #open, [ method, url, ], { #async: async, #user: user, #password: password, }, ), returnValueForMissingStub: null, ); @override void abort() => super.noSuchMethod( Invocation.method( #abort, [], ), returnValueForMissingStub: null, ); @override String getAllResponseHeaders() => (super.noSuchMethod( Invocation.method( #getAllResponseHeaders, [], ), returnValue: '', returnValueForMissingStub: '', ) as String); @override String? getResponseHeader(String? name) => (super.noSuchMethod( Invocation.method( #getResponseHeader, [name], ), returnValueForMissingStub: null, ) as String?); @override void overrideMimeType(String? mime) => super.noSuchMethod( Invocation.method( #overrideMimeType, [mime], ), returnValueForMissingStub: null, ); @override void send([dynamic body_OR_data]) => super.noSuchMethod( Invocation.method( #send, [body_OR_data], ), returnValueForMissingStub: null, ); @override void setRequestHeader( String? name, String? value, ) => super.noSuchMethod( Invocation.method( #setRequestHeader, [ name, value, ], ), returnValueForMissingStub: null, ); @override void addEventListener( String? type, _i2.EventListener? listener, [ bool? useCapture, ]) => super.noSuchMethod( Invocation.method( #addEventListener, [ type, listener, useCapture, ], ), returnValueForMissingStub: null, ); @override void removeEventListener( String? type, _i2.EventListener? listener, [ bool? useCapture, ]) => super.noSuchMethod( Invocation.method( #removeEventListener, [ type, listener, useCapture, ], ), returnValueForMissingStub: null, ); @override bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod( Invocation.method( #dispatchEvent, [event], ), returnValue: false, returnValueForMissingStub: false, ) as bool); } /// A class which mocks [HttpRequestFactory]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpRequestFactory extends _i1.Mock implements _i4.HttpRequestFactory { @override _i3.Future<_i2.HttpRequest> request( String? url, { String? method, bool? withCredentials, String? responseType, String? mimeType, Map<String, String>? requestHeaders, dynamic sendData, void Function(_i2.ProgressEvent)? onProgress, }) => (super.noSuchMethod( Invocation.method( #request, [url], { #method: method, #withCredentials: withCredentials, #responseType: responseType, #mimeType: mimeType, #requestHeaders: requestHeaders, #sendData: sendData, #onProgress: onProgress, }, ), returnValue: _i3.Future<_i2.HttpRequest>.value(_FakeHttpRequest_2( this, Invocation.method( #request, [url], { #method: method, #withCredentials: withCredentials, #responseType: responseType, #mimeType: mimeType, #requestHeaders: requestHeaders, #sendData: sendData, #onProgress: onProgress, }, ), )), returnValueForMissingStub: _i3.Future<_i2.HttpRequest>.value(_FakeHttpRequest_2( this, Invocation.method( #request, [url], { #method: method, #withCredentials: withCredentials, #responseType: responseType, #mimeType: mimeType, #requestHeaders: requestHeaders, #sendData: sendData, #onProgress: onProgress, }, ), )), ) as _i3.Future<_i2.HttpRequest>); }
plugins/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart", "repo_id": "plugins", "token_count": 4952 }
1,256
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import Flutter; @import XCTest; @import webview_flutter_wkwebview; #import <OCMock/OCMock.h> static bool feq(CGFloat a, CGFloat b) { return fabs(b - a) < FLT_EPSILON; } @interface FWFWebViewHostApiTests : XCTestCase @end @implementation FWFWebViewHostApiTests - (void)testCreateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0]; FlutterError *error; [hostAPI createWithIdentifier:@1 configurationIdentifier:@0 error:&error]; WKWebView *webView = (WKWebView *)[instanceManager instanceForIdentifier:1]; XCTAssertTrue([webView isKindOfClass:[WKWebView class]]); XCTAssertNil(error); } - (void)testLoadRequest { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; FWFNSUrlRequestData *requestData = [FWFNSUrlRequestData makeWithUrl:@"https://www.flutter.dev" httpMethod:@"get" httpBody:nil allHttpHeaderFields:@{@"a" : @"header"}]; [hostAPI loadRequestForWebViewWithIdentifier:@0 request:requestData error:&error]; NSURL *url = [NSURL URLWithString:@"https://www.flutter.dev"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"get"; request.allHTTPHeaderFields = @{@"a" : @"header"}; OCMVerify([mockWebView loadRequest:request]); XCTAssertNil(error); } - (void)testLoadRequestWithInvalidUrl { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMReject([mockWebView loadRequest:OCMOCK_ANY]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; FWFNSUrlRequestData *requestData = [FWFNSUrlRequestData makeWithUrl:@"%invalidUrl%" httpMethod:nil httpBody:nil allHttpHeaderFields:@{}]; [hostAPI loadRequestForWebViewWithIdentifier:@0 request:requestData error:&error]; XCTAssertNotNil(error); XCTAssertEqualObjects(error.code, @"FWFURLRequestParsingError"); XCTAssertEqualObjects(error.message, @"Failed instantiating an NSURLRequest."); XCTAssertEqualObjects(error.details, @"URL was: '%invalidUrl%'"); } - (void)testSetCustomUserAgent { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI setUserAgentForWebViewWithIdentifier:@0 userAgent:@"userA" error:&error]; OCMVerify([mockWebView setCustomUserAgent:@"userA"]); XCTAssertNil(error); } - (void)testURL { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView URL]).andReturn([NSURL URLWithString:@"https://www.flutter.dev/"]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI URLForWebViewWithIdentifier:@0 error:&error], @"https://www.flutter.dev/"); XCTAssertNil(error); } - (void)testCanGoBack { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView canGoBack]).andReturn(YES); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI canGoBackForWebViewWithIdentifier:@0 error:&error], @YES); XCTAssertNil(error); } - (void)testSetUIDelegate { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; id<WKUIDelegate> mockDelegate = OCMProtocolMock(@protocol(WKUIDelegate)); [instanceManager addDartCreatedInstance:mockDelegate withIdentifier:1]; FlutterError *error; [hostAPI setUIDelegateForWebViewWithIdentifier:@0 delegateIdentifier:@1 error:&error]; OCMVerify([mockWebView setUIDelegate:mockDelegate]); XCTAssertNil(error); } - (void)testSetNavigationDelegate { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; id<WKNavigationDelegate> mockDelegate = OCMProtocolMock(@protocol(WKNavigationDelegate)); [instanceManager addDartCreatedInstance:mockDelegate withIdentifier:1]; FlutterError *error; [hostAPI setNavigationDelegateForWebViewWithIdentifier:@0 delegateIdentifier:@1 error:&error]; OCMVerify([mockWebView setNavigationDelegate:mockDelegate]); XCTAssertNil(error); } - (void)testEstimatedProgress { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView estimatedProgress]).andReturn(34.0); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI estimatedProgressForWebViewWithIdentifier:@0 error:&error], @34.0); XCTAssertNil(error); } - (void)testloadHTMLString { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI loadHTMLForWebViewWithIdentifier:@0 HTMLString:@"myString" baseURL:@"myBaseUrl" error:&error]; OCMVerify([mockWebView loadHTMLString:@"myString" baseURL:[NSURL URLWithString:@"myBaseUrl"]]); XCTAssertNil(error); } - (void)testLoadFileURL { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI loadFileForWebViewWithIdentifier:@0 fileURL:@"myFolder/apple.txt" readAccessURL:@"myFolder" error:&error]; XCTAssertNil(error); OCMVerify([mockWebView loadFileURL:[NSURL fileURLWithPath:@"myFolder/apple.txt" isDirectory:NO] allowingReadAccessToURL:[NSURL fileURLWithPath:@"myFolder/" isDirectory:YES] ]); } - (void)testLoadFlutterAsset { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFAssetManager *mockAssetManager = OCMClassMock([FWFAssetManager class]); OCMStub([mockAssetManager lookupKeyForAsset:@"assets/index.html"]) .andReturn(@"myFolder/assets/index.html"); NSBundle *mockBundle = OCMClassMock([NSBundle class]); OCMStub([mockBundle URLForResource:@"myFolder/assets/index" withExtension:@"html"]) .andReturn([NSURL URLWithString:@"webview_flutter/myFolder/assets/index.html"]); FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager bundle:mockBundle assetManager:mockAssetManager]; FlutterError *error; [hostAPI loadAssetForWebViewWithIdentifier:@0 assetKey:@"assets/index.html" error:&error]; XCTAssertNil(error); OCMVerify([mockWebView loadFileURL:[NSURL URLWithString:@"webview_flutter/myFolder/assets/index.html"] allowingReadAccessToURL:[NSURL URLWithString:@"webview_flutter/myFolder/assets/"]]); } - (void)testCanGoForward { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView canGoForward]).andReturn(NO); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI canGoForwardForWebViewWithIdentifier:@0 error:&error], @NO); XCTAssertNil(error); } - (void)testGoBack { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI goBackForWebViewWithIdentifier:@0 error:&error]; OCMVerify([mockWebView goBack]); XCTAssertNil(error); } - (void)testGoForward { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI goForwardForWebViewWithIdentifier:@0 error:&error]; OCMVerify([mockWebView goForward]); XCTAssertNil(error); } - (void)testReload { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI reloadWebViewWithIdentifier:@0 error:&error]; OCMVerify([mockWebView reload]); XCTAssertNil(error); } - (void)testTitle { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView title]).andReturn(@"myTitle"); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI titleForWebViewWithIdentifier:@0 error:&error], @"myTitle"); XCTAssertNil(error); } - (void)testSetAllowsBackForwardNavigationGestures { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI setAllowsBackForwardForWebViewWithIdentifier:@0 isAllowed:@YES error:&error]; OCMVerify([mockWebView setAllowsBackForwardNavigationGestures:YES]); XCTAssertNil(error); } - (void)testEvaluateJavaScript { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView evaluateJavaScript:@"runJavaScript" completionHandler:([OCMArg invokeBlockWithArgs:@"result", [NSNull null], nil])]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; NSString __block *returnValue; FlutterError __block *returnError; [hostAPI evaluateJavaScriptForWebViewWithIdentifier:@0 javaScriptString:@"runJavaScript" completion:^(id result, FlutterError *error) { returnValue = result; returnError = error; }]; XCTAssertEqualObjects(returnValue, @"result"); XCTAssertNil(returnError); } - (void)testEvaluateJavaScriptReturnsNSErrorData { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView evaluateJavaScript:@"runJavaScript" completionHandler:([OCMArg invokeBlockWithArgs:[NSNull null], [NSError errorWithDomain:@"errorDomain" code:0 userInfo:@{ NSLocalizedDescriptionKey : @"description" }], nil])]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; NSString __block *returnValue; FlutterError __block *returnError; [hostAPI evaluateJavaScriptForWebViewWithIdentifier:@0 javaScriptString:@"runJavaScript" completion:^(id result, FlutterError *error) { returnValue = result; returnError = error; }]; XCTAssertNil(returnValue); FWFNSErrorData *errorData = returnError.details; XCTAssertTrue([errorData isKindOfClass:[FWFNSErrorData class]]); XCTAssertEqualObjects(errorData.code, @0); XCTAssertEqualObjects(errorData.domain, @"errorDomain"); XCTAssertEqualObjects(errorData.localizedDescription, @"description"); } - (void)testWebViewContentInsetBehaviorShouldBeNeverOnIOS11 API_AVAILABLE(ios(11.0)) { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0]; FlutterError *error; [hostAPI createWithIdentifier:@1 configurationIdentifier:@0 error:&error]; FWFWebView *webView = (FWFWebView *)[instanceManager instanceForIdentifier:1]; XCTAssertEqual(webView.scrollView.contentInsetAdjustmentBehavior, UIScrollViewContentInsetAdjustmentNever); } - (void)testScrollViewsAutomaticallyAdjustsScrollIndicatorInsetsShouldbeNoOnIOS13 API_AVAILABLE( ios(13.0)) { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0]; FlutterError *error; [hostAPI createWithIdentifier:@1 configurationIdentifier:@0 error:&error]; FWFWebView *webView = (FWFWebView *)[instanceManager instanceForIdentifier:1]; XCTAssertFalse(webView.scrollView.automaticallyAdjustsScrollIndicatorInsets); } - (void)testContentInsetsSumAlwaysZeroAfterSetFrame { FWFWebView *webView = [[FWFWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 400) configuration:[[WKWebViewConfiguration alloc] init]]; webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 300, 0); XCTAssertFalse(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero)); webView.frame = CGRectMake(0, 0, 300, 200); XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero)); XCTAssertTrue(CGRectEqualToRect(webView.frame, CGRectMake(0, 0, 300, 200))); if (@available(iOS 11, *)) { // After iOS 11, we need to make sure the contentInset compensates the adjustedContentInset. UIScrollView *partialMockScrollView = OCMPartialMock(webView.scrollView); UIEdgeInsets insetToAdjust = UIEdgeInsetsMake(0, 0, 300, 0); OCMStub(partialMockScrollView.adjustedContentInset).andReturn(insetToAdjust); XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero)); webView.frame = CGRectMake(0, 0, 300, 100); XCTAssertTrue(feq(webView.scrollView.contentInset.bottom, -insetToAdjust.bottom)); XCTAssertTrue(CGRectEqualToRect(webView.frame, CGRectMake(0, 0, 300, 100))); } } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewHostApiTests.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewHostApiTests.m", "repo_id": "plugins", "token_count": 8167 }
1,257
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v4.2.13), do not edit directly. // See also: https://pub.dev/packages/pigeon #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN /// Mirror of NSKeyValueObservingOptions. /// /// See /// https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions?language=objc. typedef NS_ENUM(NSUInteger, FWFNSKeyValueObservingOptionsEnum) { FWFNSKeyValueObservingOptionsEnumNewValue = 0, FWFNSKeyValueObservingOptionsEnumOldValue = 1, FWFNSKeyValueObservingOptionsEnumInitialValue = 2, FWFNSKeyValueObservingOptionsEnumPriorNotification = 3, }; /// Mirror of NSKeyValueChange. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechange?language=objc. typedef NS_ENUM(NSUInteger, FWFNSKeyValueChangeEnum) { FWFNSKeyValueChangeEnumSetting = 0, FWFNSKeyValueChangeEnumInsertion = 1, FWFNSKeyValueChangeEnumRemoval = 2, FWFNSKeyValueChangeEnumReplacement = 3, }; /// Mirror of NSKeyValueChangeKey. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangekey?language=objc. typedef NS_ENUM(NSUInteger, FWFNSKeyValueChangeKeyEnum) { FWFNSKeyValueChangeKeyEnumIndexes = 0, FWFNSKeyValueChangeKeyEnumKind = 1, FWFNSKeyValueChangeKeyEnumNewValue = 2, FWFNSKeyValueChangeKeyEnumNotificationIsPrior = 3, FWFNSKeyValueChangeKeyEnumOldValue = 4, }; /// Mirror of WKUserScriptInjectionTime. /// /// See https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime?language=objc. typedef NS_ENUM(NSUInteger, FWFWKUserScriptInjectionTimeEnum) { FWFWKUserScriptInjectionTimeEnumAtDocumentStart = 0, FWFWKUserScriptInjectionTimeEnumAtDocumentEnd = 1, }; /// Mirror of WKAudiovisualMediaTypes. /// /// See /// [WKAudiovisualMediaTypes](https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes?language=objc). typedef NS_ENUM(NSUInteger, FWFWKAudiovisualMediaTypeEnum) { FWFWKAudiovisualMediaTypeEnumNone = 0, FWFWKAudiovisualMediaTypeEnumAudio = 1, FWFWKAudiovisualMediaTypeEnumVideo = 2, FWFWKAudiovisualMediaTypeEnumAll = 3, }; /// Mirror of WKWebsiteDataTypes. /// /// See /// https://developer.apple.com/documentation/webkit/wkwebsitedatarecord/data_store_record_types?language=objc. typedef NS_ENUM(NSUInteger, FWFWKWebsiteDataTypeEnum) { FWFWKWebsiteDataTypeEnumCookies = 0, FWFWKWebsiteDataTypeEnumMemoryCache = 1, FWFWKWebsiteDataTypeEnumDiskCache = 2, FWFWKWebsiteDataTypeEnumOfflineWebApplicationCache = 3, FWFWKWebsiteDataTypeEnumLocalStorage = 4, FWFWKWebsiteDataTypeEnumSessionStorage = 5, FWFWKWebsiteDataTypeEnumWebSQLDatabases = 6, FWFWKWebsiteDataTypeEnumIndexedDBDatabases = 7, }; /// Mirror of WKNavigationActionPolicy. /// /// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc. typedef NS_ENUM(NSUInteger, FWFWKNavigationActionPolicyEnum) { FWFWKNavigationActionPolicyEnumAllow = 0, FWFWKNavigationActionPolicyEnumCancel = 1, }; /// Mirror of NSHTTPCookiePropertyKey. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiepropertykey. typedef NS_ENUM(NSUInteger, FWFNSHttpCookiePropertyKeyEnum) { FWFNSHttpCookiePropertyKeyEnumComment = 0, FWFNSHttpCookiePropertyKeyEnumCommentUrl = 1, FWFNSHttpCookiePropertyKeyEnumDiscard = 2, FWFNSHttpCookiePropertyKeyEnumDomain = 3, FWFNSHttpCookiePropertyKeyEnumExpires = 4, FWFNSHttpCookiePropertyKeyEnumMaximumAge = 5, FWFNSHttpCookiePropertyKeyEnumName = 6, FWFNSHttpCookiePropertyKeyEnumOriginUrl = 7, FWFNSHttpCookiePropertyKeyEnumPath = 8, FWFNSHttpCookiePropertyKeyEnumPort = 9, FWFNSHttpCookiePropertyKeyEnumSameSitePolicy = 10, FWFNSHttpCookiePropertyKeyEnumSecure = 11, FWFNSHttpCookiePropertyKeyEnumValue = 12, FWFNSHttpCookiePropertyKeyEnumVersion = 13, }; /// An object that contains information about an action that causes navigation /// to occur. /// /// Wraps /// [WKNavigationType](https://developer.apple.com/documentation/webkit/wknavigationaction?language=objc). typedef NS_ENUM(NSUInteger, FWFWKNavigationType) { /// A link activation. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypelinkactivated?language=objc. FWFWKNavigationTypeLinkActivated = 0, /// A request to submit a form. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformsubmitted?language=objc. FWFWKNavigationTypeSubmitted = 1, /// A request for the frame’s next or previous item. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypebackforward?language=objc. FWFWKNavigationTypeBackForward = 2, /// A request to reload the webpage. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypereload?language=objc. FWFWKNavigationTypeReload = 3, /// A request to resubmit a form. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformresubmitted?language=objc. FWFWKNavigationTypeFormResubmitted = 4, /// A navigation request that originates for some other reason. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeother?language=objc. FWFWKNavigationTypeOther = 5, }; @class FWFNSKeyValueObservingOptionsEnumData; @class FWFNSKeyValueChangeKeyEnumData; @class FWFWKUserScriptInjectionTimeEnumData; @class FWFWKAudiovisualMediaTypeEnumData; @class FWFWKWebsiteDataTypeEnumData; @class FWFWKNavigationActionPolicyEnumData; @class FWFNSHttpCookiePropertyKeyEnumData; @class FWFNSUrlRequestData; @class FWFWKUserScriptData; @class FWFWKNavigationActionData; @class FWFWKFrameInfoData; @class FWFNSErrorData; @class FWFWKScriptMessageData; @class FWFNSHttpCookieData; @interface FWFNSKeyValueObservingOptionsEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFNSKeyValueObservingOptionsEnum)value; @property(nonatomic, assign) FWFNSKeyValueObservingOptionsEnum value; @end @interface FWFNSKeyValueChangeKeyEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFNSKeyValueChangeKeyEnum)value; @property(nonatomic, assign) FWFNSKeyValueChangeKeyEnum value; @end @interface FWFWKUserScriptInjectionTimeEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKUserScriptInjectionTimeEnum)value; @property(nonatomic, assign) FWFWKUserScriptInjectionTimeEnum value; @end @interface FWFWKAudiovisualMediaTypeEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKAudiovisualMediaTypeEnum)value; @property(nonatomic, assign) FWFWKAudiovisualMediaTypeEnum value; @end @interface FWFWKWebsiteDataTypeEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKWebsiteDataTypeEnum)value; @property(nonatomic, assign) FWFWKWebsiteDataTypeEnum value; @end @interface FWFWKNavigationActionPolicyEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKNavigationActionPolicyEnum)value; @property(nonatomic, assign) FWFWKNavigationActionPolicyEnum value; @end @interface FWFNSHttpCookiePropertyKeyEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFNSHttpCookiePropertyKeyEnum)value; @property(nonatomic, assign) FWFNSHttpCookiePropertyKeyEnum value; @end /// Mirror of NSURLRequest. /// /// See https://developer.apple.com/documentation/foundation/nsurlrequest?language=objc. @interface FWFNSUrlRequestData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithUrl:(NSString *)url httpMethod:(nullable NSString *)httpMethod httpBody:(nullable FlutterStandardTypedData *)httpBody allHttpHeaderFields:(NSDictionary<NSString *, NSString *> *)allHttpHeaderFields; @property(nonatomic, copy) NSString *url; @property(nonatomic, copy, nullable) NSString *httpMethod; @property(nonatomic, strong, nullable) FlutterStandardTypedData *httpBody; @property(nonatomic, strong) NSDictionary<NSString *, NSString *> *allHttpHeaderFields; @end /// Mirror of WKUserScript. /// /// See https://developer.apple.com/documentation/webkit/wkuserscript?language=objc. @interface FWFWKUserScriptData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithSource:(NSString *)source injectionTime:(nullable FWFWKUserScriptInjectionTimeEnumData *)injectionTime isMainFrameOnly:(NSNumber *)isMainFrameOnly; @property(nonatomic, copy) NSString *source; @property(nonatomic, strong, nullable) FWFWKUserScriptInjectionTimeEnumData *injectionTime; @property(nonatomic, strong) NSNumber *isMainFrameOnly; @end /// Mirror of WKNavigationAction. /// /// See https://developer.apple.com/documentation/webkit/wknavigationaction. @interface FWFWKNavigationActionData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithRequest:(FWFNSUrlRequestData *)request targetFrame:(FWFWKFrameInfoData *)targetFrame navigationType:(FWFWKNavigationType)navigationType; @property(nonatomic, strong) FWFNSUrlRequestData *request; @property(nonatomic, strong) FWFWKFrameInfoData *targetFrame; @property(nonatomic, assign) FWFWKNavigationType navigationType; @end /// Mirror of WKFrameInfo. /// /// See https://developer.apple.com/documentation/webkit/wkframeinfo?language=objc. @interface FWFWKFrameInfoData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithIsMainFrame:(NSNumber *)isMainFrame; @property(nonatomic, strong) NSNumber *isMainFrame; @end /// Mirror of NSError. /// /// See https://developer.apple.com/documentation/foundation/nserror?language=objc. @interface FWFNSErrorData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithCode:(NSNumber *)code domain:(NSString *)domain localizedDescription:(NSString *)localizedDescription; @property(nonatomic, strong) NSNumber *code; @property(nonatomic, copy) NSString *domain; @property(nonatomic, copy) NSString *localizedDescription; @end /// Mirror of WKScriptMessage. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessage?language=objc. @interface FWFWKScriptMessageData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithName:(NSString *)name body:(id)body; @property(nonatomic, copy) NSString *name; @property(nonatomic, strong) id body; @end /// Mirror of NSHttpCookieData. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookie?language=objc. @interface FWFNSHttpCookieData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithPropertyKeys:(NSArray<FWFNSHttpCookiePropertyKeyEnumData *> *)propertyKeys propertyValues:(NSArray<id> *)propertyValues; @property(nonatomic, strong) NSArray<FWFNSHttpCookiePropertyKeyEnumData *> *propertyKeys; @property(nonatomic, strong) NSArray<id> *propertyValues; @end /// The codec used by FWFWKWebsiteDataStoreHostApi. NSObject<FlutterMessageCodec> *FWFWKWebsiteDataStoreHostApiGetCodec(void); /// Mirror of WKWebsiteDataStore. /// /// See https://developer.apple.com/documentation/webkit/wkwebsitedatastore?language=objc. @protocol FWFWKWebsiteDataStoreHostApi - (void)createFromWebViewConfigurationWithIdentifier:(NSNumber *)identifier configurationIdentifier:(NSNumber *)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)createDefaultDataStoreWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeDataFromDataStoreWithIdentifier:(NSNumber *)identifier ofTypes:(NSArray<FWFWKWebsiteDataTypeEnumData *> *)dataTypes modifiedSince:(NSNumber *)modificationTimeInSecondsSinceEpoch completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; @end extern void FWFWKWebsiteDataStoreHostApiSetup( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKWebsiteDataStoreHostApi> *_Nullable api); /// The codec used by FWFUIViewHostApi. NSObject<FlutterMessageCodec> *FWFUIViewHostApiGetCodec(void); /// Mirror of UIView. /// /// See https://developer.apple.com/documentation/uikit/uiview?language=objc. @protocol FWFUIViewHostApi - (void)setBackgroundColorForViewWithIdentifier:(NSNumber *)identifier toValue:(nullable NSNumber *)value error:(FlutterError *_Nullable *_Nonnull)error; - (void)setOpaqueForViewWithIdentifier:(NSNumber *)identifier isOpaque:(NSNumber *)opaque error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFUIViewHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFUIViewHostApi> *_Nullable api); /// The codec used by FWFUIScrollViewHostApi. NSObject<FlutterMessageCodec> *FWFUIScrollViewHostApiGetCodec(void); /// Mirror of UIScrollView. /// /// See https://developer.apple.com/documentation/uikit/uiscrollview?language=objc. @protocol FWFUIScrollViewHostApi - (void)createFromWebViewWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSArray<NSNumber *> *) contentOffsetForScrollViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)scrollByForScrollViewWithIdentifier:(NSNumber *)identifier x:(NSNumber *)x y:(NSNumber *)y error:(FlutterError *_Nullable *_Nonnull)error; - (void)setContentOffsetForScrollViewWithIdentifier:(NSNumber *)identifier toX:(NSNumber *)x y:(NSNumber *)y error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFUIScrollViewHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFUIScrollViewHostApi> *_Nullable api); /// The codec used by FWFWKWebViewConfigurationHostApi. NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationHostApiGetCodec(void); /// Mirror of WKWebViewConfiguration. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. @protocol FWFWKWebViewConfigurationHostApi - (void)createWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)createFromWebViewWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:(NSNumber *)identifier isAllowed:(NSNumber *)allow error: (FlutterError *_Nullable *_Nonnull) error; - (void) setMediaTypesRequiresUserActionForConfigurationWithIdentifier:(NSNumber *)identifier forTypes: (NSArray< FWFWKAudiovisualMediaTypeEnumData *> *)types error: (FlutterError *_Nullable *_Nonnull) error; @end extern void FWFWKWebViewConfigurationHostApiSetup( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKWebViewConfigurationHostApi> *_Nullable api); /// The codec used by FWFWKWebViewConfigurationFlutterApi. NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationFlutterApiGetCodec(void); /// Handles callbacks from an WKWebViewConfiguration instance. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. @interface FWFWKWebViewConfigurationFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)createWithIdentifier:(NSNumber *)identifier completion:(void (^)(NSError *_Nullable))completion; @end /// The codec used by FWFWKUserContentControllerHostApi. NSObject<FlutterMessageCodec> *FWFWKUserContentControllerHostApiGetCodec(void); /// Mirror of WKUserContentController. /// /// See https://developer.apple.com/documentation/webkit/wkusercontentcontroller?language=objc. @protocol FWFWKUserContentControllerHostApi - (void)createFromWebViewConfigurationWithIdentifier:(NSNumber *)identifier configurationIdentifier:(NSNumber *)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)addScriptMessageHandlerForControllerWithIdentifier:(NSNumber *)identifier handlerIdentifier:(NSNumber *)handlerIdentifier ofName:(NSString *)name error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeScriptMessageHandlerForControllerWithIdentifier:(NSNumber *)identifier name:(NSString *)name error:(FlutterError *_Nullable *_Nonnull) error; - (void)removeAllScriptMessageHandlersForControllerWithIdentifier:(NSNumber *)identifier error: (FlutterError *_Nullable *_Nonnull) error; - (void)addUserScriptForControllerWithIdentifier:(NSNumber *)identifier userScript:(FWFWKUserScriptData *)userScript error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeAllUserScriptsForControllerWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFWKUserContentControllerHostApiSetup( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKUserContentControllerHostApi> *_Nullable api); /// The codec used by FWFWKPreferencesHostApi. NSObject<FlutterMessageCodec> *FWFWKPreferencesHostApiGetCodec(void); /// Mirror of WKUserPreferences. /// /// See https://developer.apple.com/documentation/webkit/wkpreferences?language=objc. @protocol FWFWKPreferencesHostApi - (void)createFromWebViewConfigurationWithIdentifier:(NSNumber *)identifier configurationIdentifier:(NSNumber *)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setJavaScriptEnabledForPreferencesWithIdentifier:(NSNumber *)identifier isEnabled:(NSNumber *)enabled error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFWKPreferencesHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKPreferencesHostApi> *_Nullable api); /// The codec used by FWFWKScriptMessageHandlerHostApi. NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerHostApiGetCodec(void); /// Mirror of WKScriptMessageHandler. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. @protocol FWFWKScriptMessageHandlerHostApi - (void)createWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFWKScriptMessageHandlerHostApiSetup( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKScriptMessageHandlerHostApi> *_Nullable api); /// The codec used by FWFWKScriptMessageHandlerFlutterApi. NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerFlutterApiGetCodec(void); /// Handles callbacks from an WKScriptMessageHandler instance. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. @interface FWFWKScriptMessageHandlerFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)didReceiveScriptMessageForHandlerWithIdentifier:(NSNumber *)identifier userContentControllerIdentifier:(NSNumber *)userContentControllerIdentifier message:(FWFWKScriptMessageData *)message completion:(void (^)(NSError *_Nullable))completion; @end /// The codec used by FWFWKNavigationDelegateHostApi. NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateHostApiGetCodec(void); /// Mirror of WKNavigationDelegate. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. @protocol FWFWKNavigationDelegateHostApi - (void)createWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFWKNavigationDelegateHostApiSetup( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKNavigationDelegateHostApi> *_Nullable api); /// The codec used by FWFWKNavigationDelegateFlutterApi. NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateFlutterApiGetCodec(void); /// Handles callbacks from an WKNavigationDelegate instance. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. @interface FWFWKNavigationDelegateFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)didFinishNavigationForDelegateWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier URL:(nullable NSString *)url completion:(void (^)(NSError *_Nullable))completion; - (void)didStartProvisionalNavigationForDelegateWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier URL:(nullable NSString *)url completion: (void (^)(NSError *_Nullable))completion; - (void) decidePolicyForNavigationActionForDelegateWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier navigationAction: (FWFWKNavigationActionData *)navigationAction completion: (void (^)(FWFWKNavigationActionPolicyEnumData *_Nullable, NSError *_Nullable))completion; - (void)didFailNavigationForDelegateWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier error:(FWFNSErrorData *)error completion:(void (^)(NSError *_Nullable))completion; - (void)didFailProvisionalNavigationForDelegateWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier error:(FWFNSErrorData *)error completion: (void (^)(NSError *_Nullable))completion; - (void)webViewWebContentProcessDidTerminateForDelegateWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier completion:(void (^)(NSError *_Nullable)) completion; @end /// The codec used by FWFNSObjectHostApi. NSObject<FlutterMessageCodec> *FWFNSObjectHostApiGetCodec(void); /// Mirror of NSObject. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. @protocol FWFNSObjectHostApi - (void)disposeObjectWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)addObserverForObjectWithIdentifier:(NSNumber *)identifier observerIdentifier:(NSNumber *)observerIdentifier keyPath:(NSString *)keyPath options: (NSArray<FWFNSKeyValueObservingOptionsEnumData *> *)options error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeObserverForObjectWithIdentifier:(NSNumber *)identifier observerIdentifier:(NSNumber *)observerIdentifier keyPath:(NSString *)keyPath error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFNSObjectHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFNSObjectHostApi> *_Nullable api); /// The codec used by FWFNSObjectFlutterApi. NSObject<FlutterMessageCodec> *FWFNSObjectFlutterApiGetCodec(void); /// Handles callbacks from an NSObject instance. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. @interface FWFNSObjectFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)observeValueForObjectWithIdentifier:(NSNumber *)identifier keyPath:(NSString *)keyPath objectIdentifier:(NSNumber *)objectIdentifier changeKeys:(NSArray<FWFNSKeyValueChangeKeyEnumData *> *)changeKeys changeValues:(NSArray<id> *)changeValues completion:(void (^)(NSError *_Nullable))completion; - (void)disposeObjectWithIdentifier:(NSNumber *)identifier completion:(void (^)(NSError *_Nullable))completion; @end /// The codec used by FWFWKWebViewHostApi. NSObject<FlutterMessageCodec> *FWFWKWebViewHostApiGetCodec(void); /// Mirror of WKWebView. /// /// See https://developer.apple.com/documentation/webkit/wkwebview?language=objc. @protocol FWFWKWebViewHostApi - (void)createWithIdentifier:(NSNumber *)identifier configurationIdentifier:(NSNumber *)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setUIDelegateForWebViewWithIdentifier:(NSNumber *)identifier delegateIdentifier:(nullable NSNumber *)uiDelegateIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setNavigationDelegateForWebViewWithIdentifier:(NSNumber *)identifier delegateIdentifier: (nullable NSNumber *)navigationDelegateIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)URLForWebViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSNumber *)estimatedProgressForWebViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull) error; - (void)loadRequestForWebViewWithIdentifier:(NSNumber *)identifier request:(FWFNSUrlRequestData *)request error:(FlutterError *_Nullable *_Nonnull)error; - (void)loadHTMLForWebViewWithIdentifier:(NSNumber *)identifier HTMLString:(NSString *)string baseURL:(nullable NSString *)baseUrl error:(FlutterError *_Nullable *_Nonnull)error; - (void)loadFileForWebViewWithIdentifier:(NSNumber *)identifier fileURL:(NSString *)url readAccessURL:(NSString *)readAccessUrl error:(FlutterError *_Nullable *_Nonnull)error; - (void)loadAssetForWebViewWithIdentifier:(NSNumber *)identifier assetKey:(NSString *)key error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSNumber *)canGoBackForWebViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSNumber *)canGoForwardForWebViewWithIdentifier:(NSNumber *)identifier error: (FlutterError *_Nullable *_Nonnull)error; - (void)goBackForWebViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)goForwardForWebViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)reloadWebViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)titleForWebViewWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setAllowsBackForwardForWebViewWithIdentifier:(NSNumber *)identifier isAllowed:(NSNumber *)allow error:(FlutterError *_Nullable *_Nonnull)error; - (void)setUserAgentForWebViewWithIdentifier:(NSNumber *)identifier userAgent:(nullable NSString *)userAgent error:(FlutterError *_Nullable *_Nonnull)error; - (void)evaluateJavaScriptForWebViewWithIdentifier:(NSNumber *)identifier javaScriptString:(NSString *)javaScriptString completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; @end extern void FWFWKWebViewHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKWebViewHostApi> *_Nullable api); /// The codec used by FWFWKUIDelegateHostApi. NSObject<FlutterMessageCodec> *FWFWKUIDelegateHostApiGetCodec(void); /// Mirror of WKUIDelegate. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. @protocol FWFWKUIDelegateHostApi - (void)createWithIdentifier:(NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void FWFWKUIDelegateHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKUIDelegateHostApi> *_Nullable api); /// The codec used by FWFWKUIDelegateFlutterApi. NSObject<FlutterMessageCodec> *FWFWKUIDelegateFlutterApiGetCodec(void); /// Handles callbacks from an WKUIDelegate instance. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. @interface FWFWKUIDelegateFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)onCreateWebViewForDelegateWithIdentifier:(NSNumber *)identifier webViewIdentifier:(NSNumber *)webViewIdentifier configurationIdentifier:(NSNumber *)configurationIdentifier navigationAction:(FWFWKNavigationActionData *)navigationAction completion:(void (^)(NSError *_Nullable))completion; @end /// The codec used by FWFWKHttpCookieStoreHostApi. NSObject<FlutterMessageCodec> *FWFWKHttpCookieStoreHostApiGetCodec(void); /// Mirror of WKHttpCookieStore. /// /// See https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc. @protocol FWFWKHttpCookieStoreHostApi - (void)createFromWebsiteDataStoreWithIdentifier:(NSNumber *)identifier dataStoreIdentifier:(NSNumber *)websiteDataStoreIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setCookieForStoreWithIdentifier:(NSNumber *)identifier cookie:(FWFNSHttpCookieData *)cookie completion:(void (^)(FlutterError *_Nullable))completion; @end extern void FWFWKHttpCookieStoreHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKHttpCookieStoreHostApi> *_Nullable api); NS_ASSUME_NONNULL_END
plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.h/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.h", "repo_id": "plugins", "token_count": 15680 }
1,258
// 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 "FWFScrollViewHostApi.h" #import "FWFWebViewHostApi.h" @interface FWFScrollViewHostApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFScrollViewHostApiImpl - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; } return self; } - (UIScrollView *)scrollViewForIdentifier:(NSNumber *)identifier { return (UIScrollView *)[self.instanceManager instanceForIdentifier:identifier.longValue]; } - (void)createFromWebViewWithIdentifier:(nonnull NSNumber *)identifier webViewIdentifier:(nonnull NSNumber *)webViewIdentifier error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { WKWebView *webView = (WKWebView *)[self.instanceManager instanceForIdentifier:webViewIdentifier.longValue]; [self.instanceManager addDartCreatedInstance:webView.scrollView withIdentifier:identifier.longValue]; } - (NSArray<NSNumber *> *) contentOffsetForScrollViewWithIdentifier:(nonnull NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error { CGPoint point = [[self scrollViewForIdentifier:identifier] contentOffset]; return @[ @(point.x), @(point.y) ]; } - (void)scrollByForScrollViewWithIdentifier:(nonnull NSNumber *)identifier x:(nonnull NSNumber *)x y:(nonnull NSNumber *)y error:(FlutterError *_Nullable *_Nonnull)error { UIScrollView *scrollView = [self scrollViewForIdentifier:identifier]; CGPoint contentOffset = scrollView.contentOffset; [scrollView setContentOffset:CGPointMake(contentOffset.x + x.doubleValue, contentOffset.y + y.doubleValue)]; } - (void)setContentOffsetForScrollViewWithIdentifier:(nonnull NSNumber *)identifier toX:(nonnull NSNumber *)x y:(nonnull NSNumber *)y error:(FlutterError *_Nullable *_Nonnull)error { [[self scrollViewForIdentifier:identifier] setContentOffset:CGPointMake(x.doubleValue, y.doubleValue)]; } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewHostApi.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewHostApi.m", "repo_id": "plugins", "token_count": 1115 }
1,259
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Foundation/Foundation.h> #import <webview_flutter_wkwebview/FLTWebViewFlutterPlugin.h> #import <webview_flutter_wkwebview/FWFDataConverters.h> #import <webview_flutter_wkwebview/FWFGeneratedWebKitApis.h> #import <webview_flutter_wkwebview/FWFHTTPCookieStoreHostApi.h> #import <webview_flutter_wkwebview/FWFInstanceManager.h> #import <webview_flutter_wkwebview/FWFNavigationDelegateHostApi.h> #import <webview_flutter_wkwebview/FWFObjectHostApi.h> #import <webview_flutter_wkwebview/FWFPreferencesHostApi.h> #import <webview_flutter_wkwebview/FWFScriptMessageHandlerHostApi.h> #import <webview_flutter_wkwebview/FWFScrollViewHostApi.h> #import <webview_flutter_wkwebview/FWFUIDelegateHostApi.h> #import <webview_flutter_wkwebview/FWFUIViewHostApi.h> #import <webview_flutter_wkwebview/FWFUserContentControllerHostApi.h> #import <webview_flutter_wkwebview/FWFWebViewConfigurationHostApi.h> #import <webview_flutter_wkwebview/FWFWebViewFlutterWKWebViewExternalAPI.h> #import <webview_flutter_wkwebview/FWFWebViewHostApi.h> #import <webview_flutter_wkwebview/FWFWebsiteDataStoreHostApi.h>
plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/webview-umbrella.h/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/webview-umbrella.h", "repo_id": "plugins", "token_count": 473 }
1,260
// 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 'foundation/foundation.dart'; import 'web_kit/web_kit.dart'; import 'webkit_proxy.dart'; /// Object specifying creation parameters for a [WebKitWebViewCookieManager]. class WebKitWebViewCookieManagerCreationParams extends PlatformWebViewCookieManagerCreationParams { /// Constructs a [WebKitWebViewCookieManagerCreationParams]. WebKitWebViewCookieManagerCreationParams({ WebKitProxy? webKitProxy, }) : webKitProxy = webKitProxy ?? const WebKitProxy(); /// Constructs a [WebKitWebViewCookieManagerCreationParams] using a /// [PlatformWebViewCookieManagerCreationParams]. WebKitWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams( // Recommended placeholder to prevent being broken by platform interface. // ignore: avoid_unused_constructor_parameters PlatformWebViewCookieManagerCreationParams params, { @visibleForTesting WebKitProxy? webKitProxy, }) : this(webKitProxy: webKitProxy); /// Handles constructing objects and calling static methods for the WebKit /// native library. @visibleForTesting final WebKitProxy webKitProxy; /// Manages stored data for [WKWebView]s. late final WKWebsiteDataStore _websiteDataStore = webKitProxy.defaultWebsiteDataStore(); } /// An implementation of [PlatformWebViewCookieManager] with the WebKit api. class WebKitWebViewCookieManager extends PlatformWebViewCookieManager { /// Constructs a [WebKitWebViewCookieManager]. WebKitWebViewCookieManager(PlatformWebViewCookieManagerCreationParams params) : super.implementation( params is WebKitWebViewCookieManagerCreationParams ? params : WebKitWebViewCookieManagerCreationParams .fromPlatformWebViewCookieManagerCreationParams(params), ); WebKitWebViewCookieManagerCreationParams get _webkitParams => params as WebKitWebViewCookieManagerCreationParams; @override Future<bool> clearCookies() { return _webkitParams._websiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{WKWebsiteDataType.cookies}, DateTime.fromMillisecondsSinceEpoch(0), ); } @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 _webkitParams._websiteDataStore.httpCookieStore.setCookie( NSHttpCookie.withProperties( <NSHttpCookiePropertyKey, Object>{ NSHttpCookiePropertyKey.name: cookie.name, NSHttpCookiePropertyKey.value: cookie.value, NSHttpCookiePropertyKey.domain: cookie.domain, NSHttpCookiePropertyKey.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 return !path.codeUnits.any( (int char) { return (char < 0x20 || char > 0x3A) && (char < 0x3C || char > 0x7E); }, ); } }
plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_cookie_manager.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_cookie_manager.dart", "repo_id": "plugins", "token_count": 1181 }
1,261
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_wkwebview/src/common/instance_manager.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/web_kit/web_kit_api_impls.dart'; import '../common/test_web_kit.g.dart'; import 'web_kit_test.mocks.dart'; @GenerateMocks(<Type>[ TestWKHttpCookieStoreHostApi, TestWKNavigationDelegateHostApi, TestWKPreferencesHostApi, TestWKScriptMessageHandlerHostApi, TestWKUIDelegateHostApi, TestWKUserContentControllerHostApi, TestWKWebViewConfigurationHostApi, TestWKWebViewHostApi, TestWKWebsiteDataStoreHostApi, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebKit', () { late InstanceManager instanceManager; late WebKitFlutterApis flutterApis; setUp(() { instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {}); flutterApis = WebKitFlutterApis(instanceManager: instanceManager); WebKitFlutterApis.instance = flutterApis; }); group('WKWebsiteDataStore', () { late MockTestWKWebsiteDataStoreHostApi mockPlatformHostApi; late WKWebsiteDataStore websiteDataStore; late WKWebViewConfiguration webViewConfiguration; setUp(() { mockPlatformHostApi = MockTestWKWebsiteDataStoreHostApi(); TestWKWebsiteDataStoreHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); websiteDataStore = WKWebsiteDataStore.fromWebViewConfiguration( webViewConfiguration, instanceManager: instanceManager, ); }); tearDown(() { TestWKWebsiteDataStoreHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('WKWebViewConfigurationFlutterApi.create', () { final WebKitFlutterApis flutterApis = WebKitFlutterApis( instanceManager: instanceManager, ); flutterApis.webViewConfiguration.create(2); expect(instanceManager.containsIdentifier(2), isTrue); expect( instanceManager.getInstanceWithWeakReference(2), isA<WKWebViewConfiguration>(), ); }); test('createFromWebViewConfiguration', () { verify(mockPlatformHostApi.createFromWebViewConfiguration( instanceManager.getIdentifier(websiteDataStore), instanceManager.getIdentifier(webViewConfiguration), )); }); test('createDefaultDataStore', () { final WKWebsiteDataStore defaultDataStore = WKWebsiteDataStore.defaultDataStore; verify( mockPlatformHostApi.createDefaultDataStore( NSObject.globalInstanceManager.getIdentifier(defaultDataStore), ), ); }); test('removeDataOfTypes', () { when(mockPlatformHostApi.removeDataOfTypes( any, any, any, )).thenAnswer((_) => Future<bool>.value(true)); expect( websiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{WKWebsiteDataType.cookies}, DateTime.fromMillisecondsSinceEpoch(5000), ), completion(true), ); final List<dynamic> capturedArgs = verify(mockPlatformHostApi.removeDataOfTypes( instanceManager.getIdentifier(websiteDataStore), captureAny, 5.0, )).captured; final List<WKWebsiteDataTypeEnumData> typeData = (capturedArgs.single as List<Object?>) .cast<WKWebsiteDataTypeEnumData>(); expect(typeData.single.value, WKWebsiteDataTypeEnum.cookies); }); }); group('WKHttpCookieStore', () { late MockTestWKHttpCookieStoreHostApi mockPlatformHostApi; late WKHttpCookieStore httpCookieStore; late WKWebsiteDataStore websiteDataStore; setUp(() { mockPlatformHostApi = MockTestWKHttpCookieStoreHostApi(); TestWKHttpCookieStoreHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); TestWKWebsiteDataStoreHostApi.setup( MockTestWKWebsiteDataStoreHostApi(), ); websiteDataStore = WKWebsiteDataStore.fromWebViewConfiguration( WKWebViewConfiguration(instanceManager: instanceManager), instanceManager: instanceManager, ); httpCookieStore = WKHttpCookieStore.fromWebsiteDataStore( websiteDataStore, instanceManager: instanceManager, ); }); tearDown(() { TestWKHttpCookieStoreHostApi.setup(null); TestWKWebsiteDataStoreHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('createFromWebsiteDataStore', () { verify(mockPlatformHostApi.createFromWebsiteDataStore( instanceManager.getIdentifier(httpCookieStore), instanceManager.getIdentifier(websiteDataStore), )); }); test('setCookie', () async { await httpCookieStore.setCookie( const NSHttpCookie.withProperties(<NSHttpCookiePropertyKey, Object>{ NSHttpCookiePropertyKey.comment: 'aComment', })); final NSHttpCookieData cookie = verify( mockPlatformHostApi.setCookie( instanceManager.getIdentifier(httpCookieStore), captureAny, ), ).captured.single as NSHttpCookieData; expect( cookie.propertyKeys.single!.value, NSHttpCookiePropertyKeyEnum.comment, ); expect(cookie.propertyValues.single, 'aComment'); }); }); group('WKScriptMessageHandler', () { late MockTestWKScriptMessageHandlerHostApi mockPlatformHostApi; late WKScriptMessageHandler scriptMessageHandler; setUp(() async { mockPlatformHostApi = MockTestWKScriptMessageHandlerHostApi(); TestWKScriptMessageHandlerHostApi.setup(mockPlatformHostApi); scriptMessageHandler = WKScriptMessageHandler( didReceiveScriptMessage: (_, __) {}, instanceManager: instanceManager, ); }); tearDown(() { TestWKScriptMessageHandlerHostApi.setup(null); }); test('create', () async { verify(mockPlatformHostApi.create( instanceManager.getIdentifier(scriptMessageHandler), )); }); test('didReceiveScriptMessage', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); scriptMessageHandler = WKScriptMessageHandler( instanceManager: instanceManager, didReceiveScriptMessage: ( WKUserContentController userContentController, WKScriptMessage message, ) { argsCompleter.complete(<Object?>[userContentController, message]); }, ); final WKUserContentController userContentController = WKUserContentController.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(userContentController, 2); WebKitFlutterApis.instance.scriptMessageHandler.didReceiveScriptMessage( instanceManager.getIdentifier(scriptMessageHandler)!, 2, WKScriptMessageData(name: 'name'), ); expect( argsCompleter.future, completion(<Object?>[userContentController, isA<WKScriptMessage>()]), ); }); }); group('WKPreferences', () { late MockTestWKPreferencesHostApi mockPlatformHostApi; late WKPreferences preferences; late WKWebViewConfiguration webViewConfiguration; setUp(() { mockPlatformHostApi = MockTestWKPreferencesHostApi(); TestWKPreferencesHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); preferences = WKPreferences.fromWebViewConfiguration( webViewConfiguration, instanceManager: instanceManager, ); }); tearDown(() { TestWKPreferencesHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('createFromWebViewConfiguration', () async { verify(mockPlatformHostApi.createFromWebViewConfiguration( instanceManager.getIdentifier(preferences), instanceManager.getIdentifier(webViewConfiguration), )); }); test('setJavaScriptEnabled', () async { await preferences.setJavaScriptEnabled(true); verify(mockPlatformHostApi.setJavaScriptEnabled( instanceManager.getIdentifier(preferences), true, )); }); }); group('WKUserContentController', () { late MockTestWKUserContentControllerHostApi mockPlatformHostApi; late WKUserContentController userContentController; late WKWebViewConfiguration webViewConfiguration; setUp(() { mockPlatformHostApi = MockTestWKUserContentControllerHostApi(); TestWKUserContentControllerHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); userContentController = WKUserContentController.fromWebViewConfiguration( webViewConfiguration, instanceManager: instanceManager, ); }); tearDown(() { TestWKUserContentControllerHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('createFromWebViewConfiguration', () async { verify(mockPlatformHostApi.createFromWebViewConfiguration( instanceManager.getIdentifier(userContentController), instanceManager.getIdentifier(webViewConfiguration), )); }); test('addScriptMessageHandler', () async { TestWKScriptMessageHandlerHostApi.setup( MockTestWKScriptMessageHandlerHostApi(), ); final WKScriptMessageHandler handler = WKScriptMessageHandler( didReceiveScriptMessage: (_, __) {}, instanceManager: instanceManager, ); userContentController.addScriptMessageHandler(handler, 'handlerName'); verify(mockPlatformHostApi.addScriptMessageHandler( instanceManager.getIdentifier(userContentController), instanceManager.getIdentifier(handler), 'handlerName', )); }); test('removeScriptMessageHandler', () async { userContentController.removeScriptMessageHandler('handlerName'); verify(mockPlatformHostApi.removeScriptMessageHandler( instanceManager.getIdentifier(userContentController), 'handlerName', )); }); test('removeAllScriptMessageHandlers', () async { userContentController.removeAllScriptMessageHandlers(); verify(mockPlatformHostApi.removeAllScriptMessageHandlers( instanceManager.getIdentifier(userContentController), )); }); test('addUserScript', () { userContentController.addUserScript(const WKUserScript( 'aScript', WKUserScriptInjectionTime.atDocumentEnd, isMainFrameOnly: false, )); verify(mockPlatformHostApi.addUserScript( instanceManager.getIdentifier(userContentController), argThat(isA<WKUserScriptData>()), )); }); test('removeAllUserScripts', () { userContentController.removeAllUserScripts(); verify(mockPlatformHostApi.removeAllUserScripts( instanceManager.getIdentifier(userContentController), )); }); }); group('WKWebViewConfiguration', () { late MockTestWKWebViewConfigurationHostApi mockPlatformHostApi; late WKWebViewConfiguration webViewConfiguration; setUp(() async { mockPlatformHostApi = MockTestWKWebViewConfigurationHostApi(); TestWKWebViewConfigurationHostApi.setup(mockPlatformHostApi); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); }); tearDown(() { TestWKWebViewConfigurationHostApi.setup(null); }); test('create', () async { verify( mockPlatformHostApi.create(instanceManager.getIdentifier( webViewConfiguration, )), ); }); test('createFromWebView', () async { TestWKWebViewHostApi.setup(MockTestWKWebViewHostApi()); final WKWebView webView = WKWebView( webViewConfiguration, instanceManager: instanceManager, ); final WKWebViewConfiguration configurationFromWebView = WKWebViewConfiguration.fromWebView( webView, instanceManager: instanceManager, ); verify(mockPlatformHostApi.createFromWebView( instanceManager.getIdentifier(configurationFromWebView), instanceManager.getIdentifier(webView), )); }); test('allowsInlineMediaPlayback', () { webViewConfiguration.setAllowsInlineMediaPlayback(true); verify(mockPlatformHostApi.setAllowsInlineMediaPlayback( instanceManager.getIdentifier(webViewConfiguration), true, )); }); test('mediaTypesRequiringUserActionForPlayback', () { webViewConfiguration.setMediaTypesRequiringUserActionForPlayback( <WKAudiovisualMediaType>{ WKAudiovisualMediaType.audio, WKAudiovisualMediaType.video, }, ); final List<WKAudiovisualMediaTypeEnumData?> typeData = verify( mockPlatformHostApi.setMediaTypesRequiringUserActionForPlayback( instanceManager.getIdentifier(webViewConfiguration), captureAny, )).captured.single as List<WKAudiovisualMediaTypeEnumData?>; expect(typeData, hasLength(2)); expect(typeData[0]!.value, WKAudiovisualMediaTypeEnum.audio); expect(typeData[1]!.value, WKAudiovisualMediaTypeEnum.video); }); }); group('WKNavigationDelegate', () { late MockTestWKNavigationDelegateHostApi mockPlatformHostApi; late WKWebView webView; late WKNavigationDelegate navigationDelegate; setUp(() async { mockPlatformHostApi = MockTestWKNavigationDelegateHostApi(); TestWKNavigationDelegateHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); TestWKWebViewHostApi.setup(MockTestWKWebViewHostApi()); webView = WKWebView( WKWebViewConfiguration(instanceManager: instanceManager), instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, ); }); tearDown(() { TestWKNavigationDelegateHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); TestWKWebViewHostApi.setup(null); }); test('create', () async { navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, ); verify(mockPlatformHostApi.create( instanceManager.getIdentifier(navigationDelegate), )); }); test('didFinishNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didFinishNavigation: (WKWebView webView, String? url) { argsCompleter.complete(<Object?>[webView, url]); }, ); WebKitFlutterApis.instance.navigationDelegate.didFinishNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, 'url', ); expect(argsCompleter.future, completion(<Object?>[webView, 'url'])); }); test('didStartProvisionalNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didStartProvisionalNavigation: (WKWebView webView, String? url) { argsCompleter.complete(<Object?>[webView, url]); }, ); WebKitFlutterApis.instance.navigationDelegate .didStartProvisionalNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, 'url', ); expect(argsCompleter.future, completion(<Object?>[webView, 'url'])); }); test('decidePolicyForNavigationAction', () async { WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, decidePolicyForNavigationAction: ( WKWebView webView, WKNavigationAction navigationAction, ) async { return WKNavigationActionPolicy.cancel; }, ); final WKNavigationActionPolicyEnumData policyData = await WebKitFlutterApis.instance.navigationDelegate .decidePolicyForNavigationAction( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, WKNavigationActionData( request: NSUrlRequestData( url: 'url', allHttpHeaderFields: <String, String>{}, ), targetFrame: WKFrameInfoData(isMainFrame: false), navigationType: WKNavigationType.linkActivated, ), ); expect(policyData.value, WKNavigationActionPolicyEnum.cancel); }); test('didFailNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didFailNavigation: (WKWebView webView, NSError error) { argsCompleter.complete(<Object?>[webView, error]); }, ); WebKitFlutterApis.instance.navigationDelegate.didFailNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, NSErrorData( code: 23, domain: 'Hello', localizedDescription: 'localiziedDescription', ), ); expect( argsCompleter.future, completion(<Object?>[webView, isA<NSError>()]), ); }); test('didFailProvisionalNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didFailProvisionalNavigation: (WKWebView webView, NSError error) { argsCompleter.complete(<Object?>[webView, error]); }, ); WebKitFlutterApis.instance.navigationDelegate .didFailProvisionalNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, NSErrorData( code: 23, domain: 'Hello', localizedDescription: 'localiziedDescription', ), ); expect( argsCompleter.future, completion(<Object?>[webView, isA<NSError>()]), ); }); test('webViewWebContentProcessDidTerminate', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, webViewWebContentProcessDidTerminate: (WKWebView webView) { argsCompleter.complete(<Object?>[webView]); }, ); WebKitFlutterApis.instance.navigationDelegate .webViewWebContentProcessDidTerminate( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, ); expect(argsCompleter.future, completion(<Object?>[webView])); }); }); group('WKWebView', () { late MockTestWKWebViewHostApi mockPlatformHostApi; late WKWebViewConfiguration webViewConfiguration; late WKWebView webView; late int webViewInstanceId; setUp(() { mockPlatformHostApi = MockTestWKWebViewHostApi(); TestWKWebViewHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi()); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); webView = WKWebView( webViewConfiguration, instanceManager: instanceManager, ); webViewInstanceId = instanceManager.getIdentifier(webView)!; }); tearDown(() { TestWKWebViewHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('create', () async { verify(mockPlatformHostApi.create( instanceManager.getIdentifier(webView), instanceManager.getIdentifier( webViewConfiguration, ), )); }); test('setUIDelegate', () async { TestWKUIDelegateHostApi.setup(MockTestWKUIDelegateHostApi()); final WKUIDelegate uiDelegate = WKUIDelegate( instanceManager: instanceManager, ); await webView.setUIDelegate(uiDelegate); verify(mockPlatformHostApi.setUIDelegate( webViewInstanceId, instanceManager.getIdentifier(uiDelegate), )); TestWKUIDelegateHostApi.setup(null); }); test('setNavigationDelegate', () async { TestWKNavigationDelegateHostApi.setup( MockTestWKNavigationDelegateHostApi(), ); final WKNavigationDelegate navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, ); await webView.setNavigationDelegate(navigationDelegate); verify(mockPlatformHostApi.setNavigationDelegate( webViewInstanceId, instanceManager.getIdentifier(navigationDelegate), )); TestWKNavigationDelegateHostApi.setup(null); }); test('getUrl', () { when( mockPlatformHostApi.getUrl(webViewInstanceId), ).thenReturn('www.flutter.dev'); expect(webView.getUrl(), completion('www.flutter.dev')); }); test('getEstimatedProgress', () { when( mockPlatformHostApi.getEstimatedProgress(webViewInstanceId), ).thenReturn(54.5); expect(webView.getEstimatedProgress(), completion(54.5)); }); test('loadRequest', () { webView.loadRequest(const NSUrlRequest(url: 'www.flutter.dev')); verify(mockPlatformHostApi.loadRequest( webViewInstanceId, argThat(isA<NSUrlRequestData>()), )); }); test('loadHtmlString', () { webView.loadHtmlString('a', baseUrl: 'b'); verify(mockPlatformHostApi.loadHtmlString(webViewInstanceId, 'a', 'b')); }); test('loadFileUrl', () { webView.loadFileUrl('a', readAccessUrl: 'b'); verify(mockPlatformHostApi.loadFileUrl(webViewInstanceId, 'a', 'b')); }); test('loadFlutterAsset', () { webView.loadFlutterAsset('a'); verify(mockPlatformHostApi.loadFlutterAsset(webViewInstanceId, 'a')); }); test('canGoBack', () { when(mockPlatformHostApi.canGoBack(webViewInstanceId)).thenReturn(true); expect(webView.canGoBack(), completion(isTrue)); }); test('canGoForward', () { when(mockPlatformHostApi.canGoForward(webViewInstanceId)) .thenReturn(false); expect(webView.canGoForward(), completion(isFalse)); }); test('goBack', () { webView.goBack(); verify(mockPlatformHostApi.goBack(webViewInstanceId)); }); test('goForward', () { webView.goForward(); verify(mockPlatformHostApi.goForward(webViewInstanceId)); }); test('reload', () { webView.reload(); verify(mockPlatformHostApi.reload(webViewInstanceId)); }); test('getTitle', () { when(mockPlatformHostApi.getTitle(webViewInstanceId)) .thenReturn('MyTitle'); expect(webView.getTitle(), completion('MyTitle')); }); test('setAllowsBackForwardNavigationGestures', () { webView.setAllowsBackForwardNavigationGestures(false); verify(mockPlatformHostApi.setAllowsBackForwardNavigationGestures( webViewInstanceId, false, )); }); test('customUserAgent', () { webView.setCustomUserAgent('hello'); verify(mockPlatformHostApi.setCustomUserAgent( webViewInstanceId, 'hello', )); }); test('evaluateJavaScript', () { when(mockPlatformHostApi.evaluateJavaScript(webViewInstanceId, 'gogo')) .thenAnswer((_) => Future<String>.value('stopstop')); expect(webView.evaluateJavaScript('gogo'), completion('stopstop')); }); test('evaluateJavaScript returns NSError', () { when(mockPlatformHostApi.evaluateJavaScript(webViewInstanceId, 'gogo')) .thenThrow( PlatformException( code: '', details: NSErrorData( code: 0, domain: 'domain', localizedDescription: 'desc', ), ), ); expect( webView.evaluateJavaScript('gogo'), throwsA( isA<PlatformException>().having( (PlatformException exception) => exception.details, 'details', isA<NSError>(), ), ), ); }); }); group('WKUIDelegate', () { late MockTestWKUIDelegateHostApi mockPlatformHostApi; late WKUIDelegate uiDelegate; setUp(() async { mockPlatformHostApi = MockTestWKUIDelegateHostApi(); TestWKUIDelegateHostApi.setup(mockPlatformHostApi); uiDelegate = WKUIDelegate(instanceManager: instanceManager); }); tearDown(() { TestWKUIDelegateHostApi.setup(null); }); test('create', () async { verify(mockPlatformHostApi.create( instanceManager.getIdentifier(uiDelegate), )); }); test('onCreateWebView', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); uiDelegate = WKUIDelegate( instanceManager: instanceManager, onCreateWebView: ( WKWebView webView, WKWebViewConfiguration configuration, WKNavigationAction navigationAction, ) { argsCompleter.complete(<Object?>[ webView, configuration, navigationAction, ]); }, ); final WKWebView webView = WKWebView.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(webView, 2); final WKWebViewConfiguration configuration = WKWebViewConfiguration.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(configuration, 3); WebKitFlutterApis.instance.uiDelegate.onCreateWebView( instanceManager.getIdentifier(uiDelegate)!, 2, 3, WKNavigationActionData( request: NSUrlRequestData( url: 'url', allHttpHeaderFields: <String, String>{}, ), targetFrame: WKFrameInfoData(isMainFrame: false), navigationType: WKNavigationType.linkActivated, ), ); expect( argsCompleter.future, completion(<Object?>[ webView, configuration, isA<WKNavigationAction>(), ]), ); }); }); }); }
plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/web_kit/web_kit_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/web_kit/web_kit_test.dart", "repo_id": "plugins", "token_count": 13019 }
1,262
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io' as io; import 'package:file/file.dart'; import 'core.dart'; /// A class used to run processes. /// /// We use this instead of directly running the process so it can be overridden /// in tests. class ProcessRunner { /// Creates a new process runner. const ProcessRunner(); /// Run the [executable] with [args] and stream output to stderr and stdout. /// /// The current working directory of [executable] can be overridden by /// passing [workingDir]. /// /// If [exitOnError] is set to `true`, then this will throw an error if /// the [executable] terminates with a non-zero exit code. /// /// Returns the exit code of the [executable]. Future<int> runAndStream( String executable, List<String> args, { Directory? workingDir, bool exitOnError = false, }) async { print( 'Running command: "$executable ${args.join(' ')}" in ${workingDir?.path ?? io.Directory.current.path}'); final io.Process process = await io.Process.start(executable, args, workingDirectory: workingDir?.path); await io.stdout.addStream(process.stdout); await io.stderr.addStream(process.stderr); if (exitOnError && await process.exitCode != 0) { final String error = _getErrorString(executable, args, workingDir: workingDir); print('$error See above for details.'); throw ToolExit(await process.exitCode); } return process.exitCode; } /// Run the [executable] with [args]. /// /// The current working directory of [executable] can be overridden by /// passing [workingDir]. /// /// If [exitOnError] is set to `true`, then this will throw an error if /// the [executable] terminates with a non-zero exit code. /// Defaults to `false`. /// /// If [logOnError] is set to `true`, it will print a formatted message about the error. /// Defaults to `false` /// /// Returns the [io.ProcessResult] of the [executable]. Future<io.ProcessResult> run(String executable, List<String> args, {Directory? workingDir, bool exitOnError = false, bool logOnError = false, Encoding stdoutEncoding = io.systemEncoding, Encoding stderrEncoding = io.systemEncoding}) async { final io.ProcessResult result = await io.Process.run(executable, args, workingDirectory: workingDir?.path, stdoutEncoding: stdoutEncoding, stderrEncoding: stderrEncoding); if (result.exitCode != 0) { if (logOnError) { final String error = _getErrorString(executable, args, workingDir: workingDir); print('$error Stderr:\n${result.stdout}'); } if (exitOnError) { throw ToolExit(result.exitCode); } } return result; } /// Starts the [executable] with [args]. /// /// The current working directory of [executable] can be overridden by /// passing [workingDir]. /// /// Returns the started [io.Process]. Future<io.Process> start(String executable, List<String> args, {Directory? workingDirectory}) async { final io.Process process = await io.Process.start(executable, args, workingDirectory: workingDirectory?.path); return process; } String _getErrorString(String executable, List<String> args, {Directory? workingDir}) { final String workdir = workingDir == null ? '' : ' in ${workingDir.path}'; return 'ERROR: Unable to execute "$executable ${args.join(' ')}"$workdir.'; } }
plugins/script/tool/lib/src/common/process_runner.dart/0
{ "file_path": "plugins/script/tool/lib/src/common/process_runner.dart", "repo_id": "plugins", "token_count": 1233 }
1,263
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.FlutterViewIntegration" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_500</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> </resources>
samples/add_to_app/android_view/android_view/app/src/main/res/values/themes.xml/0
{ "file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/values/themes.xml", "repo_id": "samples", "token_count": 318 }
1,264
#Wed Mar 10 09:43:03 PST 2021 distributionBase=GRADLE_USER_HOME distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip distributionPath=wrapper/dists zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME
samples/add_to_app/books/android_books/gradle/wrapper/gradle-wrapper.properties/0
{ "file_path": "samples/add_to_app/books/android_books/gradle/wrapper/gradle-wrapper.properties", "repo_id": "samples", "token_count": 83 }
1,265
// Autogenerated from Pigeon (v1.0.1), 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 BKBook; @class BKThumbnail; @interface BKBook : NSObject @property(nonatomic, copy, nullable) NSString *title; @property(nonatomic, copy, nullable) NSString *subtitle; @property(nonatomic, copy, nullable) NSString *author; @property(nonatomic, copy, nullable) NSString *summary; @property(nonatomic, copy, nullable) NSString *publishDate; @property(nonatomic, strong, nullable) NSNumber *pageCount; @property(nonatomic, strong, nullable) BKThumbnail *thumbnail; @end @interface BKThumbnail : NSObject @property(nonatomic, copy, nullable) NSString *url; @end /// The codec used by BKFlutterBookApi. NSObject<FlutterMessageCodec> *BKFlutterBookApiGetCodec(void); @interface BKFlutterBookApi : NSObject - (instancetype)initWithBinaryMessenger: (id<FlutterBinaryMessenger>)binaryMessenger; - (void)displayBookDetailsBook:(BKBook *)book completion:(void (^)(NSError *_Nullable))completion; @end /// The codec used by BKHostBookApi. NSObject<FlutterMessageCodec> *BKHostBookApiGetCodec(void); @protocol BKHostBookApi - (void)cancelWithError:(FlutterError *_Nullable *_Nonnull)error; - (void)finishEditingBookBook:(BKBook *)book error:(FlutterError *_Nullable *_Nonnull)error; @end extern void BKHostBookApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<BKHostBookApi> *_Nullable api); NS_ASSUME_NONNULL_END
samples/add_to_app/books/ios_books/IosBooks/api.h/0
{ "file_path": "samples/add_to_app/books/ios_books/IosBooks/api.h", "repo_id": "samples", "token_count": 643 }
1,266
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.8.22' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.4.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() mavenCentral() } } task clean(type: Delete) { delete rootProject.buildDir }
samples/add_to_app/fullscreen/android_fullscreen/build.gradle/0
{ "file_path": "samples/add_to_app/fullscreen/android_fullscreen/build.gradle", "repo_id": "samples", "token_count": 258 }
1,267
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import XCTest class IOSFullScreenUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreenUITests/IOSFullScreenUITests.swift/0
{ "file_path": "samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreenUITests/IOSFullScreenUITests.swift", "repo_id": "samples", "token_count": 348 }
1,268
package dev.flutter.multipleflutters import android.content.Context import android.content.Intent import android.os.Bundle import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine /** * This is an Activity that displays one instance of Flutter. * * EngineBindings is used to bridge communication between the Flutter instance and the DataModel. */ class SingleFlutterActivity : FlutterActivity(), EngineBindingsDelegate { private val engineBindings: EngineBindings by lazy { EngineBindings(activity = this, delegate = this, entrypoint = "main") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) engineBindings.attach() } override fun onDestroy() { super.onDestroy() engineBindings.detach() } override fun provideFlutterEngine(context: Context): FlutterEngine? { return engineBindings.engine } override fun onNext() { val flutterIntent = Intent(this, MainActivity::class.java) startActivity(flutterIntent) } }
samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/SingleFlutterActivity.kt/0
{ "file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/SingleFlutterActivity.kt", "repo_id": "samples", "token_count": 363 }
1,269
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.MultipleFlutters" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_200</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/black</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_200</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> </resources>
samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/values-night/themes.xml/0
{ "file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/values-night/themes.xml", "repo_id": "samples", "token_count": 316 }
1,270
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:flutter/material.dart'; Color generateColor() => Color(0xFFFFFFFF & Random().nextInt(0xFFFFFFFF)); Widget generateContainer(int keyCount) => Container( key: ValueKey<int>(keyCount), height: Random().nextDouble() * 200, width: Random().nextDouble() * 200, decoration: BoxDecoration( color: generateColor(), borderRadius: BorderRadius.circular(Random().nextDouble() * 100), border: Border.all( color: generateColor(), width: Random().nextDouble() * 5, ), ), ); class AnimatedSwitcherDemo extends StatefulWidget { const AnimatedSwitcherDemo({super.key}); static String routeName = 'misc/animated_switcher'; @override State<AnimatedSwitcherDemo> createState() => _AnimatedSwitcherDemoState(); } class _AnimatedSwitcherDemoState extends State<AnimatedSwitcherDemo> { late Widget container; late int keyCount; @override void initState() { super.initState(); keyCount = 0; container = generateContainer(keyCount); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('AnimatedSwitcher'), actions: [ TextButton( onPressed: () => setState( () => container = generateContainer(++keyCount), ), child: const Text('Change Widget'), ), ], ), body: Center( // AnimatedSwitcher Widget is used to switch between different widgets // with a given transition. You can change the transitions by using // transitionBuilder property. child: AnimatedSwitcher( duration: const Duration(seconds: 1), child: container, transitionBuilder: (child, animation) => ScaleTransition( scale: animation, child: child, ), ), ), ); } }
samples/animations/lib/src/misc/animated_switcher.dart/0
{ "file_path": "samples/animations/lib/src/misc/animated_switcher.dart", "repo_id": "samples", "token_count": 815 }
1,271
import 'package:flutter_test/flutter_test.dart'; import 'package:client/main.dart'; void main() { group('App should', () { testWidgets('build its widgets', (WidgetTester tester) async { await tester.pumpWidget( MyApp( getCount: () => Future.value(1), increment: (int x) => Future.value(x), ), ); }); }); }
samples/code_sharing/client/test/widget_test.dart/0
{ "file_path": "samples/code_sharing/client/test/widget_test.dart", "repo_id": "samples", "token_count": 162 }
1,272
import 'dart:convert'; import 'dart:io'; import 'package:shared/shared.dart'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart'; import 'package:shelf_router/shelf_router.dart'; int count = 0; // Configure routes. final _router = Router() ..post('/', _incrementHandler) ..get('/', _getValueHandler); Future<Response> _incrementHandler(Request request) async { final incr = Increment.fromJson(json.decode(await request.readAsString())); count += incr.by; return Response.ok(json.encode(Count(count).toJson())); } Response _getValueHandler(Request request) => Response.ok(json.encode(Count(count).toJson())); void main(List<String> args) async { // Use any available host or container IP (usually `0.0.0.0`). final ip = InternetAddress.anyIPv4; // Configure a pipeline that logs requests. final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router.call); // For running in containers, we respect the PORT environment variable. final port = int.parse(Platform.environment['PORT'] ?? '8080'); final server = await serve(handler, ip, port); print('Server listening on port ${server.port}'); }
samples/code_sharing/server/bin/server.dart/0
{ "file_path": "samples/code_sharing/server/bin/server.dart", "repo_id": "samples", "token_count": 390 }
1,273
include: package:analysis_defaults/flutter.yaml
samples/context_menus/analysis_options.yaml/0
{ "file_path": "samples/context_menus/analysis_options.yaml", "repo_id": "samples", "token_count": 15 }
1,274
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import 'constants.dart'; import 'platform_selector.dart'; class CustomButtonsPage extends StatelessWidget { CustomButtonsPage({ super.key, required this.onChangedPlatform, }); static const String route = 'custom-buttons'; static const String title = 'Custom Buttons'; static const String subtitle = 'The usual buttons, but with a custom appearance.'; final PlatformCallback onChangedPlatform; final TextEditingController _controller = TextEditingController( text: 'Show the menu to see the usual default buttons, but with a custom appearance.', ); static const String url = '$kCodeUrl/custom_buttons_page.dart'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(CustomButtonsPage.title), actions: <Widget>[ PlatformSelector( onChangedPlatform: onChangedPlatform, ), IconButton( icon: const Icon(Icons.code), onPressed: () async { if (!await launchUrl(Uri.parse(url))) { throw 'Could not launch $url'; } }, ), ], ), body: Center( child: SizedBox( width: 300.0, child: TextField( controller: _controller, maxLines: 4, minLines: 2, contextMenuBuilder: (context, editableTextState) { return AdaptiveTextSelectionToolbar( anchors: editableTextState.contextMenuAnchors, // Build the default buttons, but make them look custom. // Note that in a real project you may want to build // different buttons depending on the platform. children: editableTextState.contextMenuButtonItems.map((buttonItem) { return CupertinoButton( borderRadius: null, color: const Color(0xffaaaa00), disabledColor: const Color(0xffaaaaff), onPressed: buttonItem.onPressed, padding: const EdgeInsets.all(10.0), pressedOpacity: 0.7, child: SizedBox( width: 200.0, child: Text( CupertinoTextSelectionToolbarButton.getButtonLabel( context, buttonItem), ), ), ); }).toList(), ); }, ), ), ), ); } }
samples/context_menus/lib/custom_buttons_page.dart/0
{ "file_path": "samples/context_menus/lib/custom_buttons_page.dart", "repo_id": "samples", "token_count": 1339 }
1,275
import 'package:context_menus/image_page.dart'; import 'package:context_menus/main.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( 'Gives correct behavior for all values of contextMenuBuilder', (tester) async { await tester.pumpWidget(const MyApp()); // Navigate to the ImagePage example. await tester.dragUntilVisible( find.text(ImagePage.title), find.byType(ListView), const Offset(0.0, -100.0), ); await tester.pumpAndSettle(); await tester.tap(find.text(ImagePage.title)); await tester.pumpAndSettle(); expect( find.descendant( of: find.byType(AppBar), matching: find.text(ImagePage.title), ), findsOneWidget, ); // Right click on the FlutterLogo. TestGesture gesture = await tester.startGesture( tester.getCenter(find.byType(FlutterLogo)), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await gesture.removePointer(); await tester.pumpAndSettle(); // The default context menu is shown with a custom button. expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); expect(find.text('Save'), findsOneWidget); }, variant: TargetPlatformVariant.all(), ); }
samples/context_menus/test/image_page_test.dart/0
{ "file_path": "samples/context_menus/test/image_page_test.dart", "repo_id": "samples", "token_count": 608 }
1,276
// Copyright 2018 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; abstract class Styles { static const TextStyle productListTitle = TextStyle( color: Color.fromRGBO(0, 0, 0, 0.8), ); static const TextStyle productRowItemName = TextStyle( color: Color.fromRGBO(0, 0, 0, 0.8), fontSize: 18, fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, ); static const TextStyle productRowItemPrice = TextStyle( color: Color(0xFF8E8E93), fontSize: 13, fontWeight: FontWeight.w300, ); static const TextStyle productPageItemName = TextStyle( color: Color.fromRGBO(0, 0, 0, 0.8), fontSize: 20, fontStyle: FontStyle.normal, fontWeight: FontWeight.bold, ); static const TextStyle productPageItemPrice = TextStyle( color: Color.fromRGBO(0, 0, 0, 0.8), fontSize: 20, fontWeight: FontWeight.bold, ); static const Color productRowDivider = Color(0xFFD9D9D9); static const Color scaffoldBackground = Color(0xfff0f0f0); static const Color scaffoldAppBarBackground = Color(0xffffffff); static const Widget spacer = SizedBox(height: 10); static const Widget largeSpacer = SizedBox(height: 100); }
samples/deeplink_store_example/lib/styles.dart/0
{ "file_path": "samples/deeplink_store_example/lib/styles.dart", "repo_id": "samples", "token_count": 459 }
1,277
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // GENERATED CODE - DO NOT MODIFY BY HAND part of 'current_user_collections.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** Serializer<CurrentUserCollections> _$currentUserCollectionsSerializer = new _$CurrentUserCollectionsSerializer(); class _$CurrentUserCollectionsSerializer implements StructuredSerializer<CurrentUserCollections> { @override final Iterable<Type> types = const [ CurrentUserCollections, _$CurrentUserCollections ]; @override final String wireName = 'CurrentUserCollections'; @override Iterable<Object?> serialize( Serializers serializers, CurrentUserCollections object, {FullType specifiedType = FullType.unspecified}) { final result = <Object?>[ 'id', serializers.serialize(object.id, specifiedType: const FullType(int)), ]; Object? value; value = object.title; if (value != null) { result ..add('title') ..add(serializers.serialize(value, specifiedType: const FullType(String))); } value = object.publishedAt; if (value != null) { result ..add('published_at') ..add(serializers.serialize(value, specifiedType: const FullType(String))); } value = object.updatedAt; if (value != null) { result ..add('updated_at') ..add(serializers.serialize(value, specifiedType: const FullType(String))); } return result; } @override CurrentUserCollections deserialize( Serializers serializers, Iterable<Object?> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new CurrentUserCollectionsBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current! as String; iterator.moveNext(); final Object? value = iterator.current; switch (key) { case 'id': result.id = serializers.deserialize(value, specifiedType: const FullType(int))! as int; break; case 'title': result.title = serializers.deserialize(value, specifiedType: const FullType(String)) as String?; break; case 'published_at': result.publishedAt = serializers.deserialize(value, specifiedType: const FullType(String)) as String?; break; case 'updated_at': result.updatedAt = serializers.deserialize(value, specifiedType: const FullType(String)) as String?; break; } } return result.build(); } } class _$CurrentUserCollections extends CurrentUserCollections { @override final int id; @override final String? title; @override final String? publishedAt; @override final String? updatedAt; factory _$CurrentUserCollections( [void Function(CurrentUserCollectionsBuilder)? updates]) => (new CurrentUserCollectionsBuilder()..update(updates))._build(); _$CurrentUserCollections._( {required this.id, this.title, this.publishedAt, this.updatedAt}) : super._() { BuiltValueNullFieldError.checkNotNull(id, r'CurrentUserCollections', 'id'); } @override CurrentUserCollections rebuild( void Function(CurrentUserCollectionsBuilder) updates) => (toBuilder()..update(updates)).build(); @override CurrentUserCollectionsBuilder toBuilder() => new CurrentUserCollectionsBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is CurrentUserCollections && id == other.id && title == other.title && publishedAt == other.publishedAt && updatedAt == other.updatedAt; } @override int get hashCode { var _$hash = 0; _$hash = $jc(_$hash, id.hashCode); _$hash = $jc(_$hash, title.hashCode); _$hash = $jc(_$hash, publishedAt.hashCode); _$hash = $jc(_$hash, updatedAt.hashCode); _$hash = $jf(_$hash); return _$hash; } @override String toString() { return (newBuiltValueToStringHelper(r'CurrentUserCollections') ..add('id', id) ..add('title', title) ..add('publishedAt', publishedAt) ..add('updatedAt', updatedAt)) .toString(); } } class CurrentUserCollectionsBuilder implements Builder<CurrentUserCollections, CurrentUserCollectionsBuilder> { _$CurrentUserCollections? _$v; int? _id; int? get id => _$this._id; set id(int? id) => _$this._id = id; String? _title; String? get title => _$this._title; set title(String? title) => _$this._title = title; String? _publishedAt; String? get publishedAt => _$this._publishedAt; set publishedAt(String? publishedAt) => _$this._publishedAt = publishedAt; String? _updatedAt; String? get updatedAt => _$this._updatedAt; set updatedAt(String? updatedAt) => _$this._updatedAt = updatedAt; CurrentUserCollectionsBuilder(); CurrentUserCollectionsBuilder get _$this { final $v = _$v; if ($v != null) { _id = $v.id; _title = $v.title; _publishedAt = $v.publishedAt; _updatedAt = $v.updatedAt; _$v = null; } return this; } @override void replace(CurrentUserCollections other) { ArgumentError.checkNotNull(other, 'other'); _$v = other as _$CurrentUserCollections; } @override void update(void Function(CurrentUserCollectionsBuilder)? updates) { if (updates != null) updates(this); } @override CurrentUserCollections build() => _build(); _$CurrentUserCollections _build() { final _$result = _$v ?? new _$CurrentUserCollections._( id: BuiltValueNullFieldError.checkNotNull( id, r'CurrentUserCollections', 'id'), title: title, publishedAt: publishedAt, updatedAt: updatedAt); replace(_$result); return _$result; } } // ignore_for_file: deprecated_member_use_from_same_package,type=lint
samples/desktop_photo_search/fluent_ui/lib/src/unsplash/current_user_collections.g.dart/0
{ "file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/current_user_collections.g.dart", "repo_id": "samples", "token_count": 2346 }
1,278
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; import '../serializers.dart'; part 'urls.g.dart'; abstract class Urls implements Built<Urls, UrlsBuilder> { factory Urls([void Function(UrlsBuilder b)? updates]) = _$Urls; Urls._(); @BuiltValueField(wireName: 'raw') String? get raw; @BuiltValueField(wireName: 'full') String? get full; @BuiltValueField(wireName: 'regular') String? get regular; @BuiltValueField(wireName: 'small') String? get small; @BuiltValueField(wireName: 'thumb') String? get thumb; String toJson() { return json.encode(serializers.serializeWith(Urls.serializer, this)); } static Urls? fromJson(String jsonString) { return serializers.deserializeWith( Urls.serializer, json.decode(jsonString)); } static Serializer<Urls> get serializer => _$urlsSerializer; }
samples/desktop_photo_search/fluent_ui/lib/src/unsplash/urls.dart/0
{ "file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/urls.dart", "repo_id": "samples", "token_count": 364 }
1,279
# # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST file_selector_linux menubar url_launcher_linux window_size ) list(APPEND FLUTTER_FFI_PLUGIN_LIST ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin)
samples/desktop_photo_search/fluent_ui/linux/flutter/generated_plugins.cmake/0
{ "file_path": "samples/desktop_photo_search/fluent_ui/linux/flutter/generated_plugins.cmake", "repo_id": "samples", "token_count": 338 }
1,280
package dev.flutter.example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
samples/experimental/federated_plugin/federated_plugin/example/android/app/src/main/kotlin/dev/flutter/example/MainActivity.kt/0
{ "file_path": "samples/experimental/federated_plugin/federated_plugin/example/android/app/src/main/kotlin/dev/flutter/example/MainActivity.kt", "repo_id": "samples", "token_count": 37 }
1,281
// // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include <federated_plugin_windows/federated_plugin_windows_plugin.h> void RegisterPlugins(flutter::PluginRegistry* registry) { FederatedPluginWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("FederatedPluginWindowsPlugin")); }
samples/experimental/federated_plugin/federated_plugin/example/windows/flutter/generated_plugin_registrant.cc/0
{ "file_path": "samples/experimental/federated_plugin/federated_plugin/example/windows/flutter/generated_plugin_registrant.cc", "repo_id": "samples", "token_count": 118 }
1,282
// Copyright 2021 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:linting_tool/app.dart'; import 'package:linting_tool/model/profile.dart'; import 'package:linting_tool/model/rule.dart'; import 'package:window_size/window_size.dart'; Future<void> main() async { /// Initialize Hive DB. await Hive.initFlutter(); /// Register adapters for [Rule] and [RulesProfile] /// so that their objects can be directly saved to the DB. Hive.registerAdapter(RuleAdapter()); Hive.registerAdapter(RulesProfileAdapter()); /// Open a [LazyBox] to retrieve data from it await Hive.openLazyBox<RulesProfile>('rules_profile'); setWindowMinSize(const Size(600, 600)); runApp(const LintingTool()); }
samples/experimental/linting_tool/lib/main.dart/0
{ "file_path": "samples/experimental/linting_tool/lib/main.dart", "repo_id": "samples", "token_count": 280 }
1,283
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.flutter.pedometer"> </manifest>
samples/experimental/pedometer/android/src/main/AndroidManifest.xml/0
{ "file_path": "samples/experimental/pedometer/android/src/main/AndroidManifest.xml", "repo_id": "samples", "token_count": 43 }
1,284
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:fl_chart/fl_chart.dart'; import 'steps_repo.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const Home(), ); } } class RoundClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final diameter = size.shortestSide * 1.5; final x = -(diameter - size.width) / 2; final y = size.height - diameter; final rect = Offset(x, y) & Size(diameter, diameter); return Path()..addOval(rect); } @override bool shouldReclip(CustomClipper<Path> oldClipper) { return false; } } class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { var hourlySteps = <Steps>[]; DateTime? lastUpdated; @override void initState() { runPedometer(); super.initState(); } void runPedometer() async { final now = DateTime.now(); hourlySteps = await StepsRepo.instance.getSteps(); lastUpdated = now; setState(() {}); } @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final barGroups = hourlySteps .map( (e) => BarChartGroupData( x: int.parse(e.startHour), barRods: [ BarChartRodData( color: Colors.blue[900], toY: e.steps.toDouble() / 100, ) ], ), ) .toList(); return Scaffold( body: Stack( children: [ ClipPath( clipper: RoundClipper(), child: FractionallySizedBox( heightFactor: 0.55, widthFactor: 1, child: Container(color: Colors.blue[300]), ), ), Align( alignment: Alignment.topCenter, child: Padding( padding: const EdgeInsets.all(80.0), child: Column( children: [ lastUpdated != null ? Padding( padding: const EdgeInsets.symmetric(vertical: 50.0), child: Text( DateFormat.yMMMMd('en_US').format(lastUpdated!), style: textTheme.titleLarge! .copyWith(color: Colors.blue[900]), ), ) : const SizedBox(height: 0), Text( hourlySteps.fold(0, (t, e) => t + e.steps).toString(), style: textTheme.displayMedium!.copyWith(color: Colors.white), ), Text( 'steps', style: textTheme.titleLarge!.copyWith(color: Colors.white), ) ], ), ), ), Align( alignment: Alignment.centerRight, child: GestureDetector( onTap: runPedometer, child: Padding( padding: const EdgeInsets.all(20.0), child: Container( decoration: BoxDecoration( color: Colors.blue[900], shape: BoxShape.circle, ), child: const Padding( padding: EdgeInsets.all(8.0), child: Icon( Icons.refresh, color: Colors.white, size: 50, ), ), ), ), ), ), Align( alignment: Alignment.bottomCenter, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 50.0), child: AspectRatio( aspectRatio: 1.2, child: BarChart( BarChartData( titlesData: const FlTitlesData( show: true, // Top titles are null topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)), rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)), leftTitles: AxisTitles( sideTitles: SideTitles( showTitles: false, ), ), bottomTitles: AxisTitles( sideTitles: SideTitles( showTitles: true, reservedSize: 30, getTitlesWidget: getBottomTitles, ), ), ), borderData: FlBorderData( show: false, ), barGroups: barGroups, gridData: const FlGridData(show: false), alignment: BarChartAlignment.spaceAround, ), ), ), ), ), ], )); } } // Axis labels for bottom of chart Widget getBottomTitles(double value, TitleMeta meta) { String text; switch (value.toInt()) { case 0: text = '12AM'; break; case 6: text = '6AM'; break; case 12: text = '12PM'; break; case 18: text = '6PM'; break; default: text = ''; } return SideTitleWidget( axisSide: meta.axisSide, space: 4, child: Text(text, style: TextStyle(fontSize: 14, color: Colors.blue[900])), ); }
samples/experimental/pedometer/example/lib/main.dart/0
{ "file_path": "samples/experimental/pedometer/example/lib/main.dart", "repo_id": "samples", "token_count": 3211 }
1,285
/* * Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file * for details. All rights reserved. Use of this source code is governed by a * BSD-style license that can be found in the LICENSE file. */ #ifndef RUNTIME_INCLUDE_DART_VERSION_H_ #define RUNTIME_INCLUDE_DART_VERSION_H_ // On breaking changes the major version is increased. // On backwards compatible changes the minor version is increased. // The versioning covers the symbols exposed in dart_api_dl.h #define DART_API_DL_MAJOR_VERSION 2 #define DART_API_DL_MINOR_VERSION 0 #endif /* RUNTIME_INCLUDE_DART_VERSION_H_ */ /* NOLINT */
samples/experimental/pedometer/src/dart-sdk/include/dart_version.h/0
{ "file_path": "samples/experimental/pedometer/src/dart-sdk/include/dart_version.h", "repo_id": "samples", "token_count": 196 }
1,286
package com.example.varfont_shader_puzzle import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
samples/experimental/varfont_shader_puzzle/android/app/src/main/kotlin/com/example/varfont_shader_puzzle/MainActivity.kt/0
{ "file_path": "samples/experimental/varfont_shader_puzzle/android/app/src/main/kotlin/com/example/varfont_shader_puzzle/MainActivity.kt", "repo_id": "samples", "token_count": 43 }
1,287
// Copyright 2023 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:flutter/material.dart'; import '../components/components.dart'; import '../page_content/wallpapers_flow.dart'; import 'pages.dart'; class PagesFlow extends StatefulWidget { const PagesFlow({super.key}); static const pageScrollDuration = 400; @override State<PagesFlow> createState() => _PagesFlowState(); } class _PagesFlowState extends State<PagesFlow> { late PageController pageController = PageController(); @override Widget build(BuildContext context) { final double screenWidth = MediaQuery.of(context).size.width; final double screenHeight = MediaQuery.of(context).size.height; bool narrowView = screenWidth * 1.8 < screenHeight ? true : false; double puzzleSize = narrowView ? screenWidth * 1 : min(screenHeight * 0.6, screenWidth); double topBottomMargin = (screenHeight - puzzleSize) * 0.5; double wonkyCharLargeSize = topBottomMargin * 1.0; double wonkyCharSmallSize = wonkyCharLargeSize * 0.5; PageConfig pageConfig = PageConfig( screenWidth: screenWidth, screenHeight: screenHeight, narrowView: narrowView, puzzleSize: puzzleSize, pageController: pageController, wonkyCharLargeSize: wonkyCharLargeSize, wonkyCharSmallSize: wonkyCharSmallSize, ); return PageView( controller: pageController, physics: const NeverScrollableScrollPhysics(), scrollDirection: Axis.vertical, children: [ PageNarrativePre( pageConfig: pageConfig, ), PageWeight( pageConfig: pageConfig, ), PageAscenderDescender( pageConfig: pageConfig, ), PageOpticalSize( pageConfig: pageConfig, ), PageWidth( pageConfig: pageConfig, ), PageNarrativePost( pageConfig: pageConfig, ), const WallpapersFlow(), ], ); } } class PageConfig { final double screenWidth; final double screenHeight; final bool narrowView; final double puzzleSize; final PageController pageController; final double wonkyCharLargeSize; final double wonkyCharSmallSize; static double baseWeight = 800; const PageConfig({ Key? key, required this.screenWidth, required this.screenHeight, required this.narrowView, required this.puzzleSize, required this.pageController, required this.wonkyCharLargeSize, required this.wonkyCharSmallSize, }); } class SinglePage extends StatefulWidget { final PageConfig pageConfig; const SinglePage({ super.key, required this.pageConfig, }); @override State<SinglePage> createState() => SinglePageState(); } class SinglePageState extends State<SinglePage> with TickerProviderStateMixin { List<Widget> buildWonkyChars() { return <Widget>[]; } Widget createPuzzle() { return Container(); } Widget createTopicIntro() { return LightboxedPanel( pageConfig: widget.pageConfig, content: const [], ); } @override Widget build(BuildContext context) { List<Widget> c = []; c.add(createPuzzle()); c += buildWonkyChars(); c.add(createTopicIntro()); return Stack( children: c, ); } void puzzleDone() {} } class NarrativePage extends StatefulWidget { final PageConfig pageConfig; const NarrativePage({ super.key, required this.pageConfig, }); @override State<NarrativePage> createState() => NarrativePageState(); } class NarrativePageState extends State<NarrativePage> with TickerProviderStateMixin { int panelIndex = 0; List<LightboxedPanel> panels = []; void handleIntroDismiss() { Future.delayed(const Duration(milliseconds: 50), () { setState(() { if (panelIndex == panels.length - 1) { widget.pageConfig.pageController.nextPage( duration: const Duration(milliseconds: PagesFlow.pageScrollDuration), curve: Curves.easeOut, ); } else { panelIndex++; } }); }); } @override Widget build(BuildContext context) { switch (panelIndex) { default: return Container(); } } void puzzleDone() {} }
samples/experimental/varfont_shader_puzzle/lib/page_content/pages_flow.dart/0
{ "file_path": "samples/experimental/varfont_shader_puzzle/lib/page_content/pages_flow.dart", "repo_id": "samples", "token_count": 1624 }
1,288
// Application-level settings for the Runner target. // // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the // future. If not, the values below would default to using the project name when this becomes a // 'flutter create' template. // The application's name. By default this is also the title of the Flutter window. PRODUCT_NAME = varfont_shader_puzzle // The application's bundle identifier PRODUCT_BUNDLE_IDENTIFIER = com.example.varfontShaderPuzzle // The copyright displayed in application information PRODUCT_COPYRIGHT = Copyright © 2023 com.example. All rights reserved.
samples/experimental/varfont_shader_puzzle/macos/Runner/Configs/AppInfo.xcconfig/0
{ "file_path": "samples/experimental/varfont_shader_puzzle/macos/Runner/Configs/AppInfo.xcconfig", "repo_id": "samples", "token_count": 165 }
1,289
// Copyright 2023 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define PI 3.1415926538 uniform float uTime; uniform vec2 uSize; uniform float uDampener; out vec4 fragColor; uniform sampler2D uTexture; void main() { float piTime = uTime * PI * 2; vec2 texCoord = gl_FragCoord.xy / uSize.xy; float maxMag = 0.4; float minMag = 0.3; float numRings = 6.0; float ringVel = 4.0; float numPeakShifts = 8.0; float peakShiftVel = -3.0; float unitX = (texCoord.x - 0.5) * 2; float unitY = (texCoord.y - 0.5) * 2; float dist = distance(vec2(0, 0), vec2(unitX, unitY)); float theta = atan(unitY, unitX) + PI; // add PI for atan2 values -PI to PI float thisMag = (sin(theta * numRings - piTime * ringVel) + 1) * 0.5 * (cos(theta * numPeakShifts - piTime * peakShiftVel) + 1) * 0.5 * (maxMag - minMag) + minMag; float unitSrcDist = dist - dist * thisMag; float unitSrcX = cos(theta) * unitSrcDist; float unitSrcY = sin(theta) * unitSrcDist; float texSrcX = unitSrcX * 0.5 + 0.5; float texSrcY = unitSrcY * 0.5 + 0.5; fragColor = texture(uTexture, vec2(texSrcX, texSrcY)); }
samples/experimental/varfont_shader_puzzle/shaders/wavy_circ.frag/0
{ "file_path": "samples/experimental/varfont_shader_puzzle/shaders/wavy_circ.frag", "repo_id": "samples", "token_count": 490 }
1,290
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. abstract class Auth { Future<bool> get isSignedIn; Future<User> signIn(); Future signOut(); } abstract class User { String get uid; } class SignInException implements Exception {}
samples/experimental/web_dashboard/lib/src/auth/auth.dart/0
{ "file_path": "samples/experimental/web_dashboard/lib/src/auth/auth.dart", "repo_id": "samples", "token_count": 113 }
1,291
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:web_dashboard/src/api/api.dart'; import 'package:web_dashboard/src/utils/chart_utils.dart'; void main() { group('chart utils', () { test('totals entries by day', () async { var entries = [ Entry(10, DateTime(2020, 3, 1)), Entry(10, DateTime(2020, 3, 1)), Entry(10, DateTime(2020, 3, 2)), ]; var totals = entryTotalsByDay(entries, 2, today: DateTime(2020, 3, 2)); expect(totals, hasLength(3)); expect(totals[1].value, 20); expect(totals[2].value, 10); }); test('days', () async { expect( DateTime.utc(2020, 1, 3).difference(DateTime.utc(2020, 1, 2)).inDays, 1); }); }); }
samples/experimental/web_dashboard/test/chart_utils_test.dart/0
{ "file_path": "samples/experimental/web_dashboard/test/chart_utils_test.dart", "repo_id": "samples", "token_count": 395 }
1,292
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'sign_in_http.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** FormData _$FormDataFromJson(Map<String, dynamic> json) { return FormData( email: json['email'] as String?, password: json['password'] as String?, ); } Map<String, dynamic> _$FormDataToJson(FormData instance) => <String, dynamic>{ 'email': instance.email, 'password': instance.password, };
samples/form_app/lib/src/sign_in_http.g.dart/0
{ "file_path": "samples/form_app/lib/src/sign_in_http.g.dart", "repo_id": "samples", "token_count": 166 }
1,293
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
samples/form_app/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "samples/form_app/macos/Runner/Configs/Debug.xcconfig", "repo_id": "samples", "token_count": 32 }
1,294
{ "name": "form_app", "short_name": "form_app", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "A sample demonstrating different types of forms and best practices", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" }, { "src": "icons/Icon-maskable-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" }, { "src": "icons/Icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } ] }
samples/form_app/web/manifest.json/0
{ "file_path": "samples/form_app/web/manifest.json", "repo_id": "samples", "token_count": 520 }
1,295
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleDisplayName</key> <string>Game Template</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>game_template</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>$(FLUTTER_BUILD_NAME)</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>$(FLUTTER_BUILD_NUMBER)</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UIViewControllerBasedStatusBarAppearance</key> <false/> <!-- TODO: replace with an actual AdMob app ID Get it here: https://support.google.com/admob/answer/7356431 --> <key>GADApplicationIdentifier</key> <string>ca-app-pub-3940256099942544~1458002511</string> <key>CADisableMinimumFrameDurationOnPhone</key> <true/> <key>UIApplicationSupportsIndirectInputEvents</key> <true/> </dict> </plist>
samples/game_template/ios/Runner/Info.plist/0
{ "file_path": "samples/game_template/ios/Runner/Info.plist", "repo_id": "samples", "token_count": 761 }
1,296
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:logging/logging.dart'; import '../style/snack_bar.dart'; import 'ad_removal.dart'; /// Allows buying in-app. Facade of `package:in_app_purchase`. class InAppPurchaseController extends ChangeNotifier { static final Logger _log = Logger('InAppPurchases'); StreamSubscription<List<PurchaseDetails>>? _subscription; InAppPurchase inAppPurchaseInstance; AdRemovalPurchase _adRemoval = const AdRemovalPurchase.notStarted(); /// Creates a new [InAppPurchaseController] with an injected /// [InAppPurchase] instance. /// /// Example usage: /// /// var controller = InAppPurchaseController(InAppPurchase.instance); InAppPurchaseController(this.inAppPurchaseInstance); /// The current state of the ad removal purchase. AdRemovalPurchase get adRemoval => _adRemoval; /// Launches the platform UI for buying an in-app purchase. /// /// Currently, the only supported in-app purchase is ad removal. /// To support more, ad additional classes similar to [AdRemovalPurchase] /// and modify this method. Future<void> buy() async { if (!await inAppPurchaseInstance.isAvailable()) { _reportError('InAppPurchase.instance not available'); return; } _adRemoval = const AdRemovalPurchase.pending(); notifyListeners(); _log.info('Querying the store with queryProductDetails()'); final response = await inAppPurchaseInstance .queryProductDetails({AdRemovalPurchase.productId}); if (response.error != null) { _reportError('There was an error when making the purchase: ' '${response.error}'); return; } if (response.productDetails.length != 1) { _log.info( 'Products in response: ' '${response.productDetails.map((e) => '${e.id}: ${e.title}, ').join()}', ); _reportError('There was an error when making the purchase: ' 'product ${AdRemovalPurchase.productId} does not exist?'); return; } final productDetails = response.productDetails.single; _log.info('Making the purchase'); final purchaseParam = PurchaseParam(productDetails: productDetails); try { final success = await inAppPurchaseInstance.buyNonConsumable( purchaseParam: purchaseParam); _log.info('buyNonConsumable() request was sent with success: $success'); // The result of the purchase will be reported in the purchaseStream, // which is handled in [_listenToPurchaseUpdated]. } catch (e) { _log.severe( 'Problem with calling inAppPurchaseInstance.buyNonConsumable(): ' '$e'); } } @override void dispose() { _subscription?.cancel(); super.dispose(); } /// Asks the underlying platform to list purchases that have been already /// made (for example, in a previous session of the game). Future<void> restorePurchases() async { if (!await inAppPurchaseInstance.isAvailable()) { _reportError('InAppPurchase.instance not available'); return; } try { await inAppPurchaseInstance.restorePurchases(); } catch (e) { _log.severe('Could not restore in-app purchases: $e'); } _log.info('In-app purchases restored'); } /// Subscribes to the [inAppPurchaseInstance.purchaseStream]. void subscribe() { _subscription?.cancel(); _subscription = inAppPurchaseInstance.purchaseStream.listen((purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); }, onDone: () { _subscription?.cancel(); }, onError: (dynamic error) { _log.severe('Error occurred on the purchaseStream: $error'); }); } Future<void> _listenToPurchaseUpdated( List<PurchaseDetails> purchaseDetailsList) async { for (final purchaseDetails in purchaseDetailsList) { _log.info(() => 'New PurchaseDetails instance received: ' 'productID=${purchaseDetails.productID}, ' 'status=${purchaseDetails.status}, ' 'purchaseID=${purchaseDetails.purchaseID}, ' 'error=${purchaseDetails.error}, ' 'pendingCompletePurchase=${purchaseDetails.pendingCompletePurchase}'); if (purchaseDetails.productID != AdRemovalPurchase.productId) { _log.severe("The handling of the product with id " "'${purchaseDetails.productID}' is not implemented."); _adRemoval = const AdRemovalPurchase.notStarted(); notifyListeners(); continue; } switch (purchaseDetails.status) { case PurchaseStatus.pending: _adRemoval = const AdRemovalPurchase.pending(); notifyListeners(); case PurchaseStatus.purchased: case PurchaseStatus.restored: bool valid = await _verifyPurchase(purchaseDetails); if (valid) { _adRemoval = const AdRemovalPurchase.active(); if (purchaseDetails.status == PurchaseStatus.purchased) { showSnackBar('Thank you for your support!'); } notifyListeners(); } else { _log.severe('Purchase verification failed: $purchaseDetails'); _adRemoval = AdRemovalPurchase.error( StateError('Purchase could not be verified')); notifyListeners(); } case PurchaseStatus.error: _log.severe('Error with purchase: ${purchaseDetails.error}'); _adRemoval = AdRemovalPurchase.error(purchaseDetails.error!); notifyListeners(); case PurchaseStatus.canceled: _adRemoval = const AdRemovalPurchase.notStarted(); notifyListeners(); } if (purchaseDetails.pendingCompletePurchase) { // Confirm purchase back to the store. await inAppPurchaseInstance.completePurchase(purchaseDetails); } } } void _reportError(String message) { _log.severe(message); showSnackBar(message); _adRemoval = AdRemovalPurchase.error(message); notifyListeners(); } Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async { _log.info('Verifying purchase: ${purchaseDetails.verificationData}'); // TODO: verify the purchase. // See the info in [purchaseDetails.verificationData] to learn more. // There's also a codelab that explains purchase verification // on the backend: // https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#9 return true; } }
samples/game_template/lib/src/in_app_purchase/in_app_purchase.dart/0
{ "file_path": "samples/game_template/lib/src/in_app_purchase/in_app_purchase.dart", "repo_id": "samples", "token_count": 2418 }
1,297
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:logging/logging.dart'; CustomTransitionPage<T> buildMyTransition<T>({ required Widget child, required Color color, String? name, Object? arguments, String? restorationId, LocalKey? key, }) { return CustomTransitionPage<T>( child: child, transitionsBuilder: (context, animation, secondaryAnimation, child) { return _MyReveal( animation: animation, color: color, child: child, ); }, key: key, name: name, arguments: arguments, restorationId: restorationId, transitionDuration: const Duration(milliseconds: 700), ); } class _MyReveal extends StatefulWidget { final Widget child; final Animation<double> animation; final Color color; const _MyReveal({ required this.child, required this.animation, required this.color, }); @override State<_MyReveal> createState() => _MyRevealState(); } class _MyRevealState extends State<_MyReveal> { static final _log = Logger('_InkRevealState'); bool _finished = false; final _tween = Tween(begin: const Offset(0, -1), end: Offset.zero); @override void initState() { super.initState(); widget.animation.addStatusListener(_statusListener); } @override void didUpdateWidget(covariant _MyReveal oldWidget) { if (oldWidget.animation != widget.animation) { oldWidget.animation.removeStatusListener(_statusListener); widget.animation.addStatusListener(_statusListener); } super.didUpdateWidget(oldWidget); } @override void dispose() { widget.animation.removeStatusListener(_statusListener); super.dispose(); } @override Widget build(BuildContext context) { return Stack( fit: StackFit.expand, children: [ SlideTransition( position: _tween.animate( CurvedAnimation( parent: widget.animation, curve: Curves.easeOutCubic, reverseCurve: Curves.easeOutCubic, ), ), child: Container( color: widget.color, ), ), AnimatedOpacity( opacity: _finished ? 1 : 0, duration: const Duration(milliseconds: 300), child: widget.child, ), ], ); } void _statusListener(AnimationStatus status) { _log.fine(() => 'status: $status'); switch (status) { case AnimationStatus.completed: setState(() { _finished = true; }); case AnimationStatus.forward: case AnimationStatus.dismissed: case AnimationStatus.reverse: setState(() { _finished = false; }); } } }
samples/game_template/lib/src/style/my_transition.dart/0
{ "file_path": "samples/game_template/lib/src/style/my_transition.dart", "repo_id": "samples", "token_count": 1172 }
1,298
#import "GeneratedPluginRegistrant.h"
samples/infinite_list/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "samples/infinite_list/ios/Runner/Runner-Bridging-Header.h", "repo_id": "samples", "token_count": 13 }
1,299
// Copyright 2021 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:material_3_demo/main.dart' as app; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('verify app can run', (tester) async { app.main(); }); }
samples/material_3_demo/integration_test/integration_test.dart/0
{ "file_path": "samples/material_3_demo/integration_test/integration_test.dart", "repo_id": "samples", "token_count": 152 }
1,300
<!DOCTYPE html> <html> <head> <!-- If you are serving your web app in a path other than the root, change the href value below to reflect the base path you are serving from. The path provided below has to start and end with a slash "/" in order for it to work correctly. For more details: * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base This is a placeholder for base href that will be replaced by the value of the `--base-href` argument provided to `flutter build`. --> <base href="$FLUTTER_BASE_HREF"> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="material_3_demo"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png"/> <title>material_3_demo</title> <link rel="manifest" href="manifest.json"> <script> // The value below is injected by flutter build, do not touch. var serviceWorkerVersion = null; </script> <!-- This script adds the flutter initialization JS code --> <script src="flutter.js" defer></script> <script type="text/javascript" src="assets/packages/web_startup_analyzer/lib/web_startup_analyzer.js"></script> </head> <body> <script> var flutterWebStartupAnalyzer = new FlutterWebStartupAnalyzer(); var analyzer = flutterWebStartupAnalyzer; window.addEventListener('load', function(ev) { analyzer.markStart("loadEntrypoint"); _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, }, onEntrypointLoaded: function(engineInitializer) { analyzer.markFinished("loadEntrypoint"); analyzer.markStart("initializeEngine"); engineInitializer.initializeEngine().then(function(appRunner) { analyzer.markFinished("initializeEngine"); analyzer.markStart("appRunnerRunApp"); appRunner.runApp(); }); } }); }); </script> </body> </html>
samples/material_3_demo/web/index.html/0
{ "file_path": "samples/material_3_demo/web/index.html", "repo_id": "samples", "token_count": 797 }
1,301
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:url_launcher/link.dart'; import '../auth.dart'; class SettingsScreen extends StatefulWidget { const SettingsScreen({super.key}); @override State<SettingsScreen> createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> { @override Widget build(BuildContext context) => Scaffold( body: SafeArea( child: SingleChildScrollView( child: Align( alignment: Alignment.topCenter, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 400), child: const Card( child: Padding( padding: EdgeInsets.symmetric(vertical: 18, horizontal: 12), child: SettingsContent(), ), ), ), ), ), ), ); } class SettingsContent extends StatelessWidget { const SettingsContent({ super.key, }); @override Widget build(BuildContext context) => Column( children: [ ...[ Text( 'Settings', style: Theme.of(context).textTheme.headlineMedium, ), FilledButton( onPressed: () { BookstoreAuth.of(context).signOut(); }, child: const Text('Sign out'), ), const Text('Example using the Link widget:'), Link( uri: Uri.parse('/books/all/book/0'), builder: (context, followLink) => TextButton( onPressed: followLink, child: const Text('/books/all/book/0'), ), ), const Text('Example using GoRouter.of(context).go():'), TextButton( child: const Text('/books/all/book/0'), onPressed: () { GoRouter.of(context).go('/books/all/book/0'); }, ), ].map((w) => Padding(padding: const EdgeInsets.all(8), child: w)), const Text('Displays a dialog on the root Navigator:'), TextButton( onPressed: () => showDialog<String>( context: context, builder: (context) => AlertDialog( title: const Text('Alert!'), content: const Text('The alert description goes here.'), actions: [ TextButton( onPressed: () => Navigator.pop(context, 'Cancel'), child: const Text('Cancel'), ), TextButton( onPressed: () => Navigator.pop(context, 'OK'), child: const Text('OK'), ), ], ), ), child: const Text('Show Dialog'), ) ], ); }
samples/navigation_and_routing/lib/src/screens/settings.dart/0
{ "file_path": "samples/navigation_and_routing/lib/src/screens/settings.dart", "repo_id": "samples", "token_count": 1596 }
1,302
import UIKit import Flutter import GoogleMaps @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GMSServices.provideAPIKey("YOUR KEY HERE") GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
samples/place_tracker/ios/Runner/AppDelegate.swift/0
{ "file_path": "samples/place_tracker/ios/Runner/AppDelegate.swift", "repo_id": "samples", "token_count": 148 }
1,303
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:provider/provider.dart'; import 'place.dart'; import 'place_details.dart'; import 'place_list.dart'; import 'place_map.dart'; import 'stub_data.dart'; enum PlaceTrackerViewType { map, list, } class PlaceTrackerApp extends StatelessWidget { const PlaceTrackerApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( theme: ThemeData( colorSchemeSeed: Colors.green, appBarTheme: AppBarTheme( backgroundColor: Colors.green[700], foregroundColor: Colors.white, ), floatingActionButtonTheme: FloatingActionButtonThemeData( backgroundColor: Colors.green[700], foregroundColor: Colors.white, ), ), routerConfig: GoRouter(routes: [ GoRoute( path: '/', builder: (context, state) => const _PlaceTrackerHomePage(), routes: [ GoRoute( path: 'place/:id', builder: (context, state) { final id = state.pathParameters['id']!; final place = context .read<AppState>() .places .singleWhere((place) => place.id == id); return PlaceDetails(place: place); }, ), ], ), ]), ); } } class _PlaceTrackerHomePage extends StatelessWidget { const _PlaceTrackerHomePage(); @override Widget build(BuildContext context) { var state = Provider.of<AppState>(context); return Scaffold( appBar: AppBar( title: const Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: EdgeInsets.fromLTRB(0.0, 0.0, 8.0, 0.0), child: Icon(Icons.pin_drop, size: 24.0), ), Text('Place Tracker'), ], ), actions: [ Padding( padding: const EdgeInsets.fromLTRB(0.0, 0.0, 16.0, 0.0), child: IconButton( icon: Icon( state.viewType == PlaceTrackerViewType.map ? Icons.list : Icons.map, size: 32.0, ), onPressed: () { state.setViewType( state.viewType == PlaceTrackerViewType.map ? PlaceTrackerViewType.list : PlaceTrackerViewType.map, ); }, ), ), ], ), body: IndexedStack( index: state.viewType == PlaceTrackerViewType.map ? 0 : 1, children: const [ PlaceMap(center: LatLng(45.521563, -122.677433)), PlaceList() ], ), ); } } class AppState extends ChangeNotifier { AppState({ this.places = StubData.places, this.selectedCategory = PlaceCategory.favorite, this.viewType = PlaceTrackerViewType.map, }); List<Place> places; PlaceCategory selectedCategory; PlaceTrackerViewType viewType; void setViewType(PlaceTrackerViewType viewType) { this.viewType = viewType; notifyListeners(); } void setSelectedCategory(PlaceCategory newCategory) { selectedCategory = newCategory; notifyListeners(); } void setPlaces(List<Place> newPlaces) { places = newPlaces; notifyListeners(); } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is AppState && other.places == places && other.selectedCategory == selectedCategory && other.viewType == viewType; } @override int get hashCode => Object.hash(places, selectedCategory, viewType); }
samples/place_tracker/lib/place_tracker_app.dart/0
{ "file_path": "samples/place_tracker/lib/place_tracker_app.dart", "repo_id": "samples", "token_count": 1857 }
1,304
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:platform_channels/src/pet_list_message_channel.dart'; import 'package:platform_channels/src/pet_list_screen.dart'; void main() { group('PetListScreen tests', () { const basicMessageChannel = BasicMessageChannel<String?>('stringCodecDemo', StringCodec()); var petList = [ { 'petType': 'Dog', 'breed': 'Pug', } ]; PetListModel? petListModel; setUpAll(() { // Mock for the pet list received from the platform. TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler(basicMessageChannel, (message) async { petListModel = PetListModel.fromJson(message!); return null; }); // Mock for the index received from the Dart to delete the pet details, // and send the updated pet list back to Dart. TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler( const BasicMessageChannel<ByteData?>( 'binaryCodecDemo', BinaryCodec()), (message) async { // Convert the ByteData to String. final index = utf8.decoder.convert(message!.buffer .asUint8List(message.offsetInBytes, message.lengthInBytes)); // Remove the pet details at the given index. petList.removeAt(int.parse(index)); // Send the updated petList back. final map = {'petList': petList}; await basicMessageChannel.send(json.encode(map)); return null; }); }); test('convert json message to PetListModel', () { TestWidgetsFlutterBinding.ensureInitialized(); // Initially petListModel will be null. expect(petListModel, isNull); // Send the pet list using BasicMessageChannel. final map = {'petList': petList}; basicMessageChannel.send(json.encode(map)); // Get the details of first pet. final petDetails = petListModel!.petList.first; expect(petDetails.petType, 'Dog'); expect(petDetails.breed, 'Pug'); }); testWidgets('BuildPetList test', (tester) async { await tester.pumpWidget(MaterialApp( home: Scaffold( body: BuildPetList(petListModel!.petList), ), )); expect(find.text('Pet type: Dog'), findsOneWidget); expect(find.text('Pet breed: Pug'), findsOneWidget); // Delete the pet details. await tester.tap(find.byIcon(Icons.delete).first); expect(petListModel!.petList, isEmpty); }); }); }
samples/platform_channels/test/src/pet_list_screen_test.dart/0
{ "file_path": "samples/platform_channels/test/src/pet_list_screen_test.dart", "repo_id": "samples", "token_count": 1094 }
1,305
#import "GeneratedPluginRegistrant.h"
samples/platform_design/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "samples/platform_design/ios/Runner/Runner-Bridging-Header.h", "repo_id": "samples", "token_count": 13 }
1,306
// Copyright 2018, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate, PlatformViewControllerDelegate { var flutterResult: FlutterResult? override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) let controller: FlutterViewController = window?.rootViewController as! FlutterViewController let channel = FlutterMethodChannel.init(name: "dev.flutter.sample/platform_view_swift", binaryMessenger: controller.binaryMessenger) channel.setMethodCallHandler({ (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in if ("switchView" == call.method) { self.flutterResult = result let platformViewController = PlatformViewController(nibName: "PlatformViewController", bundle: nil) platformViewController.counter = call.arguments as! Int platformViewController.delegate = self let navigationController = UINavigationController(rootViewController: platformViewController) navigationController.navigationBar.topItem?.title = "Platform View" controller.present(navigationController, animated: true, completion: nil) } else { result(FlutterMethodNotImplemented) } }); return super.application(application, didFinishLaunchingWithOptions: launchOptions) } func didUpdateCounter(counter: Int) { flutterResult?(counter) } }
samples/platform_view_swift/ios/Runner/AppDelegate.swift/0
{ "file_path": "samples/platform_view_swift/ios/Runner/AppDelegate.swift", "repo_id": "samples", "token_count": 705 }
1,307
#import "GeneratedPluginRegistrant.h"
samples/provider_shopper/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "samples/provider_shopper/ios/Runner/Runner-Bridging-Header.h", "repo_id": "samples", "token_count": 13 }
1,308
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'package:provider_shopper/models/cart.dart'; import 'package:provider_shopper/models/catalog.dart'; import 'package:provider_shopper/screens/cart.dart'; CartModel? cartModel; CatalogModel? catalogModel; Widget createCartScreen() => MultiProvider( providers: [ Provider(create: (context) => CatalogModel()), ChangeNotifierProxyProvider<CatalogModel, CartModel>( create: (context) => CartModel(), update: (context, catalog, cart) { catalogModel = catalog; cartModel = cart; cart!.catalog = catalogModel!; return cart; }, ), ], child: const MaterialApp( home: MyCart(), ), ); void main() { group('CartScreen widget tests', () { testWidgets('Tapping BUY button displays snackbar.', (tester) async { await tester.pumpWidget(createCartScreen()); // Verify no snackbar initially exists. expect(find.byType(SnackBar), findsNothing); await tester.tap(find.text('BUY')); // Schedule animation. await tester.pump(); // Verifying the snackbar upon clicking the button. expect(find.byType(SnackBar), findsOneWidget); }); testWidgets('Testing when the cart contains items', (tester) async { await tester.pumpWidget(createCartScreen()); // Adding five items in the cart and testing. for (var i = 0; i < 5; i++) { var item = catalogModel!.getByPosition(i); cartModel!.add(item); await tester.pumpAndSettle(); expect(find.text(item.name), findsOneWidget); } // Testing total price of the five items. expect(find.text('\$${42 * 5}'), findsOneWidget); expect(find.byIcon(Icons.done), findsNWidgets(5)); }); }); }
samples/provider_shopper/test/cart_widget_test.dart/0
{ "file_path": "samples/provider_shopper/test/cart_widget_test.dart", "repo_id": "samples", "token_count": 805 }
1,309
include: package:analysis_defaults/flutter.yaml
samples/simple_shader/analysis_options.yaml/0
{ "file_path": "samples/simple_shader/analysis_options.yaml", "repo_id": "samples", "token_count": 15 }
1,310
# simplistic_calculator A calculator to demonstrate a hopefully simple start for a desktop Flutter app.
samples/simplistic_calculator/README.md/0
{ "file_path": "samples/simplistic_calculator/README.md", "repo_id": "samples", "token_count": 24 }
1,311
import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'app_state.dart'; import 'replacements.dart'; /// Signature for the callback that reports when the user changes the selection /// (including the cursor location). typedef SelectionChangedCallback = void Function( TextSelection selection, SelectionChangedCause? cause); /// Signature for a widget builder that builds a context menu for the given /// editable field. typedef BasicTextFieldContextMenuBuilder = Widget Function( BuildContext context, ClipboardStatus clipboardStatus, VoidCallback? onCopy, VoidCallback? onCut, VoidCallback? onPaste, VoidCallback? onSelectAll, VoidCallback? onLookUp, VoidCallback? onLiveTextInput, VoidCallback? onSearchWeb, VoidCallback? onShare, TextSelectionToolbarAnchors anchors, ); /// A basic text input client. An implementation of [DeltaTextInputClient] meant to /// send/receive information from the framework to the platform's text input plugin /// and vice-versa. class BasicTextInputClient extends StatefulWidget { const BasicTextInputClient({ super.key, required this.controller, required this.style, required this.focusNode, this.selectionControls, this.contextMenuBuilder, required this.onSelectionChanged, required this.showSelectionHandles, }); final TextEditingController controller; final TextStyle style; final FocusNode focusNode; final TextSelectionControls? selectionControls; final bool showSelectionHandles; final SelectionChangedCallback onSelectionChanged; final BasicTextFieldContextMenuBuilder? contextMenuBuilder; @override State<BasicTextInputClient> createState() => BasicTextInputClientState(); } class BasicTextInputClientState extends State<BasicTextInputClient> with TextSelectionDelegate, TextInputClient, DeltaTextInputClient { final GlobalKey _textKey = GlobalKey(); late AppStateWidgetState manager; final ClipboardStatusNotifier? _clipboardStatus = kIsWeb ? null : ClipboardStatusNotifier(); @override void initState() { super.initState(); _clipboardStatus?.addListener(_onChangedClipboardStatus); _liveTextInputStatus?.addListener(_onChangedLiveTextInputStatus); widget.focusNode.addListener(_handleFocusChanged); widget.controller.addListener(_didChangeTextEditingValue); } @override void didChangeDependencies() { super.didChangeDependencies(); manager = AppStateWidget.of(context); } @override void dispose() { widget.controller.removeListener(_didChangeTextEditingValue); widget.focusNode.removeListener(_handleFocusChanged); _liveTextInputStatus?.removeListener(_onChangedLiveTextInputStatus); _liveTextInputStatus?.dispose(); _clipboardStatus?.removeListener(_onChangedClipboardStatus); _clipboardStatus?.dispose(); super.dispose(); } /// [DeltaTextInputClient] method implementations. @override void connectionClosed() { if (_hasInputConnection) { _textInputConnection!.connectionClosedReceived(); _textInputConnection = null; _lastKnownRemoteTextEditingValue = null; widget.focusNode.unfocus(); widget.controller.clearComposing(); } } @override // Will not implement. AutofillScope? get currentAutofillScope => throw UnimplementedError(); @override TextEditingValue? get currentTextEditingValue => _value; @override void didChangeInputControl( TextInputControl? oldControl, TextInputControl? newControl) { if (_hasFocus && _hasInputConnection) { oldControl?.hide(); newControl?.show(); } } @override void insertTextPlaceholder(Size size) { // Will not implement. This method is used for Scribble support. } @override void performAction(TextInputAction action) { // Will not implement. } @override void performPrivateCommand(String action, Map<String, dynamic> data) { // Will not implement. } @override void performSelector(String selectorName) { final Intent? intent = intentForMacOSSelector(selectorName); if (intent != null) { final BuildContext? primaryContext = primaryFocus?.context; if (primaryContext != null) { Actions.invoke(primaryContext, intent); } } } @override void removeTextPlaceholder() { // Will not implement. This method is used for Scribble support. } @override void showAutocorrectionPromptRect(int start, int end) { // Will not implement. } @override bool showToolbar() { // On the web use provided native dom elements to provide clipboard functionality. if (kIsWeb) return false; if (_selectionOverlay == null || _selectionOverlay!.toolbarIsVisible) { return false; } _liveTextInputStatus?.update(); _selectionOverlay!.showToolbar(); return true; } @override void updateEditingValue(TextEditingValue value) {/* Not using */} @override void updateEditingValueWithDeltas(List<TextEditingDelta> textEditingDeltas) { TextEditingValue value = _value; for (final TextEditingDelta delta in textEditingDeltas) { value = delta.apply(value); } _lastKnownRemoteTextEditingValue = value; if (value == _value) { // This is possible, for example, when the numeric keyboard is input, // the engine will notify twice for the same value. // Track at https://github.com/flutter/flutter/issues/65811 return; } final bool selectionChanged = _value.selection.start != value.selection.start || _value.selection.end != value.selection.end; manager.updateTextEditingDeltaHistory(textEditingDeltas); _value = value; if (widget.controller is ReplacementTextEditingController) { for (final TextEditingDelta delta in textEditingDeltas) { (widget.controller as ReplacementTextEditingController) .syncReplacementRanges(delta); } } if (selectionChanged) { manager.updateToggleButtonsStateOnSelectionChanged(value.selection, widget.controller as ReplacementTextEditingController); } } @override void updateFloatingCursor(RawFloatingCursorPoint point) { // Will not implement. } /// Open/close [DeltaTextInputClient] TextInputConnection? _textInputConnection; bool get _hasInputConnection => _textInputConnection?.attached ?? false; TextEditingValue get _value => widget.controller.value; set _value(TextEditingValue value) { widget.controller.value = value; } // Keep track of the last known text editing value from the engine so we do not // send an update message if we don't have to. TextEditingValue? _lastKnownRemoteTextEditingValue; void _openInputConnection() { // Open an input connection if one does not already exist, as well as set // its style. If one is active then show it. if (!_hasInputConnection) { final TextEditingValue localValue = _value; _textInputConnection = TextInput.attach( this, const TextInputConfiguration( enableDeltaModel: true, inputAction: TextInputAction.newline, inputType: TextInputType.multiline, ), ); final TextStyle style = widget.style; _updateSizeAndTransform(); _schedulePeriodicPostFrameCallbacks(); _textInputConnection! ..setStyle( fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight, textDirection: _textDirection, // make this variable. textAlign: TextAlign.left, // make this variable. ) ..setEditingState(localValue) ..show(); _lastKnownRemoteTextEditingValue = localValue; } else { _textInputConnection!.show(); } } void _closeInputConnectionIfNeeded() { // Close input connection if one is active. if (_hasInputConnection) { _textInputConnection!.close(); _textInputConnection = null; _lastKnownRemoteTextEditingValue = null; } } void _openOrCloseInputConnectionIfNeeded() { // Open input connection on gaining focus. // Close input connection on focus loss. if (_hasFocus && widget.focusNode.consumeKeyboardToken()) { _openInputConnection(); } else if (!_hasFocus) { _closeInputConnectionIfNeeded(); widget.controller.clearComposing(); } } /// Field focus + keyboard request. bool get _hasFocus => widget.focusNode.hasFocus; void requestKeyboard() { if (_hasFocus) { _openInputConnection(); } else { widget.focusNode.requestFocus(); } } void _handleFocusChanged() { // Open or close input connection depending on focus. _openOrCloseInputConnectionIfNeeded(); if (_hasFocus) { if (!_value.selection.isValid) { // Place cursor at the end if the selection is invalid when we receive focus. final TextSelection validSelection = TextSelection.collapsed(offset: _value.text.length); _handleSelectionChanged(validSelection, null); manager.updateToggleButtonsStateOnSelectionChanged(validSelection, widget.controller as ReplacementTextEditingController); } } } /// Misc. TextDirection get _textDirection => Directionality.of(context); TextSpan _buildTextSpan() { return widget.controller.buildTextSpan( context: context, style: widget.style, withComposing: true, ); } void _onChangedClipboardStatus() { setState(() { // Inform the widget that the value of clipboardStatus has changed. }); } // These actions have yet to be implemented for this sample. static final Map<Type, Action<Intent>> _unsupportedActions = <Type, Action<Intent>>{ DeleteToNextWordBoundaryIntent: DoNothingAction(consumesKey: false), DeleteToLineBreakIntent: DoNothingAction(consumesKey: false), ExtendSelectionToNextWordBoundaryIntent: DoNothingAction(consumesKey: false), ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent: DoNothingAction(consumesKey: false), ExtendSelectionToLineBreakIntent: DoNothingAction(consumesKey: false), ExtendSelectionVerticallyToAdjacentLineIntent: DoNothingAction(consumesKey: false), ExtendSelectionVerticallyToAdjacentPageIntent: DoNothingAction(consumesKey: false), ExtendSelectionToNextParagraphBoundaryIntent: DoNothingAction(consumesKey: false), ExtendSelectionToDocumentBoundaryIntent: DoNothingAction(consumesKey: false), ExtendSelectionByPageIntent: DoNothingAction(consumesKey: false), ExpandSelectionToDocumentBoundaryIntent: DoNothingAction(consumesKey: false), ExpandSelectionToLineBreakIntent: DoNothingAction(consumesKey: false), ScrollToDocumentBoundaryIntent: DoNothingAction(consumesKey: false), RedoTextIntent: DoNothingAction(consumesKey: false), ReplaceTextIntent: DoNothingAction(consumesKey: false), UndoTextIntent: DoNothingAction(consumesKey: false), UpdateSelectionIntent: DoNothingAction(consumesKey: false), TransposeCharactersIntent: DoNothingAction(consumesKey: false), }; /// Keyboard text editing actions. // The Handling of the default text editing shortcuts with deltas // needs to be in the framework somehow. This should go through some kind of // generic "replace" method like in EditableText. // EditableText converts intents like DeleteCharacterIntent to a generic // ReplaceTextIntent. I wonder if that could be done at a higher level, so // that users could listen to that instead of DeleteCharacterIntent? TextSelection get _selection => _value.selection; late final Map<Type, Action<Intent>> _actions = <Type, Action<Intent>>{ DeleteCharacterIntent: CallbackAction<DeleteCharacterIntent>( onInvoke: (intent) => _delete(intent.forward), ), ExtendSelectionByCharacterIntent: CallbackAction<ExtendSelectionByCharacterIntent>( onInvoke: (intent) => _extendSelection(intent.forward, intent.collapseSelection), ), SelectAllTextIntent: CallbackAction<SelectAllTextIntent>( onInvoke: (intent) => selectAll(intent.cause), ), CopySelectionTextIntent: CallbackAction<CopySelectionTextIntent>( onInvoke: (intent) => copySelection(intent.cause), ), PasteTextIntent: CallbackAction<PasteTextIntent>( onInvoke: (intent) => pasteText(intent.cause), ), DoNothingAndStopPropagationTextIntent: DoNothingAction( consumesKey: false, ), ..._unsupportedActions, }; void _delete(bool forward) { if (_value.text.isEmpty) return; late final TextRange deletedRange; late final TextRange newComposing; late final String deletedText; final int offset = _selection.baseOffset; if (_selection.isCollapsed) { if (forward) { if (_selection.baseOffset == _value.text.length) return; deletedText = _value.text.substring(offset).characters.first; deletedRange = TextRange( start: offset, end: offset + deletedText.length, ); } else { if (_selection.baseOffset == 0) return; deletedText = _value.text.substring(0, offset).characters.last; deletedRange = TextRange( start: offset - deletedText.length, end: offset, ); } } else { deletedRange = _selection; } final bool isComposing = _selection.isCollapsed && _value.isComposingRangeValid; if (isComposing) { newComposing = TextRange.collapsed(deletedRange.start); } else { newComposing = TextRange.empty; } _userUpdateTextEditingValueWithDelta( TextEditingDeltaDeletion( oldText: _value.text, selection: TextSelection.collapsed(offset: deletedRange.start), composing: newComposing, deletedRange: deletedRange, ), SelectionChangedCause.keyboard, ); } void _extendSelection(bool forward, bool collapseSelection) { late final TextSelection selection; if (collapseSelection) { if (!_selection.isCollapsed) { final int firstOffset = _selection.isNormalized ? _selection.start : _selection.end; final int lastOffset = _selection.isNormalized ? _selection.end : _selection.start; selection = TextSelection.collapsed(offset: forward ? lastOffset : firstOffset); } else { if (forward && _selection.baseOffset == _value.text.length) return; if (!forward && _selection.baseOffset == 0) return; final int adjustment = forward ? _value.text .substring(_selection.baseOffset) .characters .first .length : -_value.text .substring(0, _selection.baseOffset) .characters .last .length; selection = TextSelection.collapsed( offset: _selection.baseOffset + adjustment, ); } } else { if (forward && _selection.extentOffset == _value.text.length) return; if (!forward && _selection.extentOffset == 0) return; final int adjustment = forward ? _value.text.substring(_selection.baseOffset).characters.first.length : -_value.text .substring(0, _selection.baseOffset) .characters .last .length; selection = TextSelection( baseOffset: _selection.baseOffset, extentOffset: _selection.extentOffset + adjustment, ); } _userUpdateTextEditingValueWithDelta( TextEditingDeltaNonTextUpdate( oldText: _value.text, selection: selection, composing: _value.composing, ), SelectionChangedCause.keyboard, ); } void _userUpdateTextEditingValueWithDelta( TextEditingDelta textEditingDelta, SelectionChangedCause cause) { TextEditingValue value = _value; value = textEditingDelta.apply(value); if (widget.controller is ReplacementTextEditingController) { (widget.controller as ReplacementTextEditingController) .syncReplacementRanges(textEditingDelta); } if (value != _value) { manager.updateTextEditingDeltaHistory([textEditingDelta]); } userUpdateTextEditingValue(value, cause); } /// For updates to text editing value. void _didChangeTextEditingValue() { _updateRemoteTextEditingValueIfNeeded(); _updateOrDisposeOfSelectionOverlayIfNeeded(); setState(() {}); } // Only update the platform's text input plugin's text editing value when it has changed // to avoid sending duplicate update messages to the engine. void _updateRemoteTextEditingValueIfNeeded() { if (_lastKnownRemoteTextEditingValue == _value) return; if (_textInputConnection != null) { _textInputConnection!.setEditingState(_value); _lastKnownRemoteTextEditingValue = _value; } } /// For correctly positioning the candidate menu on macOS. // Sends the current composing rect to the iOS text input plugin via the text // input channel. We need to keep sending the information even if no text is // currently marked, as the information usually lags behind. The text input // plugin needs to estimate the composing rect based on the latest caret rect, // when the composing rect info didn't arrive in time. void _updateComposingRectIfNeeded() { final TextRange composingRange = _value.composing; assert(mounted); Rect? composingRect = renderEditable.getRectForComposingRange(composingRange); // Send the caret location instead if there's no marked text yet. if (composingRect == null) { assert(!composingRange.isValid || composingRange.isCollapsed); final int offset = composingRange.isValid ? composingRange.start : 0; composingRect = renderEditable.getLocalRectForCaret(TextPosition(offset: offset)); } _textInputConnection!.setComposingRect(composingRect); } void _updateCaretRectIfNeeded() { final TextSelection? selection = renderEditable.selection; if (selection == null || !selection.isValid || !selection.isCollapsed) { return; } final TextPosition currentTextPosition = TextPosition(offset: selection.baseOffset); final Rect caretRect = renderEditable.getLocalRectForCaret(currentTextPosition); _textInputConnection!.setCaretRect(caretRect); } void _updateSizeAndTransform() { final Size size = renderEditable.size; final Matrix4 transform = renderEditable.getTransformTo(null); _textInputConnection!.setEditableSizeAndTransform(size, transform); } void _schedulePeriodicPostFrameCallbacks([Duration? duration]) { if (!_hasInputConnection) { return; } _updateComposingRectIfNeeded(); _updateCaretRectIfNeeded(); SchedulerBinding.instance .addPostFrameCallback(_schedulePeriodicPostFrameCallbacks); } /// [TextSelectionDelegate] method implementations. @override void bringIntoView(TextPosition position) { // Not implemented. } @override bool get cutEnabled => !textEditingValue.selection.isCollapsed; @override bool get copyEnabled => !textEditingValue.selection.isCollapsed; @override bool get pasteEnabled => _clipboardStatus == null || _clipboardStatus.value == ClipboardStatus.pasteable; @override bool get selectAllEnabled => textEditingValue.text.isNotEmpty; @override void copySelection(SelectionChangedCause cause) { final TextSelection copyRange = textEditingValue.selection; if (!copyRange.isValid || copyRange.isCollapsed) return; final String text = textEditingValue.text; Clipboard.setData(ClipboardData(text: copyRange.textInside(text))); // If copy was done by the text selection toolbar we should hide the toolbar and set the selection // to the end of the copied text. if (cause == SelectionChangedCause.toolbar) { switch (defaultTargetPlatform) { case TargetPlatform.iOS: break; case TargetPlatform.macOS: case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: _userUpdateTextEditingValueWithDelta( TextEditingDeltaNonTextUpdate( oldText: textEditingValue.text, selection: TextSelection.collapsed( offset: textEditingValue.selection.end), composing: TextRange.empty, ), cause, ); } hideToolbar(); } _clipboardStatus?.update(); } @override void cutSelection(SelectionChangedCause cause) { final TextSelection cutRange = textEditingValue.selection; final String text = textEditingValue.text; if (cutRange.isCollapsed) return; Clipboard.setData(ClipboardData(text: cutRange.textInside(text))); final int lastSelectionIndex = math.min(cutRange.baseOffset, cutRange.extentOffset); _userUpdateTextEditingValueWithDelta( TextEditingDeltaReplacement( oldText: textEditingValue.text, replacementText: '', replacedRange: cutRange, selection: TextSelection.collapsed(offset: lastSelectionIndex), composing: TextRange.empty, ), cause, ); if (cause == SelectionChangedCause.toolbar) hideToolbar(); _clipboardStatus?.update(); } @override Future<void> pasteText(SelectionChangedCause cause) async { final TextSelection pasteRange = textEditingValue.selection; if (!pasteRange.isValid) return; final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain); if (data == null) return; // After the paste, the cursor should be collapsed and located after the // pasted content. final int lastSelectionIndex = math.max( pasteRange.baseOffset, pasteRange.baseOffset + data.text!.length); _userUpdateTextEditingValueWithDelta( TextEditingDeltaReplacement( oldText: textEditingValue.text, replacementText: data.text!, replacedRange: pasteRange, selection: TextSelection.collapsed(offset: lastSelectionIndex), composing: TextRange.empty, ), cause, ); if (cause == SelectionChangedCause.toolbar) hideToolbar(); } @override void selectAll(SelectionChangedCause cause) { final TextSelection newSelection = _value.selection .copyWith(baseOffset: 0, extentOffset: _value.text.length); _userUpdateTextEditingValueWithDelta( TextEditingDeltaNonTextUpdate( oldText: textEditingValue.text, selection: newSelection, composing: TextRange.empty, ), cause, ); if (cause == SelectionChangedCause.toolbar) { switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: break; case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: hideToolbar(); } } } @override TextEditingValue get textEditingValue => _value; @override void userUpdateTextEditingValue( TextEditingValue value, SelectionChangedCause cause) { if (value == _value) return; final bool selectionChanged = _value.selection != value.selection; if (cause == SelectionChangedCause.drag || cause == SelectionChangedCause.longPress || cause == SelectionChangedCause.tap) { // Here the change is coming from gestures which call on RenderEditable to change the selection. // Create a TextEditingDeltaNonTextUpdate so we can keep track of the delta history. RenderEditable // does not report a delta on selection change. final bool textChanged = _value.text != value.text; if (selectionChanged && !textChanged) { final TextEditingDeltaNonTextUpdate selectionUpdate = TextEditingDeltaNonTextUpdate( oldText: value.text, selection: value.selection, composing: value.composing, ); if (widget.controller is ReplacementTextEditingController) { (widget.controller as ReplacementTextEditingController) .syncReplacementRanges(selectionUpdate); } manager.updateTextEditingDeltaHistory([selectionUpdate]); } } final bool selectionRangeChanged = _value.selection.start != value.selection.start || _value.selection.end != value.selection.end; _value = value; if (selectionChanged) { _handleSelectionChanged(_value.selection, cause); if (selectionRangeChanged) { manager.updateToggleButtonsStateOnSelectionChanged(_value.selection, widget.controller as ReplacementTextEditingController); } } } @override void hideToolbar([bool hideHandles = true]) { if (hideHandles) { // Hide the handles and the toolbar. _selectionOverlay?.hide(); } else if (_selectionOverlay?.toolbarIsVisible ?? false) { // Hide only the toolbar but not the handles. _selectionOverlay?.hideToolbar(); } } /// For TextSelection. final LayerLink _startHandleLayerLink = LayerLink(); final LayerLink _endHandleLayerLink = LayerLink(); final LayerLink _toolbarLayerLink = LayerLink(); TextSelectionOverlay? _selectionOverlay; RenderEditable get renderEditable => _textKey.currentContext!.findRenderObject()! as RenderEditable; void _handleSelectionChanged( TextSelection selection, SelectionChangedCause? cause) { // We return early if the selection is not valid. This can happen when the // text of the editable is updated at the same time as the selection is // changed by a gesture event. if (!widget.controller.isSelectionWithinTextBounds(selection)) return; widget.controller.selection = selection; // This will show the keyboard for all selection changes on the // editable except for those triggered by a keyboard input. // Typically BasicTextInputClient shouldn't take user keyboard input if // it's not focused already. switch (cause) { case null: case SelectionChangedCause.doubleTap: case SelectionChangedCause.drag: case SelectionChangedCause.forcePress: case SelectionChangedCause.longPress: case SelectionChangedCause.scribble: case SelectionChangedCause.tap: case SelectionChangedCause.toolbar: requestKeyboard(); case SelectionChangedCause.keyboard: if (_hasFocus) { requestKeyboard(); } } if (widget.selectionControls == null && widget.contextMenuBuilder == null) { _selectionOverlay?.dispose(); _selectionOverlay = null; } else { if (_selectionOverlay == null) { _selectionOverlay = _createSelectionOverlay(); } else { _selectionOverlay!.update(_value); } _selectionOverlay!.handlesVisible = widget.showSelectionHandles; _selectionOverlay!.showHandles(); } try { widget.onSelectionChanged.call(selection, cause); } catch (exception, stack) { FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'widgets', context: ErrorDescription('while calling onSelectionChanged for $cause'), )); } } TextSelectionOverlay _createSelectionOverlay() { final TextSelectionOverlay selectionOverlay = TextSelectionOverlay( clipboardStatus: _clipboardStatus, context: context, value: _value, debugRequiredFor: widget, toolbarLayerLink: _toolbarLayerLink, startHandleLayerLink: _startHandleLayerLink, endHandleLayerLink: _endHandleLayerLink, renderObject: renderEditable, selectionControls: widget.selectionControls, selectionDelegate: this, dragStartBehavior: DragStartBehavior.start, onSelectionHandleTapped: () { _toggleToolbar(); }, contextMenuBuilder: widget.contextMenuBuilder == null || kIsWeb ? null : (context) { return widget.contextMenuBuilder!( context, _clipboardStatus!.value, copyEnabled ? () => copySelection(SelectionChangedCause.toolbar) : null, cutEnabled ? () => cutSelection(SelectionChangedCause.toolbar) : null, pasteEnabled ? () => pasteText(SelectionChangedCause.toolbar) : null, selectAllEnabled ? () => selectAll(SelectionChangedCause.toolbar) : null, lookUpEnabled ? () => _lookUpSelection(SelectionChangedCause.toolbar) : null, liveTextInputEnabled ? () => _startLiveTextInput(SelectionChangedCause.toolbar) : null, searchWebEnabled ? () => _searchWebForSelection(SelectionChangedCause.toolbar) : null, shareEnabled ? () => _shareSelection(SelectionChangedCause.toolbar) : null, _contextMenuAnchors, ); }, magnifierConfiguration: TextMagnifierConfiguration.disabled, ); return selectionOverlay; } void _toggleToolbar() { final TextSelectionOverlay selectionOverlay = _selectionOverlay ??= _createSelectionOverlay(); if (selectionOverlay.toolbarIsVisible) { hideToolbar(false); } else { showToolbar(); } } // When the framework's text editing value changes we should update the text editing // value contained within the selection overlay or we might observe unexpected behavior. void _updateOrDisposeOfSelectionOverlayIfNeeded() { if (_selectionOverlay != null) { if (_hasFocus) { _selectionOverlay!.update(_value); } else { _selectionOverlay!.dispose(); _selectionOverlay = null; } } } /// Gets the line heights at the start and end of the selection for the given /// editable. _GlyphHeights _getGlyphHeights() { final TextSelection selection = textEditingValue.selection; // Only calculate handle rects if the text in the previous frame // is the same as the text in the current frame. This is done because // widget.renderObject contains the renderEditable from the previous frame. // If the text changed between the current and previous frames then // widget.renderObject.getRectForComposingRange might fail. In cases where // the current frame is different from the previous we fall back to // renderObject.preferredLineHeight. final InlineSpan span = renderEditable.text!; final String prevText = span.toPlainText(); final String currText = textEditingValue.text; if (prevText != currText || !selection.isValid || selection.isCollapsed) { return _GlyphHeights( start: renderEditable.preferredLineHeight, end: renderEditable.preferredLineHeight, ); } final String selectedGraphemes = selection.textInside(currText); final int firstSelectedGraphemeExtent = selectedGraphemes.characters.first.length; final Rect? startCharacterRect = renderEditable.getRectForComposingRange(TextRange( start: selection.start, end: selection.start + firstSelectedGraphemeExtent, )); final int lastSelectedGraphemeExtent = selectedGraphemes.characters.last.length; final Rect? endCharacterRect = renderEditable.getRectForComposingRange(TextRange( start: selection.end - lastSelectedGraphemeExtent, end: selection.end, )); return _GlyphHeights( start: startCharacterRect?.height ?? renderEditable.preferredLineHeight, end: endCharacterRect?.height ?? renderEditable.preferredLineHeight, ); } /// Returns the anchor points for the default context menu. TextSelectionToolbarAnchors get _contextMenuAnchors { if (renderEditable.lastSecondaryTapDownPosition != null) { return TextSelectionToolbarAnchors( primaryAnchor: renderEditable.lastSecondaryTapDownPosition!, ); } final _GlyphHeights glyphHeights = _getGlyphHeights(); final TextSelection selection = textEditingValue.selection; final List<TextSelectionPoint> points = renderEditable.getEndpointsForSelection(selection); return TextSelectionToolbarAnchors.fromSelection( renderBox: renderEditable, startGlyphHeight: glyphHeights.start, endGlyphHeight: glyphHeights.end, selectionEndpoints: points, ); } /// For OCR Support. /// Detects whether the Live Text input is enabled. final LiveTextInputStatusNotifier? _liveTextInputStatus = kIsWeb ? null : LiveTextInputStatusNotifier(); @override bool get liveTextInputEnabled { return _liveTextInputStatus?.value == LiveTextInputStatus.enabled && textEditingValue.selection.isCollapsed; } void _onChangedLiveTextInputStatus() { setState(() { // Inform the widget that the value of liveTextInputStatus has changed. }); } void _startLiveTextInput(SelectionChangedCause cause) { if (!liveTextInputEnabled) { return; } if (_hasInputConnection) { LiveText.startLiveTextInput(); } if (cause == SelectionChangedCause.toolbar) { hideToolbar(); } } /// For lookup support. @override bool get lookUpEnabled { if (defaultTargetPlatform != TargetPlatform.iOS) { return false; } return !textEditingValue.selection.isCollapsed; } /// Look up the current selection, as in the "Look Up" edit menu button on iOS. /// Currently this is only implemented for iOS. /// Throws an error if the selection is empty or collapsed. Future<void> _lookUpSelection(SelectionChangedCause cause) async { final String text = textEditingValue.selection.textInside(textEditingValue.text); if (text.isEmpty) { return; } await SystemChannels.platform.invokeMethod( 'LookUp.invoke', text, ); } @override bool get searchWebEnabled { if (defaultTargetPlatform != TargetPlatform.iOS) { return false; } return !textEditingValue.selection.isCollapsed && textEditingValue.selection.textInside(textEditingValue.text).trim() != ''; } /// Launch a web search on the current selection, /// as in the "Search Web" edit menu button on iOS. /// /// Currently this is only implemented for iOS. Future<void> _searchWebForSelection(SelectionChangedCause cause) async { final String text = textEditingValue.selection.textInside(textEditingValue.text); if (text.isNotEmpty) { await SystemChannels.platform.invokeMethod( 'SearchWeb.invoke', text, ); } } @override bool get shareEnabled { switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.iOS: return !textEditingValue.selection.isCollapsed && textEditingValue.selection .textInside(textEditingValue.text) .trim() != ''; case TargetPlatform.macOS: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: return false; } } /// Launch the share interface for the current selection, /// as in the "Share..." edit menu button on iOS. /// /// Currently this is only implemented for iOS and Android. Future<void> _shareSelection(SelectionChangedCause cause) async { final String text = textEditingValue.selection.textInside(textEditingValue.text); if (text.isNotEmpty) { await SystemChannels.platform.invokeMethod( 'Share.invoke', text, ); } } @override Widget build(BuildContext context) { return Actions( actions: _actions, child: Focus( focusNode: widget.focusNode, child: Scrollable( viewportBuilder: (context, position) { return CompositedTransformTarget( link: _toolbarLayerLink, child: _Editable( key: _textKey, startHandleLayerLink: _startHandleLayerLink, endHandleLayerLink: _endHandleLayerLink, inlineSpan: _buildTextSpan(), value: _value, // We pass value.selection to RenderEditable. cursorColor: Colors.blue, backgroundCursorColor: Colors.grey[100], showCursor: ValueNotifier<bool>(_hasFocus), forceLine: true, // Whether text field will take full line regardless of width. readOnly: false, // editable text-field. hasFocus: _hasFocus, maxLines: null, // multi-line text-field. minLines: null, expands: false, // expands to height of parent. strutStyle: null, selectionColor: Colors.blue.withOpacity(0.40), textScaler: MediaQuery.textScalerOf(context), textAlign: TextAlign.left, textDirection: _textDirection, locale: Localizations.maybeLocaleOf(context), textHeightBehavior: DefaultTextHeightBehavior.maybeOf(context), textWidthBasis: TextWidthBasis.parent, obscuringCharacter: '•', obscureText: false, // This is a non-private text field that does not require obfuscation. offset: position, rendererIgnoresPointer: true, cursorWidth: 2.0, cursorHeight: null, cursorRadius: const Radius.circular(2.0), cursorOffset: Offset.zero, paintCursorAboveText: false, enableInteractiveSelection: true, // make true to enable selection on mobile. textSelectionDelegate: this, devicePixelRatio: MediaQuery.of(context).devicePixelRatio, promptRectRange: null, promptRectColor: null, clipBehavior: Clip.hardEdge, ), ); }, ), ), ); } } class _Editable extends MultiChildRenderObjectWidget { _Editable({ super.key, required this.inlineSpan, required this.value, required this.startHandleLayerLink, required this.endHandleLayerLink, this.cursorColor, this.backgroundCursorColor, required this.showCursor, required this.forceLine, required this.readOnly, this.textHeightBehavior, required this.textWidthBasis, required this.hasFocus, required this.maxLines, this.minLines, required this.expands, this.strutStyle, this.selectionColor, required this.textScaler, required this.textAlign, required this.textDirection, this.locale, required this.obscuringCharacter, required this.obscureText, required this.offset, this.rendererIgnoresPointer = false, required this.cursorWidth, this.cursorHeight, this.cursorRadius, required this.cursorOffset, required this.paintCursorAboveText, this.enableInteractiveSelection = true, required this.textSelectionDelegate, required this.devicePixelRatio, this.promptRectRange, this.promptRectColor, required this.clipBehavior, }) : super(children: _extractChildren(inlineSpan)); // Traverses the InlineSpan tree and depth-first collects the list of // child widgets that are created in WidgetSpans. static List<Widget> _extractChildren(InlineSpan span) { final List<Widget> result = <Widget>[]; span.visitChildren((span) { if (span is WidgetSpan) { result.add(span.child); } return true; }); return result; } final InlineSpan inlineSpan; final TextEditingValue value; final Color? cursorColor; final LayerLink startHandleLayerLink; final LayerLink endHandleLayerLink; final Color? backgroundCursorColor; final ValueNotifier<bool> showCursor; final bool forceLine; final bool readOnly; final bool hasFocus; final int? maxLines; final int? minLines; final bool expands; final StrutStyle? strutStyle; final Color? selectionColor; final TextScaler textScaler; final TextAlign textAlign; final TextDirection textDirection; final Locale? locale; final String obscuringCharacter; final bool obscureText; final TextHeightBehavior? textHeightBehavior; final TextWidthBasis textWidthBasis; final ViewportOffset offset; final bool rendererIgnoresPointer; final double cursorWidth; final double? cursorHeight; final Radius? cursorRadius; final Offset cursorOffset; final bool paintCursorAboveText; final bool enableInteractiveSelection; final TextSelectionDelegate textSelectionDelegate; final double devicePixelRatio; final TextRange? promptRectRange; final Color? promptRectColor; final Clip clipBehavior; @override RenderEditable createRenderObject(BuildContext context) { return RenderEditable( text: inlineSpan, cursorColor: cursorColor, startHandleLayerLink: startHandleLayerLink, endHandleLayerLink: endHandleLayerLink, backgroundCursorColor: backgroundCursorColor, showCursor: showCursor, forceLine: forceLine, readOnly: readOnly, hasFocus: hasFocus, maxLines: maxLines, minLines: minLines, expands: expands, strutStyle: strutStyle, selectionColor: selectionColor, textScaler: textScaler, textAlign: textAlign, textDirection: textDirection, locale: locale ?? Localizations.maybeLocaleOf(context), selection: value.selection, offset: offset, ignorePointer: rendererIgnoresPointer, obscuringCharacter: obscuringCharacter, obscureText: obscureText, textHeightBehavior: textHeightBehavior, textWidthBasis: textWidthBasis, cursorWidth: cursorWidth, cursorHeight: cursorHeight, cursorRadius: cursorRadius, cursorOffset: cursorOffset, paintCursorAboveText: paintCursorAboveText, enableInteractiveSelection: enableInteractiveSelection, textSelectionDelegate: textSelectionDelegate, devicePixelRatio: devicePixelRatio, promptRectRange: promptRectRange, promptRectColor: promptRectColor, clipBehavior: clipBehavior, ); } @override void updateRenderObject(BuildContext context, RenderEditable renderObject) { renderObject ..text = inlineSpan ..cursorColor = cursorColor ..startHandleLayerLink = startHandleLayerLink ..endHandleLayerLink = endHandleLayerLink ..showCursor = showCursor ..forceLine = forceLine ..readOnly = readOnly ..hasFocus = hasFocus ..maxLines = maxLines ..minLines = minLines ..expands = expands ..strutStyle = strutStyle ..selectionColor = selectionColor ..textScaler = textScaler ..textAlign = textAlign ..textDirection = textDirection ..locale = locale ?? Localizations.maybeLocaleOf(context) ..selection = value.selection ..offset = offset ..ignorePointer = rendererIgnoresPointer ..textHeightBehavior = textHeightBehavior ..textWidthBasis = textWidthBasis ..obscuringCharacter = obscuringCharacter ..obscureText = obscureText ..cursorWidth = cursorWidth ..cursorHeight = cursorHeight ..cursorRadius = cursorRadius ..cursorOffset = cursorOffset ..enableInteractiveSelection = enableInteractiveSelection ..textSelectionDelegate = textSelectionDelegate ..devicePixelRatio = devicePixelRatio ..paintCursorAboveText = paintCursorAboveText ..promptRectColor = promptRectColor ..clipBehavior = clipBehavior ..setPromptRectRange(promptRectRange); } } /// The start and end glyph heights of some range of text. @immutable class _GlyphHeights { const _GlyphHeights({ required this.start, required this.end, }); /// The glyph height of the first line. final double start; /// The glyph height of the last line. final double end; }
samples/simplistic_editor/lib/basic_text_input_client.dart/0
{ "file_path": "samples/simplistic_editor/lib/basic_text_input_client.dart", "repo_id": "samples", "token_count": 16447 }
1,312
#include "ephemeral/Flutter-Generated.xcconfig"
samples/simplistic_editor/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "samples/simplistic_editor/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "samples", "token_count": 19 }
1,313
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:provider/provider.dart'; import 'package:testing_app/models/favorites.dart'; import 'package:testing_app/screens/favorites.dart'; late Favorites favoritesList; Widget createFavoritesScreen() => ChangeNotifierProvider<Favorites>( create: (context) { favoritesList = Favorites(); return favoritesList; }, child: const MaterialApp( home: FavoritesPage(), ), ); void main() { group('Testing App State Management Tests', () { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Verifying add method', (tester) async { await tester.pumpWidget(createFavoritesScreen()); // Add an item to the list. favoritesList.add(30); await tester.pumpAndSettle(); // Check if the new item appears in the list. expect(find.text('Item 30'), findsOneWidget); }); testWidgets('Verifying remove method', (tester) async { await tester.pumpWidget(createFavoritesScreen()); // Remove an item from the list. favoritesList.remove(30); await tester.pumpAndSettle(); // Verify if it disappears. expect(find.text('Item 30'), findsNothing); }); }); }
samples/testing_app/integration_test/state_mgmt_test.dart/0
{ "file_path": "samples/testing_app/integration_test/state_mgmt_test.dart", "repo_id": "samples", "token_count": 536 }
1,314
#!/bin/bash set -e flutter doctor -v echo "Fetching dependencies and building 'prebuilt_module/flutter_module/'." pushd add_to_app/prebuilt_module/flutter_module/ flutter packages get flutter build aar popd echo "Fetching dependencies for 'plugin/flutter_module_using_plugin'." pushd add_to_app/plugin/flutter_module_using_plugin flutter packages get popd echo "Fetching dependencies for 'fullscreen/'." pushd add_to_app/fullscreen/flutter_module flutter packages get popd echo "Fetching dependencies for 'multiple_flutters/'." pushd add_to_app/multiple_flutters/multiple_flutters_module flutter packages get popd declare -ar ANDROID_PROJECT_NAMES=( "add_to_app/fullscreen/android_fullscreen" \ "add_to_app/plugin/android_using_plugin" \ "add_to_app/multiple_flutters/multiple_flutters_android" \ "add_to_app/prebuilt_module/android_using_prebuilt_module" \ ) for PROJECT_NAME in "${ANDROID_PROJECT_NAMES[@]}" do echo "== Testing '${PROJECT_NAME}' on Flutter's stable channel ==" pushd "${PROJECT_NAME}" ./gradlew --stacktrace assembleDebug ./gradlew --stacktrace assembleRelease popd done # If the credentials don't exist, this script isn't being run from within the # flutter/samples repo. Rather than throw an error, allow the test to pass # successfully. if [ ! -f "svc-keyfile.json" ] then echo "Keyfile for Firebase Test Lab not found. Skipping integration tests." echo "-- Success --" exit 0 fi # At this time, espresso tests only exist for android_fullscreen. These will # eventually be rolled out to each Android project and included in the loop # above. echo "== Espresso testing 'android_fullscreen' on Flutter's ${FLUTTER_VERSION} channel ==" pushd "add_to_app/fullscreen/android_fullscreen" ./gradlew app:assembleAndroidTest ./gradlew app:assembleDebug -Ptarget=../flutter_module/test_driver/example.dart gcloud auth activate-service-account --key-file=../../svc-keyfile.json gcloud --quiet config set project test-lab-project-ccbec gcloud firebase test android run --type instrumentation \ --app app/build/outputs/apk/debug/app-debug.apk \ --test app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk\ --timeout 5m popd echo "== Run e2e test for testing_app ==" pushd "testing_app" readonly APP_DIR=$(pwd) flutter packages get flutter build apk pushd "android" ./gradlew app:assembleAndroidTest ./gradlew app:assembleRelease -Ptarget=${APP_DIR}/test/perf_test_e2e.dart popd gcloud auth activate-service-account --key-file=../svc-keyfile.json gcloud --quiet config set project test-lab-project-ccbec gcloud firebase test android run --type instrumentation \ --app build/app/outputs/apk/release/app-release.apk \ --test build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk \ --timeout 5m popd echo "-- Success --"
samples/tool/android_ci_script.sh/0
{ "file_path": "samples/tool/android_ci_script.sh", "repo_id": "samples", "token_count": 961 }
1,315
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig"
samples/veggieseasons/ios/Flutter/Debug.xcconfig/0
{ "file_path": "samples/veggieseasons/ios/Flutter/Debug.xcconfig", "repo_id": "samples", "token_count": 69 }
1,316
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>Veg. Seasons</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>veggieseasons</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>$(MARKETING_VERSION)</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>$(CURRENT_PROJECT_VERSION)</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UIViewControllerBasedStatusBarAppearance</key> <false/> </dict> </plist>
samples/veggieseasons/ios/Runner/Info.plist/0
{ "file_path": "samples/veggieseasons/ios/Runner/Info.plist", "repo_id": "samples", "token_count": 599 }
1,317
// Copyright 2018 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:veggieseasons/styles.dart'; import 'settings_item.dart'; // The widgets in this file present a group of Cupertino-style settings items to // the user. In the future, the Cupertino package in the Flutter SDK will // include dedicated widgets for this purpose, but for now they're done here. // // See https://github.com/flutter/flutter/projects/29 for more info. class SettingsGroupHeader extends StatelessWidget { const SettingsGroupHeader(this.title, {super.key}); final String title; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only( left: 15, right: 15, bottom: 6, ), child: Text( title.toUpperCase(), style: Styles.settingsGroupHeaderText(CupertinoTheme.of(context)), ), ); } } class SettingsGroupFooter extends StatelessWidget { const SettingsGroupFooter(this.title, {super.key}); final String title; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only( left: 15, right: 15, top: 7.5, ), child: Text(title, style: Styles.settingsGroupFooterText(CupertinoTheme.of(context))), ); } } class SettingsGroup extends StatelessWidget { SettingsGroup({ required this.items, this.header, this.footer, super.key, }) : assert(items.isNotEmpty); final List<SettingsItem> items; final Widget? header; final Widget? footer; @override Widget build(BuildContext context) { var brightness = CupertinoTheme.brightnessOf(context); final dividedItems = <Widget>[items[0]]; for (var i = 1; i < items.length; i++) { dividedItems.add(Container( color: Styles.settingsLineation(brightness), height: 0.3, )); dividedItems.add(items[i]); } return Padding( padding: EdgeInsets.only( top: header == null ? 35 : 22, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (header != null) header!, Container( decoration: BoxDecoration( color: CupertinoColors.white, border: Border( top: BorderSide( color: Styles.settingsLineation(brightness), width: 0, ), bottom: BorderSide( color: Styles.settingsLineation(brightness), width: 0, ), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: dividedItems, ), ), if (footer != null) footer!, ], ), ); } }
samples/veggieseasons/lib/widgets/settings_group.dart/0
{ "file_path": "samples/veggieseasons/lib/widgets/settings_group.dart", "repo_id": "samples", "token_count": 1269 }
1,318
// Copyright 2021 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:web_startup_analyzer/web_startup_analyzer.dart'; main() async { var analyzer = WebStartupAnalyzer(additionalFrameCount: 10); print(json.encode(analyzer.startupTiming)); analyzer.onFirstFrame.addListener(() { print(json.encode({'firstFrame': analyzer.onFirstFrame.value})); }); analyzer.onFirstPaint.addListener(() { print(json.encode({ 'firstPaint': analyzer.onFirstPaint.value?.$1, 'firstContentfulPaint': analyzer.onFirstPaint.value?.$2, })); }); analyzer.onAdditionalFrames.addListener(() { print(json.encode({ 'additionalFrames': analyzer.onAdditionalFrames.value, })); }); runApp( WebStartupAnalyzerSample( analyzer: analyzer, ), ); } class WebStartupAnalyzerSample extends StatelessWidget { final WebStartupAnalyzer analyzer; const WebStartupAnalyzerSample({super.key, required this.analyzer}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter web app timing', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.green.shade100), ), home: WebStartupAnalyzerScreen(analyzer: analyzer), ); } } class WebStartupAnalyzerScreen extends StatefulWidget { final WebStartupAnalyzer analyzer; const WebStartupAnalyzerScreen({super.key, required this.analyzer}); @override State<WebStartupAnalyzerScreen> createState() => _WebStartupAnalyzerScreenState(); } class _WebStartupAnalyzerScreenState extends State<WebStartupAnalyzerScreen> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.amber.shade50, body: Align( alignment: Alignment.topCenter, child: Container( margin: const EdgeInsets.all(8.0), constraints: const BoxConstraints(maxWidth: 400), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8.0), ), child: ListenableBuilder( listenable: widget.analyzer.onChange, builder: (BuildContext context, child) { return ListView( shrinkWrap: true, children: [ TimingWidget( name: 'DCL', timingMs: widget.analyzer.domContentLoaded, ), TimingWidget( name: 'Load entrypoint', timingMs: widget.analyzer.loadEntrypoint, ), TimingWidget( name: 'Initialize engine', timingMs: widget.analyzer.initializeEngine, ), TimingWidget( name: 'Run app', timingMs: widget.analyzer.appRunnerRunApp, ), if (widget.analyzer.firstFrame != null) TimingWidget( name: 'First frame', timingMs: widget.analyzer.firstFrame!, ), if (widget.analyzer.firstPaint != null) TimingWidget( name: 'First paint', timingMs: widget.analyzer.firstPaint!), if (widget.analyzer.firstContentfulPaint != null) TimingWidget( name: 'First contentful paint', timingMs: widget.analyzer.firstContentfulPaint!), if (widget.analyzer.additionalFrames != null) ...[ for (var i in widget.analyzer.additionalFrames!) TimingWidget(name: 'Frame', timingMs: i.toDouble()), ] else TextButton( child: const Text('Trigger frames'), onPressed: () {}, ), ], ); }, ), ), ), ); } } class TimingWidget extends StatelessWidget { final String name; final double timingMs; const TimingWidget({ super.key, required this.name, required this.timingMs, }); @override Widget build(BuildContext context) { return ListTile( title: Text( name, style: const TextStyle(fontSize: 18), overflow: TextOverflow.ellipsis, ), trailing: Text( '${timingMs.truncate()}ms', style: const TextStyle(fontSize: 18), ), ); } }
samples/web/_packages/web_startup_analyzer/example/lib/main.dart/0
{ "file_path": "samples/web/_packages/web_startup_analyzer/example/lib/main.dart", "repo_id": "samples", "token_count": 2250 }
1,319
name: web_startup_analyzer description: "Captures web startup timing data in a Flutter web app" version: 0.1.0-wip environment: sdk: ^3.2.0 flutter: ^3.16.0 dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.0 flutter: assets: - lib/web_startup_analyzer.js
samples/web/_packages/web_startup_analyzer/pubspec.yaml/0
{ "file_path": "samples/web/_packages/web_startup_analyzer/pubspec.yaml", "repo_id": "samples", "token_count": 144 }
1,320
samples: # Bad type, should be string, but it's a number. - name: 42 screenshots: - url: https://placekitten.com/500/500 alt: a kitten - url: https://placekitten.com/400/400 alt: another kitten source: http://github.com/johnpryan/kittens description: A sample kitten app difficulty: beginner widgets: - AnimatedBuilder - FutureBuilder packages: - json_serializable - path tags: ['beginner', 'kittens', 'cats'] platforms: ['web', 'ios', 'android'] links: - text: inspiration href: https://apps.apple.com/us/app/neko-atsume-kitty-collector/id923917775 - text: author href: http://jpryan.me type: sample # sample or app date: 2019-12-15T02:59:43.1Z channel: stable
samples/web/samples_index/test/yaml/bad.yaml/0
{ "file_path": "samples/web/samples_index/test/yaml/bad.yaml", "repo_id": "samples", "token_count": 331 }
1,321
// ignore_for_file: avoid_web_libraries_in_flutter import 'dart:async'; import 'package:flutter/material.dart'; import 'package:js/js.dart' as js; import 'package:js/js_util.dart' as js_util; void main() { runApp(const MyApp()); } enum DemoScreen { counter, textField, custom } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } @js.JSExport() class _MyAppState extends State<MyApp> { final _streamController = StreamController<void>.broadcast(); DemoScreen _currentDemoScreen = DemoScreen.counter; int _counterScreenCount = 0; @override void initState() { super.initState(); final export = js_util.createDartExport(this); js_util.setProperty(js_util.globalThis, '_appState', export); js_util.callMethod<void>(js_util.globalThis, '_stateSet', []); } @override void dispose() { _streamController.close(); super.dispose(); } @js.JSExport() void increment() { if (_currentDemoScreen == DemoScreen.counter) { setState(() { _counterScreenCount++; _streamController.add(null); }); } } @js.JSExport() void addHandler(void Function() handler) { _streamController.stream.listen((event) { handler(); }); } @js.JSExport() int get count => _counterScreenCount; @override Widget build(BuildContext context) { return MaterialApp( title: 'Element embedding', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), ), debugShowCheckedModeBanner: false, home: demoScreenRouter(_currentDemoScreen), ); } Widget demoScreenRouter(DemoScreen which) { switch (which) { case DemoScreen.counter: return CounterDemo( title: 'Counter', numToDisplay: _counterScreenCount, incrementHandler: increment, ); case DemoScreen.textField: return const TextFieldDemo(title: 'Note to Self'); case DemoScreen.custom: return const CustomDemo(title: 'Character Counter'); } } @js.JSExport() void changeDemoScreenTo(String screenString) { setState(() { switch (screenString) { case 'counter': _currentDemoScreen = DemoScreen.counter; break; case 'textField': _currentDemoScreen = DemoScreen.textField; break; case 'custom': _currentDemoScreen = DemoScreen.custom; break; default: _currentDemoScreen = DemoScreen.counter; break; } }); } } class CounterDemo extends StatefulWidget { final String title; final int numToDisplay; final VoidCallback incrementHandler; const CounterDemo({ super.key, required this.title, required this.numToDisplay, required this.incrementHandler, }); @override State<CounterDemo> createState() => _CounterDemoState(); } class _CounterDemoState extends State<CounterDemo> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '${widget.numToDisplay}', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: widget.incrementHandler, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } } class TextFieldDemo extends StatelessWidget { const TextFieldDemo({super.key, required this.title}); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), ), body: const Center( child: Padding( padding: EdgeInsets.all(14.0), child: TextField( maxLines: null, decoration: InputDecoration( border: OutlineInputBorder(), // hintText: 'Text goes here!', ), ), ), ), ); } } class CustomDemo extends StatefulWidget { final String title; const CustomDemo({super.key, required this.title}); @override State<CustomDemo> createState() => _CustomDemoState(); } class _CustomDemoState extends State<CustomDemo> { final double textFieldHeight = 80; final Color colorPrimary = const Color(0xff027dfd); // const Color(0xffd43324); // const Color(0xff6200ee); // const Color.fromARGB(255, 255, 82, 44); final TextEditingController _textController = TextEditingController(); late FocusNode textFocusNode; int totalCharCount = 0; @override void initState() { super.initState(); textFocusNode = FocusNode(); textFocusNode.requestFocus(); } @override void dispose() { _textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( toolbarHeight: MediaQuery.of(context).size.height - textFieldHeight, flexibleSpace: Container( color: colorPrimary, height: MediaQuery.of(context).size.height - textFieldHeight, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'COUNT WITH DASH!', style: TextStyle(color: Colors.white, fontSize: 18), ), const SizedBox( height: 26, ), Container( width: 98, height: 98, decoration: BoxDecoration( border: Border.all(width: 2, color: Colors.white), shape: BoxShape.circle, ), child: Center( child: Container( width: 90, height: 90, decoration: const BoxDecoration( image: DecorationImage( image: AssetImage('assets/dash.png'), fit: BoxFit.cover, ), color: Colors.white, shape: BoxShape.circle, ), ), ), ), const SizedBox(height: 20), Text( totalCharCount.toString(), style: const TextStyle(color: Colors.white, fontSize: 52), ), // const Text( // 'characters typed', // style: TextStyle(color: Colors.white, fontSize: 14), // ), ], ), ), ), body: Column( children: [ SizedBox( height: textFieldHeight, child: Center( child: Padding( padding: const EdgeInsets.only(left: 18, right: 18), child: Row( children: [ Expanded( child: TextField( controller: _textController, focusNode: textFocusNode, onSubmitted: (value) { textFocusNode.requestFocus(); }, onChanged: (value) { handleChange(); }, maxLines: 1, decoration: const InputDecoration( border: OutlineInputBorder(), ), ), ), const SizedBox( width: 12, ), Center( child: Container( width: 42, height: 42, decoration: BoxDecoration( color: colorPrimary, shape: BoxShape.circle, ), child: IconButton( icon: const Icon(Icons.refresh), color: Colors.white, onPressed: () { handleClear(); }, ), ), ), ], ), ), ), ), ], ), ); } void handleChange() { setState(() { totalCharCount = _textController.value.text.toString().length; }); } void handleClear() { setState(() { _textController.clear(); totalCharCount = 0; }); textFocusNode.requestFocus(); } }
samples/web_embedding/element_embedding_demo/lib/main.dart/0
{ "file_path": "samples/web_embedding/element_embedding_demo/lib/main.dart", "repo_id": "samples", "token_count": 4507 }
1,322
// Sets up a channel to JS-interop with Flutter (function() { "use strict"; // This function will be called from Flutter when it prepares the JS-interop. window._stateSet = function () { window._stateSet = function () { console.log("Call _stateSet only once!"); }; // The state of the flutter app, see `class _MyAppState` in lib/main.dart. let appState = window._appState; let valueField = document.querySelector("#value"); let updateState = function () { valueField.value = appState.count; }; // Register a callback to update the HTML field from Flutter. appState.addHandler(updateState); // Render the first value (0). updateState(); let incrementButton = document.querySelector("#increment"); incrementButton.addEventListener("click", (event) => { appState.increment(); }); let screenSelector = document.querySelector("#screen-selector"); screenSelector.addEventListener("change", (event) => { appState.changeDemoScreenTo(event.target.value); setJsInteropControlsEnabled(event.target.value === 'counter'); }); // Enables/disables the Value/Increment controls. function setJsInteropControlsEnabled(enabled) { let elements = document.querySelectorAll("#increment, label[for='value']"); elements.forEach((el) => { el.classList.toggle('disabled', !enabled); }) } }; }());
samples/web_embedding/element_embedding_demo/web/js/demo-js-interop.js/0
{ "file_path": "samples/web_embedding/element_embedding_demo/web/js/demo-js-interop.js", "repo_id": "samples", "token_count": 485 }
1,323
import 'dart:js_interop'; import 'package:flutter/foundation.dart'; enum DemoScreen { counter('counter'), text('text'), dash('dash'); const DemoScreen(String screen) : _screen = screen; final String _screen; @override String toString() => _screen; } /// This is the bit of state that JS is able to see. /// /// It contains getters/setters/operations and a mechanism to /// subscribe to change notifications from an incoming [notifier]. @JSExport() class DemoAppStateManager { // Creates a DemoAppStateManager wrapping a ValueNotifier. DemoAppStateManager({ required ValueNotifier<DemoScreen> screen, required ValueNotifier<int> counter, required ValueNotifier<String> text, }) : _counter = counter, _text = text, _screen = screen; final ValueNotifier<DemoScreen> _screen; final ValueNotifier<int> _counter; final ValueNotifier<String> _text; // _counter int getClicks() { return _counter.value; } void setClicks(int value) { _counter.value = value; } void incrementClicks() { _counter.value++; } void decrementClicks() { _counter.value--; } // _text void setText(String text) { _text.value = text; } String getText() { return _text.value; } // _screen void setScreen(String screen) { _screen.value = DemoScreen.values.byName(screen); } String getScreen() { return _screen.value.toString(); } // Allows clients to subscribe to changes to the wrapped value. void onClicksChanged(VoidCallback f) { _counter.addListener(f); } void onTextChanged(VoidCallback f) { _text.addListener(f); } void onScreenChanged(VoidCallback f) { _screen.addListener(f); } }
samples/web_embedding/ng-flutter/flutter/lib/src/js_interop/counter_state_manager.dart/0
{ "file_path": "samples/web_embedding/ng-flutter/flutter/lib/src/js_interop/counter_state_manager.dart", "repo_id": "samples", "token_count": 588 }
1,324
lts/*
website/.nvmrc/0
{ "file_path": "website/.nvmrc", "repo_id": "website", "token_count": 4 }
1,325
import 'package:flutter/material.dart'; void main() => runApp(const SnackBarDemo()); class SnackBarDemo extends StatelessWidget { const SnackBarDemo({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'SnackBar Demo', // #docregion Scaffold home: Scaffold( appBar: AppBar( title: const Text('SnackBar Demo'), ), body: const SnackBarPage(), ), // #enddocregion Scaffold ); } } class SnackBarPage extends StatelessWidget { const SnackBarPage({super.key}); @override Widget build(BuildContext context) { return Center( child: ElevatedButton( onPressed: () { // #docregion SnackBarAction final snackBar = SnackBar( content: const Text('Yay! A SnackBar!'), action: SnackBarAction( label: 'Undo', onPressed: () { // Some code to undo the change. }, ), ); // #enddocregion SnackBarAction // Find the ScaffoldMessenger in the widget tree // and use it to show a SnackBar. ScaffoldMessenger.of(context).showSnackBar(snackBar); }, child: const Text('Show SnackBar'), ), ); } }
website/examples/cookbook/design/snackbars/lib/main.dart/0
{ "file_path": "website/examples/cookbook/design/snackbars/lib/main.dart", "repo_id": "website", "token_count": 600 }
1,326
import 'package:flutter/material.dart'; // #docregion LocationListItem @immutable class LocationListItem extends StatelessWidget { const LocationListItem({ super.key, required this.imageUrl, required this.name, required this.country, }); final String imageUrl; final String name; final String country; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), child: AspectRatio( aspectRatio: 16 / 9, child: ClipRRect( borderRadius: BorderRadius.circular(16), child: Stack( children: [ _buildParallaxBackground(context), _buildGradient(), _buildTitleAndSubtitle(), ], ), ), ), ); } Widget _buildParallaxBackground(BuildContext context) { return Positioned.fill( child: Image.network( imageUrl, fit: BoxFit.cover, ), ); } Widget _buildGradient() { return Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.transparent, Colors.black.withOpacity(0.7)], begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: const [0.6, 0.95], ), ), ), ); } Widget _buildTitleAndSubtitle() { return Positioned( left: 20, bottom: 20, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( name, style: const TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), Text( country, style: const TextStyle( color: Colors.white, fontSize: 14, ), ), ], ), ); } } // #enddocregion LocationListItem
website/examples/cookbook/effects/parallax_scrolling/lib/excerpt2.dart/0
{ "file_path": "website/examples/cookbook/effects/parallax_scrolling/lib/excerpt2.dart", "repo_id": "website", "token_count": 1006 }
1,327
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; // #docregion TypingIndicator class TypingIndicator extends StatefulWidget { const TypingIndicator({ super.key, this.showIndicator = false, this.bubbleColor = const Color(0xFF646b7f), this.flashingCircleDarkColor = const Color(0xFF333333), this.flashingCircleBrightColor = const Color(0xFFaec1dd), }); final bool showIndicator; final Color bubbleColor; final Color flashingCircleDarkColor; final Color flashingCircleBrightColor; @override State<TypingIndicator> createState() => _TypingIndicatorState(); } class _TypingIndicatorState extends State<TypingIndicator> { @override Widget build(BuildContext context) { // TODO: return const SizedBox(); } } // #enddocregion TypingIndicator
website/examples/cookbook/effects/typing_indicator/lib/excerpt1.dart/0
{ "file_path": "website/examples/cookbook/effects/typing_indicator/lib/excerpt1.dart", "repo_id": "website", "token_count": 276 }
1,328
name: games_services_example description: Games services environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter games_services: ^4.0.0 logging: ^1.2.0 dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/games/achievements_leaderboards/pubspec.yaml/0
{ "file_path": "website/examples/cookbook/games/achievements_leaderboards/pubspec.yaml", "repo_id": "website", "token_count": 109 }
1,329
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { var title = 'Web Images'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: Text(title), ), // #docregion ImageNetwork body: Image.network('https://picsum.photos/250?image=9'), // #enddocregion ImageNetwork ), ); } }
website/examples/cookbook/images/network_image/lib/main.dart/0
{ "file_path": "website/examples/cookbook/images/network_image/lib/main.dart", "repo_id": "website", "token_count": 216 }
1,330
name: hero_animations description: Hero animations environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/navigation/hero_animations/pubspec.yaml/0
{ "file_path": "website/examples/cookbook/navigation/hero_animations/pubspec.yaml", "repo_id": "website", "token_count": 86 }
1,331
import 'package:flutter/material.dart'; class Todo { final String title; final String description; const Todo(this.title, this.description); } void main() { runApp( MaterialApp( title: 'Passing Data', home: TodosScreen( todos: List.generate( 20, (i) => Todo( 'Todo $i', 'A description of what needs to be done for Todo $i', ), ), ), ), ); } class TodosScreen extends StatelessWidget { const TodosScreen({super.key, required this.todos}); final List<Todo> todos; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Todos'), ), // #docregion builder body: ListView.builder( itemCount: todos.length, itemBuilder: (context, index) { return ListTile( title: Text(todos[index].title), // When a user taps the ListTile, navigate to the DetailScreen. // Notice that you're not only creating a DetailScreen, you're // also passing the current todo through to it. onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const DetailScreen(), // Pass the arguments as part of the RouteSettings. The // DetailScreen reads the arguments from these settings. settings: RouteSettings( arguments: todos[index], ), ), ); }, ); }, ), // #enddocregion builder ); } } // #docregion DetailScreen class DetailScreen extends StatelessWidget { const DetailScreen({super.key}); @override Widget build(BuildContext context) { final todo = ModalRoute.of(context)!.settings.arguments as Todo; // Use the Todo to create the UI. return Scaffold( appBar: AppBar( title: Text(todo.title), ), body: Padding( padding: const EdgeInsets.all(16), child: Text(todo.description), ), ); } } // #enddocregion DetailScreen
website/examples/cookbook/navigation/passing_data/lib/main_routesettings.dart/0
{ "file_path": "website/examples/cookbook/navigation/passing_data/lib/main_routesettings.dart", "repo_id": "website", "token_count": 1014 }
1,332
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; // #docregion Http import 'package:http/http.dart' as http; // #enddocregion Http Future<Album> fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), ); if (response.statusCode == 200) { // If the server did return a 200 OK response, then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a 200 OK response, then throw an exception. throw Exception('Failed to load album'); } } // #docregion deleteAlbum Future<Album> deleteAlbum(String id) async { final http.Response response = await http.delete( Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. After deleting, // you'll get an empty JSON `{}` response. // Don't return `null`, otherwise `snapshot.hasData` // will always return false on `FutureBuilder`. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a "200 OK response", // then throw an exception. throw Exception('Failed to delete album.'); } } // #enddocregion deleteAlbum class Album { final int id; final String title; const Album({required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return switch (json) { { 'id': int id, 'title': String title, } => Album( id: id, title: title, ), _ => throw const FormatException('Failed to load album.'), }; } } void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() { return _MyAppState(); } } class _MyAppState extends State<MyApp> { late Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Delete Data Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar( title: const Text('Delete Data Example'), ), body: Center( child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { // If the connection is done, // check for response data or an error. if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { // #docregion Column return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(snapshot.data?.title ?? 'Deleted'), ElevatedButton( child: const Text('Delete Data'), onPressed: () { setState(() { _futureAlbum = deleteAlbum(snapshot.data!.id.toString()); }); }, ), ], ); // #enddocregion Column } else if (snapshot.hasError) { return Text('${snapshot.error}'); } } // By default, show a loading spinner. return const CircularProgressIndicator(); }, ), ), ), ); } }
website/examples/cookbook/networking/delete_data/lib/main.dart/0
{ "file_path": "website/examples/cookbook/networking/delete_data/lib/main.dart", "repo_id": "website", "token_count": 1773 }
1,333
name: sqlite description: Example of using sqflite plugin to access SQLite database. environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter sqflite: ^2.3.2 path: ^1.9.0 dev_dependencies: example_utils: path: ../../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/cookbook/persistence/sqlite/pubspec.yaml/0
{ "file_path": "website/examples/cookbook/persistence/sqlite/pubspec.yaml", "repo_id": "website", "token_count": 133 }
1,334
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; // #docregion fetchAlbum Future<Album> fetchAlbum(http.Client client) async { final response = await client .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); } } // #enddocregion fetchAlbum class Album { final int userId; final int id; final String title; const Album({required this.userId, required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( userId: json['userId'] as int, id: json['id'] as int, title: json['title'] as String, ); } } void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { late final Future<Album> futureAlbum; @override void initState() { super.initState(); futureAlbum = fetchAlbum(http.Client()); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Fetch Data Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar( title: const Text('Fetch Data Example'), ), body: Center( child: FutureBuilder<Album>( future: futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data!.title); } else if (snapshot.hasError) { return Text('${snapshot.error}'); } // By default, show a loading spinner. return const CircularProgressIndicator(); }, ), ), ), ); } }
website/examples/cookbook/testing/unit/mocking/lib/main.dart/0
{ "file_path": "website/examples/cookbook/testing/unit/mocking/lib/main.dart", "repo_id": "website", "token_count": 903 }
1,335
name: scrolling description: A new Flutter project. environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter path_provider: ^2.1.2 path: ^1.9.0 flutter_test: sdk: flutter dev_dependencies: example_utils: path: ../../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/testing/widget/scrolling/pubspec.yaml/0
{ "file_path": "website/examples/cookbook/testing/widget/scrolling/pubspec.yaml", "repo_id": "website", "token_count": 127 }
1,336
import 'dart:convert'; import 'user.dart'; // #docregion JSON const jsonString = ''' { "name": "John Smith", "email": "[email protected]" } '''; // #enddocregion JSON void example() { // #docregion manual final user = jsonDecode(jsonString) as Map<String, dynamic>; print('Howdy, ${user['name']}!'); print('We sent the verification link to ${user['email']}.'); // #enddocregion manual } void exampleJson() { // #docregion fromJson final userMap = jsonDecode(jsonString) as Map<String, dynamic>; final user = User.fromJson(userMap); print('Howdy, ${user.name}!'); print('We sent the verification link to ${user.email}.'); // #enddocregion fromJson // #docregion jsonEncode // ignore: unused_local_variable String json = jsonEncode(user); // #enddocregion jsonEncode }
website/examples/development/data-and-backend/json/lib/manual/main.dart/0
{ "file_path": "website/examples/development/data-and-backend/json/lib/manual/main.dart", "repo_id": "website", "token_count": 278 }
1,337
// #docregion Import import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; // #enddocregion Import class HybridCompositionWidget extends StatelessWidget { const HybridCompositionWidget({super.key}); @override // #docregion HybridCompositionWidget Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. const Map<String, dynamic> creationParams = <String, dynamic>{}; return PlatformViewLink( viewType: viewType, surfaceFactory: (context, controller) { return AndroidViewSurface( controller: controller as AndroidViewController, gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); }, onCreatePlatformView: (params) { return PlatformViewsService.initSurfaceAndroidView( id: params.id, viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), onFocus: () { params.onFocusChanged(true); }, ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..create(); }, ); } // #enddocregion HybridCompositionWidget }
website/examples/development/platform_integration/lib/platform_views/native_view_example_1.dart/0
{ "file_path": "website/examples/development/platform_integration/lib/platform_views/native_view_example_1.dart", "repo_id": "website", "token_count": 588 }
1,338
arb-dir: lib template-arb-file: arb_examples.arb output-localization-file: app_localizations.dart
website/examples/get-started/flutter-for/android_devs/l10n.yaml/0
{ "file_path": "website/examples/get-started/flutter-for/android_devs/l10n.yaml", "repo_id": "website", "token_count": 35 }
1,339
import 'package:flutter/material.dart'; class SampleApp extends StatelessWidget { // This widget is the root of your application. const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Fade Demo', home: MyFadeTest(title: 'Fade Demo'), ); } } class MyFadeTest extends StatefulWidget { const MyFadeTest({super.key, required this.title}); final String title; @override State<MyFadeTest> createState() => _MyFadeTest(); } class _MyFadeTest extends State<MyFadeTest> with SingleTickerProviderStateMixin { late AnimationController controller; late CurvedAnimation curve; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 2000), vsync: this, ); curve = CurvedAnimation( parent: controller, curve: Curves.easeIn, ); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(widget.title)), body: Center( child: FadeTransition( opacity: curve, child: const FlutterLogo(size: 100), ), ), floatingActionButton: FloatingActionButton( onPressed: () { controller.forward(); }, tooltip: 'Fade', child: const Icon(Icons.brush), ), ); } }
website/examples/get-started/flutter-for/ios_devs/lib/animation.dart/0
{ "file_path": "website/examples/get-started/flutter-for/ios_devs/lib/animation.dart", "repo_id": "website", "token_count": 578 }
1,340
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( home: MyHomePage(), ); } } // #docregion State class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('$_counter'), TextButton( onPressed: () => setState(() { _counter++; }), child: const Text('+'), ), ], ), ), ); } } // #enddocregion State
website/examples/get-started/flutter-for/ios_devs/lib/state.dart/0
{ "file_path": "website/examples/get-started/flutter-for/ios_devs/lib/state.dart", "repo_id": "website", "token_count": 442 }
1,341
// Flutter import 'package:flutter/material.dart'; void main() { runApp( const Center( child: Text( 'Hello, world!', textDirection: TextDirection.ltr, ), ), ); }
website/examples/get-started/flutter-for/react_native_devs/lib/hello_world.dart/0
{ "file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/hello_world.dart", "repo_id": "website", "token_count": 95 }
1,342
import 'package:flutter/material.dart'; void main() { runApp(const FadeAppTest()); } class FadeAppTest extends StatelessWidget { /// This widget is the root of your application. const FadeAppTest({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Fade Demo', home: MyFadeTest(title: 'Fade Demo'), ); } } class MyFadeTest extends StatefulWidget { const MyFadeTest({super.key, required this.title}); final String title; @override State<MyFadeTest> createState() => _MyFadeTest(); } class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin { late final AnimationController controller; late final CurvedAnimation curve; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 2000), vsync: this, ); curve = CurvedAnimation( parent: controller, curve: Curves.easeIn, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(widget.title)), body: Center( child: FadeTransition( opacity: curve, child: const FlutterLogo(size: 100), ), ), floatingActionButton: FloatingActionButton( onPressed: () { controller.forward(); }, tooltip: 'Fade', child: const Icon(Icons.brush), ), ); } }
website/examples/get-started/flutter-for/xamarin_devs/lib/animation.dart/0
{ "file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/animation.dart", "repo_id": "website", "token_count": 566 }
1,343
import 'dart:developer' as developer; import 'package:flutter/material.dart'; // #docregion Main void main() { runApp( MaterialApp( home: const MyAppHome(), // becomes the route named '/' routes: <String, WidgetBuilder>{ '/a': (context) => const MyPage(title: 'page A'), '/b': (context) => const MyPage(title: 'page B'), '/c': (context) => const MyPage(title: 'page C'), }, ), ); } // #enddocregion Main class MyAppHome extends StatelessWidget { const MyAppHome({super.key}); @override Widget build(BuildContext context) { return const Text('Hello World!'); } } class MyPage extends StatelessWidget { const MyPage({super.key, required this.title}); final String title; @override Widget build(BuildContext context) { return Text(title); } } class AnotherPage extends StatelessWidget { const AnotherPage({super.key}); void goToPage(BuildContext context) { // #docregion PushNamed Navigator.of(context).pushNamed('/b'); // #enddocregion PushNamed } Future<void> goToAnotherPage(BuildContext context) async { // #docregion await Object? coordinates = await Navigator.of(context).pushNamed('/location'); // #enddocregion await if (coordinates is Map) { developer.log(coordinates.toString()); } } void popLocation(BuildContext context) { // #docregion PopLocation Navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392}); // #enddocregion PopLocation } @override Widget build(BuildContext context) { return const Text('Hello World!'); } }
website/examples/get-started/flutter-for/xamarin_devs/lib/navigation.dart/0
{ "file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/navigation.dart", "repo_id": "website", "token_count": 571 }
1,344
import 'package:flutter_driver/flutter_driver.dart'; import 'package:test/test.dart'; void main() { group('end-to-end test', () { late FlutterDriver driver; setUpAll(() async { // Connect to a running Flutter application instance. driver = await FlutterDriver.connect(); }); tearDownAll(() async { await driver.close(); }); test('tap on the floating action button; verify counter', () async { // Finds the floating action button to tap on. SerializableFinder fab = find.byTooltip('Increment'); // Wait for the floating action button to appear. await driver.waitFor(fab); // Emulate a tap on the floating action button. await driver.tap(fab); // Wait for text to change to the desired value. await driver.waitFor(find.text('1')); }); }); }
website/examples/integration_test/test_driver/before.dart/0
{ "file_path": "website/examples/integration_test/test_driver/before.dart", "repo_id": "website", "token_count": 296 }
1,345
name: add_language description: An i18n app example that adds a supported language environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: any # Use the pinned version from flutter_localizations dev_dependencies: example_utils: path: ../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/internationalization/add_language/pubspec.yaml/0
{ "file_path": "website/examples/internationalization/add_language/pubspec.yaml", "repo_id": "website", "token_count": 143 }
1,346
name: dart_swift_concurrency description: Examples for the Flutter concurrency for Swift developers article. publish_to: none environment: sdk: ^3.3.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../example_utils flutter: uses-material-design: true
website/examples/resources/dart_swift_concurrency/pubspec.yaml/0
{ "file_path": "website/examples/resources/dart_swift_concurrency/pubspec.yaml", "repo_id": "website", "token_count": 105 }
1,347
import 'package:flutter/material.dart'; class ProblemWidget extends StatelessWidget { const ProblemWidget({super.key}); @override // #docregion Problem Widget build(BuildContext context) { return Center( child: Column( children: <Widget>[ const Text('Header'), ListView( children: const <Widget>[ ListTile( leading: Icon(Icons.map), title: Text('Map'), ), ListTile( leading: Icon(Icons.subway), title: Text('Subway'), ), ], ), ], ), ); } // #enddocregion Problem } class SolutionWidget extends StatelessWidget { const SolutionWidget({super.key}); @override // #docregion Fix Widget build(BuildContext context) { return Center( child: Column( children: <Widget>[ const Text('Header'), Expanded( child: ListView( children: const <Widget>[ ListTile( leading: Icon(Icons.map), title: Text('Map'), ), ListTile( leading: Icon(Icons.subway), title: Text('Subway'), ), ], ), ), ], ), ); } // #enddocregion Fix }
website/examples/testing/common_errors/lib/unbounded_height.dart/0
{ "file_path": "website/examples/testing/common_errors/lib/unbounded_height.dart", "repo_id": "website", "token_count": 737 }
1,348
// #docregion initial import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:how_to/main.dart'; import 'package:integration_test/integration_test.dart'; void main() { // #enddocregion initial IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // NEW // #docregion initial testWidgets('tap on the floating action button, verify counter', (tester) async { // Load app widget. await tester.pumpWidget(const MyApp()); // Verify the counter starts at 0. expect(find.text('0'), findsOneWidget); // Finds the floating action button to tap on. final fab = find.byKey(const Key('increment')); // Emulate a tap on the floating action button. await tester.tap(fab); // Trigger a frame. await tester.pumpAndSettle(); // Verify the counter increments by 1. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); } // #enddocregion initial
website/examples/testing/integration_tests/how_to/integration_test/counter_test.dart/0
{ "file_path": "website/examples/testing/integration_tests/how_to/integration_test/counter_test.dart", "repo_id": "website", "token_count": 329 }
1,349