text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../platform_interface/quick_actions_platform.dart';
import '../types/types.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/quick_actions');
/// An implementation of [QuickActionsPlatform] that uses method channels.
class MethodChannelQuickActions extends QuickActionsPlatform {
/// The MethodChannel that is being used by this implementation of the plugin.
@visibleForTesting
MethodChannel get channel => _channel;
@override
Future<void> initialize(QuickActionHandler handler) async {
channel.setMethodCallHandler((MethodCall call) async {
assert(call.method == 'launch');
handler(call.arguments as String);
});
final String? action =
await channel.invokeMethod<String?>('getLaunchAction');
if (action != null) {
handler(action);
}
}
@override
Future<void> setShortcutItems(List<ShortcutItem> items) async {
final List<Map<String, String?>> itemsList =
items.map(_serializeItem).toList();
await channel.invokeMethod<void>('setShortcutItems', itemsList);
}
@override
Future<void> clearShortcutItems() =>
channel.invokeMethod<void>('clearShortcutItems');
Map<String, String?> _serializeItem(ShortcutItem item) {
return <String, String?>{
'type': item.type,
'localizedTitle': item.localizedTitle,
'icon': item.icon,
};
}
}
| plugins/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart",
"repo_id": "plugins",
"token_count": 525
} | 1,271 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('SharedPreferencesAndroid', () {
const Map<String, Object> kTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.bool': true,
'flutter.int': 42,
'flutter.double': 3.14159,
'flutter.List': <String>['foo', 'bar'],
};
const Map<String, Object> kTestValues2 = <String, Object>{
'flutter.String': 'goodbye world',
'flutter.bool': false,
'flutter.int': 1337,
'flutter.double': 2.71828,
'flutter.List': <String>['baz', 'quox'],
};
late SharedPreferencesStorePlatform preferences;
setUp(() async {
preferences = SharedPreferencesStorePlatform.instance;
});
tearDown(() {
preferences.clear();
});
// Normally the app-facing package adds the prefix, but since this test
// bypasses the app-facing package it needs to be manually added.
String prefixedKey(String key) {
return 'flutter.$key';
}
testWidgets('reading', (WidgetTester _) async {
final Map<String, Object> values = await preferences.getAll();
expect(values[prefixedKey('String')], isNull);
expect(values[prefixedKey('bool')], isNull);
expect(values[prefixedKey('int')], isNull);
expect(values[prefixedKey('double')], isNull);
expect(values[prefixedKey('List')], isNull);
});
testWidgets('writing', (WidgetTester _) async {
await Future.wait(<Future<bool>>[
preferences.setValue(
'String', prefixedKey('String'), kTestValues2['flutter.String']!),
preferences.setValue(
'Bool', prefixedKey('bool'), kTestValues2['flutter.bool']!),
preferences.setValue(
'Int', prefixedKey('int'), kTestValues2['flutter.int']!),
preferences.setValue(
'Double', prefixedKey('double'), kTestValues2['flutter.double']!),
preferences.setValue(
'StringList', prefixedKey('List'), kTestValues2['flutter.List']!)
]);
final Map<String, Object> values = await preferences.getAll();
expect(values[prefixedKey('String')], kTestValues2['flutter.String']);
expect(values[prefixedKey('bool')], kTestValues2['flutter.bool']);
expect(values[prefixedKey('int')], kTestValues2['flutter.int']);
expect(values[prefixedKey('double')], kTestValues2['flutter.double']);
expect(values[prefixedKey('List')], kTestValues2['flutter.List']);
});
testWidgets('removing', (WidgetTester _) async {
final String key = prefixedKey('testKey');
await preferences.setValue('String', key, kTestValues['flutter.String']!);
await preferences.setValue('Bool', key, kTestValues['flutter.bool']!);
await preferences.setValue('Int', key, kTestValues['flutter.int']!);
await preferences.setValue('Double', key, kTestValues['flutter.double']!);
await preferences.setValue(
'StringList', key, kTestValues['flutter.List']!);
await preferences.remove(key);
final Map<String, Object> values = await preferences.getAll();
expect(values[key], isNull);
});
testWidgets('clearing', (WidgetTester _) async {
await preferences.setValue(
'String', 'String', kTestValues['flutter.String']!);
await preferences.setValue('Bool', 'bool', kTestValues['flutter.bool']!);
await preferences.setValue('Int', 'int', kTestValues['flutter.int']!);
await preferences.setValue(
'Double', 'double', kTestValues['flutter.double']!);
await preferences.setValue(
'StringList', 'List', kTestValues['flutter.List']!);
await preferences.clear();
final Map<String, Object> values = await preferences.getAll();
expect(values['String'], null);
expect(values['bool'], null);
expect(values['int'], null);
expect(values['double'], null);
expect(values['List'], null);
});
testWidgets('simultaneous writes', (WidgetTester _) async {
final List<Future<bool>> writes = <Future<bool>>[];
const int writeCount = 100;
for (int i = 1; i <= writeCount; i++) {
writes.add(preferences.setValue('Int', prefixedKey('int'), i));
}
final List<bool> result = await Future.wait(writes, eagerError: true);
// All writes should succeed.
expect(result.where((bool element) => !element), isEmpty);
// The last write should win.
final Map<String, Object> values = await preferences.getAll();
expect(values[prefixedKey('int')], writeCount);
});
testWidgets('string clash with lists, big integers and doubles',
(WidgetTester _) async {
final String key = prefixedKey('akey');
const String value = 'a string value';
await preferences.clear();
// Special prefixes used to store datatypes that can't be stored directly
// in SharedPreferences as strings instead.
const List<String> specialPrefixes = <String>[
// Prefix for lists:
'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu',
// Prefix for big integers:
'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy',
// Prefix for doubles:
'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu',
];
for (final String prefix in specialPrefixes) {
expect(preferences.setValue('String', key, prefix + value),
throwsA(isA<PlatformException>()));
final Map<String, Object> values = await preferences.getAll();
expect(values[key], null);
}
});
});
}
| plugins/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart",
"repo_id": "plugins",
"token_count": 2298
} | 1,272 |
// 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 'shared_preferences_platform_interface.dart';
const MethodChannel _kChannel =
MethodChannel('plugins.flutter.io/shared_preferences');
/// Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing
/// a persistent store for simple data.
///
/// Data is persisted to disk asynchronously.
class MethodChannelSharedPreferencesStore
extends SharedPreferencesStorePlatform {
@override
Future<bool> remove(String key) async {
return (await _kChannel.invokeMethod<bool>(
'remove',
<String, dynamic>{'key': key},
))!;
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
return (await _kChannel.invokeMethod<bool>(
'set$valueType',
<String, dynamic>{'key': key, 'value': value},
))!;
}
@override
Future<bool> clear() async {
return (await _kChannel.invokeMethod<bool>('clear'))!;
}
@override
Future<Map<String, Object>> getAll() async {
final Map<String, Object>? preferences =
await _kChannel.invokeMapMethod<String, Object>('getAll');
if (preferences == null) {
return <String, Object>{};
}
return preferences;
}
}
| plugins/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart",
"repo_id": "plugins",
"token_count": 477
} | 1,273 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert' show json;
import 'dart:html' as html;
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
/// The web implementation of [SharedPreferencesStorePlatform].
///
/// This class implements the `package:shared_preferences` functionality for the web.
class SharedPreferencesPlugin extends SharedPreferencesStorePlatform {
/// Registers this class as the default instance of [SharedPreferencesStorePlatform].
static void registerWith(Registrar? registrar) {
SharedPreferencesStorePlatform.instance = SharedPreferencesPlugin();
}
@override
Future<bool> clear() async {
// IMPORTANT: Do not use html.window.localStorage.clear() as that will
// remove _all_ local data, not just the keys prefixed with
// "flutter."
_storedFlutterKeys.forEach(html.window.localStorage.remove);
return true;
}
@override
Future<Map<String, Object>> getAll() async {
final Map<String, Object> allData = <String, Object>{};
for (final String key in _storedFlutterKeys) {
allData[key] = _decodeValue(html.window.localStorage[key]!);
}
return allData;
}
@override
Future<bool> remove(String key) async {
_checkPrefix(key);
html.window.localStorage.remove(key);
return true;
}
@override
Future<bool> setValue(String valueType, String key, Object? value) async {
_checkPrefix(key);
html.window.localStorage[key] = _encodeValue(value);
return true;
}
void _checkPrefix(String key) {
if (!key.startsWith('flutter.')) {
throw FormatException(
'Shared preferences keys must start with prefix "flutter.".',
key,
0,
);
}
}
Iterable<String> get _storedFlutterKeys {
return html.window.localStorage.keys
.where((String key) => key.startsWith('flutter.'));
}
String _encodeValue(Object? value) {
return json.encode(value);
}
Object _decodeValue(String encodedValue) {
final Object? decodedValue = json.decode(encodedValue);
if (decodedValue is List) {
// JSON does not preserve generics. The encode/decode roundtrip is
// `List<String>` => JSON => `List<dynamic>`. We have to explicitly
// restore the RTTI.
return decodedValue.cast<String>();
}
return decodedValue!;
}
}
| plugins/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart",
"repo_id": "plugins",
"token_count": 902
} | 1,274 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.urllauncherexample">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<!--#docregion android-queries-->
<!-- Provide required visibility configuration for API level 30 and above -->
<queries>
<!-- If your app checks for SMS support -->
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="sms" />
</intent>
<!-- If your app checks for call support -->
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="tel" />
</intent>
<!--#enddocregion android-queries-->
<!-- The "https" scheme is only required for integration tests of this package.
It shouldn't be needed in most actual apps, or show up in the README! -->
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" />
</intent>
<!--#docregion android-queries-->
</queries>
<!--#enddocregion android-queries-->
<application
android:icon="@mipmap/ic_launcher"
android:label="url_launcher_example">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
</manifest>
| plugins/packages/url_launcher/url_launcher/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 687
} | 1,275 |
name: url_launcher
description: Flutter plugin for launching a URL. Supports
web, phone, SMS, and email schemes.
repository: https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 6.1.9
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
default_package: url_launcher_android
ios:
default_package: url_launcher_ios
linux:
default_package: url_launcher_linux
macos:
default_package: url_launcher_macos
web:
default_package: url_launcher_web
windows:
default_package: url_launcher_windows
dependencies:
flutter:
sdk: flutter
url_launcher_android: ^6.0.13
url_launcher_ios: ^6.0.13
# Allow either the pure-native or Dart/native hybrid versions of the desktop
# implementations, as both are compatible.
url_launcher_linux: ">=2.0.0 <4.0.0"
url_launcher_macos: ">=2.0.0 <4.0.0"
url_launcher_platform_interface: ^2.1.0
url_launcher_web: ^2.0.0
url_launcher_windows: ">=2.0.0 <4.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
test: ^1.16.3
| plugins/packages/url_launcher/url_launcher/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/pubspec.yaml",
"repo_id": "plugins",
"token_count": 573
} | 1,276 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.urllauncher;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Browser;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/* Launches WebView activity */
public class WebViewActivity extends Activity {
/*
* Use this to trigger a BroadcastReceiver inside WebViewActivity
* that will request the current instance to finish.
* */
public static String ACTION_CLOSE = "close action";
private final BroadcastReceiver broadcastReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_CLOSE.equals(action)) {
finish();
}
}
};
private final WebViewClient webViewClient =
new WebViewClient() {
/*
* This method is deprecated in API 24. Still overridden to support
* earlier Android versions.
*/
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(url);
return false;
}
return super.shouldOverrideUrlLoading(view, url);
}
@RequiresApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(request.getUrl().toString());
}
return false;
}
};
private WebView webview;
private IntentFilter closeIntentFilter = new IntentFilter(ACTION_CLOSE);
// Verifies that a url opened by `Window.open` has a secure url.
private class FlutterWebChromeClient extends WebChromeClient {
@Override
public boolean onCreateWindow(
final WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
final WebViewClient webViewClient =
new WebViewClient() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(
@NonNull WebView view, @NonNull WebResourceRequest request) {
webview.loadUrl(request.getUrl().toString());
return true;
}
/*
* This method is deprecated in API 24. Still overridden to support
* earlier Android versions.
*/
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webview.loadUrl(url);
return true;
}
};
final WebView newWebView = new WebView(webview.getContext());
newWebView.setWebViewClient(webViewClient);
final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
// Get the Intent that started this activity and extract the string
final Intent intent = getIntent();
final String url = intent.getStringExtra(URL_EXTRA);
final boolean enableJavaScript = intent.getBooleanExtra(ENABLE_JS_EXTRA, false);
final boolean enableDomStorage = intent.getBooleanExtra(ENABLE_DOM_EXTRA, false);
final Bundle headersBundle = intent.getBundleExtra(Browser.EXTRA_HEADERS);
final Map<String, String> headersMap = extractHeaders(headersBundle);
webview.loadUrl(url, headersMap);
webview.getSettings().setJavaScriptEnabled(enableJavaScript);
webview.getSettings().setDomStorageEnabled(enableDomStorage);
// Open new urls inside the webview itself.
webview.setWebViewClient(webViewClient);
// Multi windows is set with FlutterWebChromeClient by default to handle internal bug: b/159892679.
webview.getSettings().setSupportMultipleWindows(true);
webview.setWebChromeClient(new FlutterWebChromeClient());
// Register receiver that may finish this Activity.
registerReceiver(broadcastReceiver, closeIntentFilter);
}
@VisibleForTesting
public static Map<String, String> extractHeaders(@Nullable Bundle headersBundle) {
if (headersBundle == null) {
return Collections.emptyMap();
}
final Map<String, String> headersMap = new HashMap<>();
for (String key : headersBundle.keySet()) {
final String value = headersBundle.getString(key);
headersMap.put(key, value);
}
return headersMap;
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private static String URL_EXTRA = "url";
private static String ENABLE_JS_EXTRA = "enableJavaScript";
private static String ENABLE_DOM_EXTRA = "enableDomStorage";
/* Hides the constants used to forward data to the Activity instance. */
public static Intent createIntent(
Context context,
String url,
boolean enableJavaScript,
boolean enableDomStorage,
Bundle headersBundle) {
return new Intent(context, WebViewActivity.class)
.putExtra(URL_EXTRA, url)
.putExtra(ENABLE_JS_EXTRA, enableJavaScript)
.putExtra(ENABLE_DOM_EXTRA, enableDomStorage)
.putExtra(Browser.EXTRA_HEADERS, headersBundle);
}
}
| plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/WebViewActivity.java/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/WebViewActivity.java",
"repo_id": "plugins",
"token_count": 2389
} | 1,277 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import XCTest;
@import os.log;
@interface URLLauncherUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@end
@implementation URLLauncherUITests
- (void)setUp {
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
[self.app launch];
}
- (void)testLaunch {
XCUIApplication *app = self.app;
NSArray<NSString *> *buttonNames = @[
@"Launch in app", @"Launch in app(JavaScript ON)", @"Launch in app(DOM storage ON)",
@"Launch a universal link in a native app, fallback to Safari.(Youtube)"
];
for (NSString *buttonName in buttonNames) {
XCUIElement *button = app.buttons[buttonName];
XCTAssertTrue([button waitForExistenceWithTimeout:30.0]);
XCTAssertEqual(app.webViews.count, 0);
[button tap];
XCUIElement *webView = app.webViews.firstMatch;
XCTAssertTrue([webView waitForExistenceWithTimeout:30.0]);
XCTAssertTrue([app.buttons[@"ForwardButton"] waitForExistenceWithTimeout:30.0]);
XCTAssertTrue(app.buttons[@"Share"].exists);
XCTAssertTrue(app.buttons[@"OpenInSafariButton"].exists);
[app.buttons[@"Done"] tap];
}
}
@end
| plugins/packages/url_launcher/url_launcher_ios/example/ios/RunnerUITests/URLLauncherUITests.m/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_ios/example/ios/RunnerUITests/URLLauncherUITests.m",
"repo_id": "plugins",
"token_count": 478
} | 1,278 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,279 |
// 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 (v2.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis
// ignore_for_file: avoid_relative_lib_imports
// @dart = 2.12
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316)
// ignore: unnecessary_import
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
// TODO(gaaclarke): This had to be hand tweaked from a relative path.
import 'package:video_player_android/src/messages.g.dart';
class _TestHostVideoPlayerApiCodec extends StandardMessageCodec {
const _TestHostVideoPlayerApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is CreateMessage) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is LoopingMessage) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is MixWithOthersMessage) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else if (value is PlaybackSpeedMessage) {
buffer.putUint8(131);
writeValue(buffer, value.encode());
} else if (value is PositionMessage) {
buffer.putUint8(132);
writeValue(buffer, value.encode());
} else if (value is TextureMessage) {
buffer.putUint8(133);
writeValue(buffer, value.encode());
} else if (value is VolumeMessage) {
buffer.putUint8(134);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return CreateMessage.decode(readValue(buffer)!);
case 129:
return LoopingMessage.decode(readValue(buffer)!);
case 130:
return MixWithOthersMessage.decode(readValue(buffer)!);
case 131:
return PlaybackSpeedMessage.decode(readValue(buffer)!);
case 132:
return PositionMessage.decode(readValue(buffer)!);
case 133:
return TextureMessage.decode(readValue(buffer)!);
case 134:
return VolumeMessage.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestHostVideoPlayerApi {
static const MessageCodec<Object?> codec = _TestHostVideoPlayerApiCodec();
void initialize();
TextureMessage create(CreateMessage msg);
void dispose(TextureMessage msg);
void setLooping(LoopingMessage msg);
void setVolume(VolumeMessage msg);
void setPlaybackSpeed(PlaybackSpeedMessage msg);
void play(TextureMessage msg);
PositionMessage position(TextureMessage msg);
void seekTo(PositionMessage msg);
void pause(TextureMessage msg);
void setMixWithOthers(MixWithOthersMessage msg);
static void setup(TestHostVideoPlayerApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.initialize', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
api.initialize();
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final CreateMessage? arg_msg = (args[0] as CreateMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.create was null, expected non-null CreateMessage.');
final TextureMessage output = api.create(arg_msg!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.dispose', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.dispose was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.dispose was null, expected non-null TextureMessage.');
api.dispose(arg_msg!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setLooping', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setLooping was null.');
final List<Object?> args = (message as List<Object?>?)!;
final LoopingMessage? arg_msg = (args[0] as LoopingMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setLooping was null, expected non-null LoopingMessage.');
api.setLooping(arg_msg!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setVolume', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setVolume was null.');
final List<Object?> args = (message as List<Object?>?)!;
final VolumeMessage? arg_msg = (args[0] as VolumeMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setVolume was null, expected non-null VolumeMessage.');
api.setVolume(arg_msg!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setPlaybackSpeed', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setPlaybackSpeed was null.');
final List<Object?> args = (message as List<Object?>?)!;
final PlaybackSpeedMessage? arg_msg =
(args[0] as PlaybackSpeedMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setPlaybackSpeed was null, expected non-null PlaybackSpeedMessage.');
api.setPlaybackSpeed(arg_msg!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.play', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.play was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.play was null, expected non-null TextureMessage.');
api.play(arg_msg!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.position', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.position was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.position was null, expected non-null TextureMessage.');
final PositionMessage output = api.position(arg_msg!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.seekTo', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.seekTo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final PositionMessage? arg_msg = (args[0] as PositionMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.seekTo was null, expected non-null PositionMessage.');
api.seekTo(arg_msg!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.pause', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.pause was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.pause was null, expected non-null TextureMessage.');
api.pause(arg_msg!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setMixWithOthers', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setMixWithOthers was null.');
final List<Object?> args = (message as List<Object?>?)!;
final MixWithOthersMessage? arg_msg =
(args[0] as MixWithOthersMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setMixWithOthers was null, expected non-null MixWithOthersMessage.');
api.setMixWithOthers(arg_msg!);
return <Object?, Object?>{};
});
}
}
}
}
| plugins/packages/video_player/video_player_android/test/test_api.g.dart/0 | {
"file_path": "plugins/packages/video_player/video_player_android/test/test_api.g.dart",
"repo_id": "plugins",
"token_count": 5205
} | 1,280 |
// 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 (v2.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name
// @dart = 2.12
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
class TextureMessage {
TextureMessage({
required this.textureId,
});
int textureId;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['textureId'] = textureId;
return pigeonMap;
}
static TextureMessage decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return TextureMessage(
textureId: pigeonMap['textureId']! as int,
);
}
}
class LoopingMessage {
LoopingMessage({
required this.textureId,
required this.isLooping,
});
int textureId;
bool isLooping;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['textureId'] = textureId;
pigeonMap['isLooping'] = isLooping;
return pigeonMap;
}
static LoopingMessage decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return LoopingMessage(
textureId: pigeonMap['textureId']! as int,
isLooping: pigeonMap['isLooping']! as bool,
);
}
}
class VolumeMessage {
VolumeMessage({
required this.textureId,
required this.volume,
});
int textureId;
double volume;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['textureId'] = textureId;
pigeonMap['volume'] = volume;
return pigeonMap;
}
static VolumeMessage decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return VolumeMessage(
textureId: pigeonMap['textureId']! as int,
volume: pigeonMap['volume']! as double,
);
}
}
class PlaybackSpeedMessage {
PlaybackSpeedMessage({
required this.textureId,
required this.speed,
});
int textureId;
double speed;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['textureId'] = textureId;
pigeonMap['speed'] = speed;
return pigeonMap;
}
static PlaybackSpeedMessage decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return PlaybackSpeedMessage(
textureId: pigeonMap['textureId']! as int,
speed: pigeonMap['speed']! as double,
);
}
}
class PositionMessage {
PositionMessage({
required this.textureId,
required this.position,
});
int textureId;
int position;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['textureId'] = textureId;
pigeonMap['position'] = position;
return pigeonMap;
}
static PositionMessage decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return PositionMessage(
textureId: pigeonMap['textureId']! as int,
position: pigeonMap['position']! as int,
);
}
}
class CreateMessage {
CreateMessage({
this.asset,
this.uri,
this.packageName,
this.formatHint,
required this.httpHeaders,
});
String? asset;
String? uri;
String? packageName;
String? formatHint;
Map<String?, String?> httpHeaders;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['asset'] = asset;
pigeonMap['uri'] = uri;
pigeonMap['packageName'] = packageName;
pigeonMap['formatHint'] = formatHint;
pigeonMap['httpHeaders'] = httpHeaders;
return pigeonMap;
}
static CreateMessage decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return CreateMessage(
asset: pigeonMap['asset'] as String?,
uri: pigeonMap['uri'] as String?,
packageName: pigeonMap['packageName'] as String?,
formatHint: pigeonMap['formatHint'] as String?,
httpHeaders: (pigeonMap['httpHeaders'] as Map<Object?, Object?>?)!
.cast<String?, String?>(),
);
}
}
class MixWithOthersMessage {
MixWithOthersMessage({
required this.mixWithOthers,
});
bool mixWithOthers;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['mixWithOthers'] = mixWithOthers;
return pigeonMap;
}
static MixWithOthersMessage decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return MixWithOthersMessage(
mixWithOthers: pigeonMap['mixWithOthers']! as bool,
);
}
}
class _AVFoundationVideoPlayerApiCodec extends StandardMessageCodec {
const _AVFoundationVideoPlayerApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is CreateMessage) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is LoopingMessage) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is MixWithOthersMessage) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else if (value is PlaybackSpeedMessage) {
buffer.putUint8(131);
writeValue(buffer, value.encode());
} else if (value is PositionMessage) {
buffer.putUint8(132);
writeValue(buffer, value.encode());
} else if (value is TextureMessage) {
buffer.putUint8(133);
writeValue(buffer, value.encode());
} else if (value is VolumeMessage) {
buffer.putUint8(134);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return CreateMessage.decode(readValue(buffer)!);
case 129:
return LoopingMessage.decode(readValue(buffer)!);
case 130:
return MixWithOthersMessage.decode(readValue(buffer)!);
case 131:
return PlaybackSpeedMessage.decode(readValue(buffer)!);
case 132:
return PositionMessage.decode(readValue(buffer)!);
case 133:
return TextureMessage.decode(readValue(buffer)!);
case 134:
return VolumeMessage.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class AVFoundationVideoPlayerApi {
/// Constructor for [AVFoundationVideoPlayerApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
AVFoundationVideoPlayerApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _AVFoundationVideoPlayerApiCodec();
Future<void> initialize() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.initialize', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<TextureMessage> create(CreateMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.create', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as TextureMessage?)!;
}
}
Future<void> dispose(TextureMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.dispose', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> setLooping(LoopingMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.setLooping', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> setVolume(VolumeMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.setVolume', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> setPlaybackSpeed(PlaybackSpeedMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.setPlaybackSpeed', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> play(TextureMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.play', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<PositionMessage> position(TextureMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.position', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as PositionMessage?)!;
}
}
Future<void> seekTo(PositionMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.seekTo', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> pause(TextureMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.pause', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> setMixWithOthers(MixWithOthersMessage arg_msg) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AVFoundationVideoPlayerApi.setMixWithOthers', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_msg]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
}
| plugins/packages/video_player/video_player_avfoundation/lib/src/messages.g.dart/0 | {
"file_path": "plugins/packages/video_player/video_player_avfoundation/lib/src/messages.g.dart",
"repo_id": "plugins",
"token_count": 6581
} | 1,281 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.0.13
* Adds compatibilty with version 6.0 of the platform interface.
* Updates minimum Flutter version to 2.10.
## 2.0.12
* Updates the `README` with:
* Information about a common known issue: "Some videos restart when using the
seek bar/progress bar/scrubber" (Issue [#49630](https://github.com/flutter/flutter/issues/49360))
* Links to the Autoplay information of all major browsers (Chrome/Edge, Firefox, Safari).
## 2.0.11
* Improves handling of videos with `Infinity` duration.
## 2.0.10
* Minor fixes for new analysis options.
## 2.0.9
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.8
* Ensures `buffering` state is only removed when the browser reports enough data
has been buffered so that the video can likely play through without stopping
(`onCanPlayThrough`). Issue [#94630](https://github.com/flutter/flutter/issues/94630).
* Improves testability of the `_VideoPlayer` private class.
* Ensures that tests that listen to a Stream fail "fast" (1 second max timeout).
## 2.0.7
* Internal code cleanup for stricter analysis options.
## 2.0.6
* Removes dependency on `meta`.
## 2.0.5
* Adds compatibility with `video_player_platform_interface` 5.0, which does not
include non-dev test dependencies.
## 2.0.4
* Adopt `video_player_platform_interface` 4.2 and opt out of `contentUri` data source.
## 2.0.3
* Add `implements` to pubspec.
## 2.0.2
* Updated installation instructions in README.
## 2.0.1
* Fix videos not playing in Safari/Chrome on iOS by setting autoplay to false
* Change sizing code of `Video` widget's `HtmlElementView` so it works well when slotted.
* Move tests to `example` directory, so they run as integration_tests with `flutter drive`.
## 2.0.0
* Migrate to null safety.
* Calling `setMixWithOthers()` now is silently ignored instead of throwing an exception.
* Fixed an issue where `isBuffering` was not updating on Web.
## 0.1.4+2
* Update Flutter SDK constraint.
## 0.1.4+1
* Substitute `undefined_prefixed_name: ignore` analyzer setting by a `dart:ui` shim with conditional exports. [Issue](https://github.com/flutter/flutter/issues/69309).
## 0.1.4
* Added option to set the video playback speed on the video controller.
## 0.1.3+2
* Allow users to set the 'muted' attribute on video elements by setting their volume to 0.
* Do not parse URIs on 'network' videos to not break blobs (Safari).
## 0.1.3+1
* Remove Android folder from `video_player_web`.
## 0.1.3
* Updated video_player_platform_interface, bumped minimum Dart version to 2.1.0.
## 0.1.2+3
* Declare API stability and compatibility with `1.0.0` (more details at: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0).
## 0.1.2+2
* Add `analysis_options.yaml` to the package, so we can ignore `undefined_prefixed_name` errors. Works around https://github.com/flutter/flutter/issues/41563.
## 0.1.2+1
* Make the pedantic dev_dependency explicit.
## 0.1.2
* Add a `PlatformException` to the player's `eventController` when there's a `videoElement.onError`. Fixes https://github.com/flutter/flutter/issues/48884.
* Handle DomExceptions on videoElement.play() and turn them into `PlatformException` as well, so we don't end up with unhandled Futures.
* Update setup instructions in the README.
## 0.1.1+1
* Add an android/ folder with no-op implementation to workaround https://github.com/flutter/flutter/issues/46898.
## 0.1.1
* Support videos from assets.
## 0.1.0+1
* Remove the deprecated `author:` field from pubspec.yaml
* Require Flutter SDK 1.10.0 or greater.
## 0.1.0
* Initial release
| plugins/packages/video_player/video_player_web/CHANGELOG.md/0 | {
"file_path": "plugins/packages/video_player/video_player_web/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 1212
} | 1,282 |
name: webview_flutter_example
description: Demonstrates how to use the webview_flutter plugin.
publish_to: none
environment:
sdk: ">=2.17.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
path_provider: ^2.0.6
webview_flutter:
# When depending on this package from a real application you should use:
# webview_flutter: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
webview_flutter_android: ^3.0.0
webview_flutter_wkwebview: ^3.0.0
dev_dependencies:
build_runner: ^2.1.5
espresso: ^0.2.0
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
webview_flutter_platform_interface: ^2.0.0
flutter:
uses-material-design: true
assets:
- assets/sample_audio.ogg
- assets/sample_video.mp4
- assets/www/index.html
- assets/www/styles/style.css
| plugins/packages/webview_flutter/webview_flutter/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 415
} | 1,283 |
// 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:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'webview_controller_test.mocks.dart';
@GenerateMocks(<Type>[PlatformWebViewController, PlatformNavigationDelegate])
void main() {
test('loadFile', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.loadFile('file/path');
verify(mockPlatformWebViewController.loadFile('file/path'));
});
test('loadFlutterAsset', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.loadFlutterAsset('file/path');
verify(mockPlatformWebViewController.loadFlutterAsset('file/path'));
});
test('loadHtmlString', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.loadHtmlString('html', baseUrl: 'baseUrl');
verify(mockPlatformWebViewController.loadHtmlString(
'html',
baseUrl: 'baseUrl',
));
});
test('loadRequest', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.loadRequest(
Uri(scheme: 'https', host: 'dart.dev'),
method: LoadRequestMethod.post,
headers: <String, String>{'a': 'header'},
body: Uint8List(0),
);
final LoadRequestParams params =
verify(mockPlatformWebViewController.loadRequest(captureAny))
.captured[0] as LoadRequestParams;
expect(params.uri, Uri(scheme: 'https', host: 'dart.dev'));
expect(params.method, LoadRequestMethod.post);
expect(params.headers, <String, String>{'a': 'header'});
expect(params.body, Uint8List(0));
});
test('currentUrl', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
when(mockPlatformWebViewController.currentUrl()).thenAnswer(
(_) => Future<String>.value('https://dart.dev'),
);
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await expectLater(
webViewController.currentUrl(),
completion('https://dart.dev'),
);
});
test('canGoBack', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
when(mockPlatformWebViewController.canGoBack()).thenAnswer(
(_) => Future<bool>.value(false),
);
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await expectLater(webViewController.canGoBack(), completion(false));
});
test('canGoForward', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
when(mockPlatformWebViewController.canGoForward()).thenAnswer(
(_) => Future<bool>.value(true),
);
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await expectLater(webViewController.canGoForward(), completion(true));
});
test('goBack', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.goBack();
verify(mockPlatformWebViewController.goBack());
});
test('goForward', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.goForward();
verify(mockPlatformWebViewController.goForward());
});
test('reload', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.reload();
verify(mockPlatformWebViewController.reload());
});
test('clearCache', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.clearCache();
verify(mockPlatformWebViewController.clearCache());
});
test('clearLocalStorage', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.clearLocalStorage();
verify(mockPlatformWebViewController.clearLocalStorage());
});
test('runJavaScript', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.runJavaScript('1 + 1');
verify(mockPlatformWebViewController.runJavaScript('1 + 1'));
});
test('runJavaScriptReturningResult', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
when(mockPlatformWebViewController.runJavaScriptReturningResult('1 + 1'))
.thenAnswer((_) => Future<String>.value('2'));
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await expectLater(
webViewController.runJavaScriptReturningResult('1 + 1'),
completion('2'),
);
});
test('addJavaScriptChannel', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
void onMessageReceived(JavaScriptMessage message) {}
await webViewController.addJavaScriptChannel(
'name',
onMessageReceived: onMessageReceived,
);
final JavaScriptChannelParams params =
verify(mockPlatformWebViewController.addJavaScriptChannel(captureAny))
.captured[0] as JavaScriptChannelParams;
expect(params.name, 'name');
expect(params.onMessageReceived, onMessageReceived);
});
test('removeJavaScriptChannel', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.removeJavaScriptChannel('channel');
verify(mockPlatformWebViewController.removeJavaScriptChannel('channel'));
});
test('getTitle', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
when(mockPlatformWebViewController.getTitle())
.thenAnswer((_) => Future<String>.value('myTitle'));
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await expectLater(webViewController.getTitle(), completion('myTitle'));
});
test('scrollTo', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.scrollTo(2, 3);
verify(mockPlatformWebViewController.scrollTo(2, 3));
});
test('scrollBy', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.scrollBy(2, 3);
verify(mockPlatformWebViewController.scrollBy(2, 3));
});
test('getScrollPosition', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
when(mockPlatformWebViewController.getScrollPosition()).thenAnswer(
(_) => Future<Offset>.value(const Offset(2, 3)),
);
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await expectLater(
webViewController.getScrollPosition(),
completion(const Offset(2.0, 3.0)),
);
});
test('enableZoom', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.enableZoom(false);
verify(mockPlatformWebViewController.enableZoom(false));
});
test('setBackgroundColor', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.setBackgroundColor(Colors.green);
verify(mockPlatformWebViewController.setBackgroundColor(Colors.green));
});
test('setJavaScriptMode', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.setJavaScriptMode(JavaScriptMode.disabled);
verify(
mockPlatformWebViewController.setJavaScriptMode(JavaScriptMode.disabled),
);
});
test('setUserAgent', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
await webViewController.setUserAgent('userAgent');
verify(mockPlatformWebViewController.setUserAgent('userAgent'));
});
test('setNavigationDelegate', () async {
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController = WebViewController.fromPlatform(
mockPlatformWebViewController,
);
final MockPlatformNavigationDelegate mockPlatformNavigationDelegate =
MockPlatformNavigationDelegate();
final NavigationDelegate navigationDelegate =
NavigationDelegate.fromPlatform(mockPlatformNavigationDelegate);
await webViewController.setNavigationDelegate(navigationDelegate);
verify(mockPlatformWebViewController.setPlatformNavigationDelegate(
mockPlatformNavigationDelegate,
));
});
}
| plugins/packages/webview_flutter/webview_flutter/test/webview_controller_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/test/webview_controller_test.dart",
"repo_id": "plugins",
"token_count": 3785
} | 1,284 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.webkit.DownloadListener;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.DownloadListenerFlutterApi;
/**
* Flutter Api implementation for {@link DownloadListener}.
*
* <p>Passes arguments of callbacks methods from a {@link DownloadListener} to Dart.
*/
public class DownloadListenerFlutterApiImpl extends DownloadListenerFlutterApi {
private final InstanceManager instanceManager;
/**
* Creates a Flutter api that sends messages to Dart.
*
* @param binaryMessenger handles sending messages to Dart
* @param instanceManager maintains instances stored to communicate with Dart objects
*/
public DownloadListenerFlutterApiImpl(
BinaryMessenger binaryMessenger, InstanceManager instanceManager) {
super(binaryMessenger);
this.instanceManager = instanceManager;
}
/** Passes arguments from {@link DownloadListener#onDownloadStart} to Dart. */
public void onDownloadStart(
DownloadListener downloadListener,
String url,
String userAgent,
String contentDisposition,
String mimetype,
long contentLength,
Reply<Void> callback) {
onDownloadStart(
getIdentifierForListener(downloadListener),
url,
userAgent,
contentDisposition,
mimetype,
contentLength,
callback);
}
private long getIdentifierForListener(DownloadListener listener) {
final Long identifier = instanceManager.getIdentifierForStrongReference(listener);
if (identifier == null) {
throw new IllegalStateException("Could not find identifier for DownloadListener.");
}
return identifier;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerFlutterApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerFlutterApiImpl.java",
"repo_id": "plugins",
"token_count": 579
} | 1,285 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.webkit.WebSettings;
import android.webkit.WebView;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebSettingsHostApi;
/**
* Host api implementation for {@link WebSettings}.
*
* <p>Handles creating {@link WebSettings}s that intercommunicate with a paired Dart object.
*/
public class WebSettingsHostApiImpl implements WebSettingsHostApi {
private final InstanceManager instanceManager;
private final WebSettingsCreator webSettingsCreator;
/** Handles creating {@link WebSettings} for a {@link WebSettingsHostApiImpl}. */
public static class WebSettingsCreator {
/**
* Creates a {@link WebSettings}.
*
* @param webView the {@link WebView} which the settings affect
* @return the created {@link WebSettings}
*/
public WebSettings createWebSettings(WebView webView) {
return webView.getSettings();
}
}
/**
* Creates a host API that handles creating {@link WebSettings} and invoke its methods.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param webSettingsCreator handles creating {@link WebSettings}s
*/
public WebSettingsHostApiImpl(
InstanceManager instanceManager, WebSettingsCreator webSettingsCreator) {
this.instanceManager = instanceManager;
this.webSettingsCreator = webSettingsCreator;
}
@Override
public void create(Long instanceId, Long webViewInstanceId) {
final WebView webView = (WebView) instanceManager.getInstance(webViewInstanceId);
instanceManager.addDartCreatedInstance(
webSettingsCreator.createWebSettings(webView), instanceId);
}
@Override
public void setDomStorageEnabled(Long instanceId, Boolean flag) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setDomStorageEnabled(flag);
}
@Override
public void setJavaScriptCanOpenWindowsAutomatically(Long instanceId, Boolean flag) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setJavaScriptCanOpenWindowsAutomatically(flag);
}
@Override
public void setSupportMultipleWindows(Long instanceId, Boolean support) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setSupportMultipleWindows(support);
}
@Override
public void setJavaScriptEnabled(Long instanceId, Boolean flag) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setJavaScriptEnabled(flag);
}
@Override
public void setUserAgentString(Long instanceId, String userAgentString) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setUserAgentString(userAgentString);
}
@Override
public void setMediaPlaybackRequiresUserGesture(Long instanceId, Boolean require) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setMediaPlaybackRequiresUserGesture(require);
}
@Override
public void setSupportZoom(Long instanceId, Boolean support) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setSupportZoom(support);
}
@Override
public void setLoadWithOverviewMode(Long instanceId, Boolean overview) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setLoadWithOverviewMode(overview);
}
@Override
public void setUseWideViewPort(Long instanceId, Boolean use) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setUseWideViewPort(use);
}
@Override
public void setDisplayZoomControls(Long instanceId, Boolean enabled) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setDisplayZoomControls(enabled);
}
@Override
public void setBuiltInZoomControls(Long instanceId, Boolean enabled) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setBuiltInZoomControls(enabled);
}
@Override
public void setAllowFileAccess(Long instanceId, Boolean enabled) {
final WebSettings webSettings = (WebSettings) instanceManager.getInstance(instanceId);
webSettings.setAllowFileAccess(enabled);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebSettingsHostApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebSettingsHostApiImpl.java",
"repo_id": "plugins",
"token_count": 1314
} | 1,286 |
// 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.assertArrayEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.res.AssetManager;
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterAssets;
import io.flutter.plugins.webviewflutter.FlutterAssetManager.PluginBindingFlutterAssetManager;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public class PluginBindingFlutterAssetManagerTest {
@Mock AssetManager mockAssetManager;
@Mock FlutterAssets mockFlutterAssets;
PluginBindingFlutterAssetManager tesPluginBindingFlutterAssetManager;
@Before
public void setUp() {
mockAssetManager = mock(AssetManager.class);
mockFlutterAssets = mock(FlutterAssets.class);
tesPluginBindingFlutterAssetManager =
new PluginBindingFlutterAssetManager(mockAssetManager, mockFlutterAssets);
}
@Test
public void list() {
try {
when(mockAssetManager.list("test/path"))
.thenReturn(new String[] {"index.html", "styles.css"});
String[] actualFilePaths = tesPluginBindingFlutterAssetManager.list("test/path");
verify(mockAssetManager).list("test/path");
assertArrayEquals(new String[] {"index.html", "styles.css"}, actualFilePaths);
} catch (IOException ex) {
fail();
}
}
@Test
public void registrar_getAssetFilePathByName() {
tesPluginBindingFlutterAssetManager.getAssetFilePathByName("sample_movie.mp4");
verify(mockFlutterAssets).getAssetFilePathByName("sample_movie.mp4");
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/PluginBindingFlutterAssetManagerTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/PluginBindingFlutterAssetManagerTest.java",
"repo_id": "plugins",
"token_count": 630
} | 1,287 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutterexample;
import static org.junit.Assert.assertTrue;
import androidx.test.core.app.ActivityScenario;
import io.flutter.plugins.webviewflutter.WebViewFlutterPlugin;
import org.junit.Test;
public class WebViewTest {
@Test
public void webViewPluginIsAdded() {
final ActivityScenario<WebViewTestActivity> scenario =
ActivityScenario.launch(WebViewTestActivity.class);
scenario.onActivity(
activity -> {
assertTrue(activity.engine.getPlugins().has(WebViewFlutterPlugin.class));
});
}
}
| plugins/packages/webview_flutter/webview_flutter_android/example/android/app/src/androidTest/java/io/flutter/plugins/webviewflutterexample/WebViewTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/android/app/src/androidTest/java/io/flutter/plugins/webviewflutterexample/WebViewTest.java",
"repo_id": "plugins",
"token_count": 244
} | 1,288 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:async';
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'android_proxy.dart';
import 'android_webview.dart' as android_webview;
import 'instance_manager.dart';
import 'platform_views_service_proxy.dart';
import 'weak_reference_utils.dart';
/// Object specifying creation parameters for creating a [AndroidWebViewController].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebViewControllerCreationParams] for
/// more information.
@immutable
class AndroidWebViewControllerCreationParams
extends PlatformWebViewControllerCreationParams {
/// Creates a new [AndroidWebViewControllerCreationParams] instance.
AndroidWebViewControllerCreationParams({
@visibleForTesting this.androidWebViewProxy = const AndroidWebViewProxy(),
@visibleForTesting android_webview.WebStorage? androidWebStorage,
}) : androidWebStorage =
androidWebStorage ?? android_webview.WebStorage.instance,
super();
/// Creates a [AndroidWebViewControllerCreationParams] instance based on [PlatformWebViewControllerCreationParams].
factory AndroidWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebViewControllerCreationParams params, {
@visibleForTesting
AndroidWebViewProxy androidWebViewProxy = const AndroidWebViewProxy(),
@visibleForTesting android_webview.WebStorage? androidWebStorage,
}) {
return AndroidWebViewControllerCreationParams(
androidWebViewProxy: androidWebViewProxy,
androidWebStorage:
androidWebStorage ?? android_webview.WebStorage.instance,
);
}
/// Handles constructing objects and calling static methods for the Android WebView
/// native library.
@visibleForTesting
final AndroidWebViewProxy androidWebViewProxy;
/// Manages the JavaScript storage APIs provided by the [android_webview.WebView].
@visibleForTesting
final android_webview.WebStorage androidWebStorage;
}
/// Implementation of the [PlatformWebViewController] with the Android WebView API.
class AndroidWebViewController extends PlatformWebViewController {
/// Creates a new [AndroidWebViewCookieManager].
AndroidWebViewController(PlatformWebViewControllerCreationParams params)
: super.implementation(params is AndroidWebViewControllerCreationParams
? params
: AndroidWebViewControllerCreationParams
.fromPlatformWebViewControllerCreationParams(params)) {
_webView.settings.setDomStorageEnabled(true);
_webView.settings.setJavaScriptCanOpenWindowsAutomatically(true);
_webView.settings.setSupportMultipleWindows(true);
_webView.settings.setLoadWithOverviewMode(true);
_webView.settings.setUseWideViewPort(true);
_webView.settings.setDisplayZoomControls(false);
_webView.settings.setBuiltInZoomControls(true);
_webView.setWebChromeClient(_webChromeClient);
}
AndroidWebViewControllerCreationParams get _androidWebViewParams =>
params as AndroidWebViewControllerCreationParams;
/// The native [android_webview.WebView] being controlled.
late final android_webview.WebView _webView =
_androidWebViewParams.androidWebViewProxy.createAndroidWebView(
// Due to changes in Flutter 3.0 the `useHybridComposition` doesn't have
// any effect and is purposefully not exposed publicly by the
// [AndroidWebViewController]. More info here:
// https://github.com/flutter/flutter/issues/108106
useHybridComposition: true,
);
late final android_webview.WebChromeClient _webChromeClient =
_androidWebViewParams.androidWebViewProxy.createAndroidWebChromeClient(
onProgressChanged: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (android_webview.WebView webView, int progress) {
if (weakReference.target?._currentNavigationDelegate?._onProgress !=
null) {
weakReference
.target!._currentNavigationDelegate!._onProgress!(progress);
}
};
}),
onShowFileChooser: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (android_webview.WebView webView,
android_webview.FileChooserParams params) async {
if (weakReference.target?._onShowFileSelectorCallback != null) {
return weakReference.target!._onShowFileSelectorCallback!(
FileSelectorParams._fromFileChooserParams(params),
);
}
return <String>[];
};
}),
);
/// The native [android_webview.FlutterAssetManager] allows managing assets.
late final android_webview.FlutterAssetManager _flutterAssetManager =
_androidWebViewParams.androidWebViewProxy.createFlutterAssetManager();
final Map<String, AndroidJavaScriptChannelParams> _javaScriptChannelParams =
<String, AndroidJavaScriptChannelParams>{};
AndroidNavigationDelegate? _currentNavigationDelegate;
Future<List<String>> Function(FileSelectorParams)?
_onShowFileSelectorCallback;
/// Whether to enable the platform's webview content debugging tools.
///
/// Defaults to false.
static Future<void> enableDebugging(
bool enabled, {
@visibleForTesting
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(),
}) {
return webViewProxy.setWebContentsDebuggingEnabled(enabled);
}
/// Identifier used to retrieve the underlying native `WKWebView`.
///
/// This is typically used by other plugins to retrieve the native `WebView`
/// from an `InstanceManager`.
///
/// See Java method `WebViewFlutterPlugin.getWebView`.
int get webViewIdentifier =>
// ignore: invalid_use_of_visible_for_testing_member
android_webview.WebView.api.instanceManager.getIdentifier(_webView)!;
@override
Future<void> loadFile(
String absoluteFilePath,
) {
final String url = absoluteFilePath.startsWith('file://')
? absoluteFilePath
: Uri.file(absoluteFilePath).toString();
_webView.settings.setAllowFileAccess(true);
return _webView.loadUrl(url, <String, String>{});
}
@override
Future<void> loadFlutterAsset(
String key,
) async {
final String assetFilePath =
await _flutterAssetManager.getAssetFilePathByName(key);
final List<String> pathElements = assetFilePath.split('/');
final String fileName = pathElements.removeLast();
final List<String?> paths =
await _flutterAssetManager.list(pathElements.join('/'));
if (!paths.contains(fileName)) {
throw ArgumentError(
'Asset for key "$key" not found.',
'key',
);
}
return _webView.loadUrl(
Uri.file('/android_asset/$assetFilePath').toString(),
<String, String>{},
);
}
@override
Future<void> loadHtmlString(
String html, {
String? baseUrl,
}) {
return _webView.loadDataWithBaseUrl(
baseUrl: baseUrl,
data: html,
mimeType: 'text/html',
);
}
@override
Future<void> loadRequest(
LoadRequestParams params,
) {
if (!params.uri.hasScheme) {
throw ArgumentError('WebViewRequest#uri is required to have a scheme.');
}
switch (params.method) {
case LoadRequestMethod.get:
return _webView.loadUrl(params.uri.toString(), params.headers);
case LoadRequestMethod.post:
return _webView.postUrl(
params.uri.toString(), params.body ?? Uint8List(0));
}
// The enum comes from a different package, which could get a new value at
// any time, so a fallback case is necessary. Since there is no reasonable
// default behavior, throw to alert the client that they need an updated
// version. This is deliberately outside the switch rather than a `default`
// so that the linter will flag the switch as needing an update.
// ignore: dead_code
throw UnimplementedError(
'This version of `AndroidWebViewController` currently has no '
'implementation for HTTP method ${params.method.serialize()} in '
'loadRequest.');
}
@override
Future<String?> currentUrl() => _webView.getUrl();
@override
Future<bool> canGoBack() => _webView.canGoBack();
@override
Future<bool> canGoForward() => _webView.canGoForward();
@override
Future<void> goBack() => _webView.goBack();
@override
Future<void> goForward() => _webView.goForward();
@override
Future<void> reload() => _webView.reload();
@override
Future<void> clearCache() => _webView.clearCache(true);
@override
Future<void> clearLocalStorage() =>
_androidWebViewParams.androidWebStorage.deleteAllData();
@override
Future<void> setPlatformNavigationDelegate(
covariant AndroidNavigationDelegate handler) async {
_currentNavigationDelegate = handler;
handler.setOnLoadRequest(loadRequest);
_webView.setWebViewClient(handler.androidWebViewClient);
_webView.setDownloadListener(handler.androidDownloadListener);
}
@override
Future<void> runJavaScript(String javaScript) {
return _webView.evaluateJavascript(javaScript);
}
@override
Future<Object> runJavaScriptReturningResult(String javaScript) async {
final String? result = await _webView.evaluateJavascript(javaScript);
if (result == null) {
return '';
} else if (result == 'true') {
return true;
} else if (result == 'false') {
return false;
}
return num.tryParse(result) ?? result;
}
@override
Future<void> addJavaScriptChannel(
JavaScriptChannelParams javaScriptChannelParams,
) {
final AndroidJavaScriptChannelParams androidJavaScriptParams =
javaScriptChannelParams is AndroidJavaScriptChannelParams
? javaScriptChannelParams
: AndroidJavaScriptChannelParams.fromJavaScriptChannelParams(
javaScriptChannelParams);
// When JavaScript channel with the same name exists make sure to remove it
// before registering the new channel.
if (_javaScriptChannelParams.containsKey(androidJavaScriptParams.name)) {
_webView
.removeJavaScriptChannel(androidJavaScriptParams._javaScriptChannel);
}
_javaScriptChannelParams[androidJavaScriptParams.name] =
androidJavaScriptParams;
return _webView
.addJavaScriptChannel(androidJavaScriptParams._javaScriptChannel);
}
@override
Future<void> removeJavaScriptChannel(String javaScriptChannelName) async {
final AndroidJavaScriptChannelParams? javaScriptChannelParams =
_javaScriptChannelParams[javaScriptChannelName];
if (javaScriptChannelParams == null) {
return;
}
_javaScriptChannelParams.remove(javaScriptChannelName);
return _webView
.removeJavaScriptChannel(javaScriptChannelParams._javaScriptChannel);
}
@override
Future<String?> getTitle() => _webView.getTitle();
@override
Future<void> scrollTo(int x, int y) => _webView.scrollTo(x, y);
@override
Future<void> scrollBy(int x, int y) => _webView.scrollBy(x, y);
@override
Future<Offset> getScrollPosition() {
return _webView.getScrollPosition();
}
@override
Future<void> enableZoom(bool enabled) =>
_webView.settings.setSupportZoom(enabled);
@override
Future<void> setBackgroundColor(Color color) =>
_webView.setBackgroundColor(color);
@override
Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) =>
_webView.settings
.setJavaScriptEnabled(javaScriptMode == JavaScriptMode.unrestricted);
@override
Future<void> setUserAgent(String? userAgent) =>
_webView.settings.setUserAgentString(userAgent);
/// Sets the restrictions that apply on automatic media playback.
Future<void> setMediaPlaybackRequiresUserGesture(bool require) {
return _webView.settings.setMediaPlaybackRequiresUserGesture(require);
}
/// Sets the callback that is invoked when the client should show a file
/// selector.
Future<void> setOnShowFileSelector(
Future<List<String>> Function(FileSelectorParams params)?
onShowFileSelector,
) {
_onShowFileSelectorCallback = onShowFileSelector;
return _webChromeClient.setSynchronousReturnValueForOnShowFileChooser(
onShowFileSelector != null,
);
}
}
/// Mode of how to select files for a file chooser.
enum FileSelectorMode {
/// Open single file and requires that the file exists before allowing the
/// user to pick it.
open,
/// Similar to [open] but allows multiple files to be selected.
openMultiple,
/// Allows picking a nonexistent file and saving it.
save,
}
/// Parameters received when the `WebView` should show a file selector.
@immutable
class FileSelectorParams {
/// Constructs a [FileSelectorParams].
const FileSelectorParams({
required this.isCaptureEnabled,
required this.acceptTypes,
this.filenameHint,
required this.mode,
});
factory FileSelectorParams._fromFileChooserParams(
android_webview.FileChooserParams params,
) {
final FileSelectorMode mode;
switch (params.mode) {
case android_webview.FileChooserMode.open:
mode = FileSelectorMode.open;
break;
case android_webview.FileChooserMode.openMultiple:
mode = FileSelectorMode.openMultiple;
break;
case android_webview.FileChooserMode.save:
mode = FileSelectorMode.save;
break;
}
return FileSelectorParams(
isCaptureEnabled: params.isCaptureEnabled,
acceptTypes: params.acceptTypes,
mode: mode,
filenameHint: params.filenameHint,
);
}
/// Preference for a live media captured value (e.g. Camera, Microphone).
final bool isCaptureEnabled;
/// A list of acceptable MIME types.
final List<String> acceptTypes;
/// The file name of a default selection if specified, or null.
final String? filenameHint;
/// Mode of how to select files for a file selector.
final FileSelectorMode mode;
}
/// An implementation of [JavaScriptChannelParams] with the Android WebView API.
///
/// See [AndroidWebViewController.addJavaScriptChannel].
@immutable
class AndroidJavaScriptChannelParams extends JavaScriptChannelParams {
/// Constructs a [AndroidJavaScriptChannelParams].
AndroidJavaScriptChannelParams({
required super.name,
required super.onMessageReceived,
@visibleForTesting
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(),
}) : assert(name.isNotEmpty),
_javaScriptChannel = webViewProxy.createJavaScriptChannel(
name,
postMessage: withWeakReferenceTo(
onMessageReceived,
(WeakReference<void Function(JavaScriptMessage)> weakReference) {
return (
String message,
) {
if (weakReference.target != null) {
weakReference.target!(
JavaScriptMessage(message: message),
);
}
};
},
),
);
/// Constructs a [AndroidJavaScriptChannelParams] using a
/// [JavaScriptChannelParams].
AndroidJavaScriptChannelParams.fromJavaScriptChannelParams(
JavaScriptChannelParams params, {
@visibleForTesting
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(),
}) : this(
name: params.name,
onMessageReceived: params.onMessageReceived,
webViewProxy: webViewProxy,
);
final android_webview.JavaScriptChannel _javaScriptChannel;
}
/// Object specifying creation parameters for creating a [AndroidWebViewWidget].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebViewWidgetCreationParams] for
/// more information.
@immutable
class AndroidWebViewWidgetCreationParams
extends PlatformWebViewWidgetCreationParams {
/// Creates [AndroidWebWidgetCreationParams].
AndroidWebViewWidgetCreationParams({
super.key,
required super.controller,
super.layoutDirection,
super.gestureRecognizers,
this.displayWithHybridComposition = false,
@visibleForTesting InstanceManager? instanceManager,
@visibleForTesting
this.platformViewsServiceProxy = const PlatformViewsServiceProxy(),
}) : instanceManager =
instanceManager ?? android_webview.JavaObject.globalInstanceManager;
/// Constructs a [WebKitWebViewWidgetCreationParams] using a
/// [PlatformWebViewWidgetCreationParams].
AndroidWebViewWidgetCreationParams.fromPlatformWebViewWidgetCreationParams(
PlatformWebViewWidgetCreationParams params, {
bool displayWithHybridComposition = false,
@visibleForTesting InstanceManager? instanceManager,
@visibleForTesting PlatformViewsServiceProxy platformViewsServiceProxy =
const PlatformViewsServiceProxy(),
}) : this(
key: params.key,
controller: params.controller,
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
displayWithHybridComposition: displayWithHybridComposition,
instanceManager: instanceManager,
platformViewsServiceProxy: platformViewsServiceProxy,
);
/// Maintains instances used to communicate with the native objects they
/// represent.
///
/// This field is exposed for testing purposes only and should not be used
/// outside of tests.
@visibleForTesting
final InstanceManager instanceManager;
/// Proxy that provides access to the platform views service.
///
/// This service allows creating and controlling platform-specific views.
@visibleForTesting
final PlatformViewsServiceProxy platformViewsServiceProxy;
/// Whether the [WebView] will be displayed using the Hybrid Composition
/// PlatformView implementation.
///
/// For most use cases, this flag should be set to false. Hybrid Composition
/// can have performance costs but doesn't have the limitation of rendering to
/// an Android SurfaceTexture. See
/// * https://flutter.dev/docs/development/platform-integration/platform-views#performance
/// * https://github.com/flutter/flutter/issues/104889
/// * https://github.com/flutter/flutter/issues/116954
///
/// Defaults to false.
final bool displayWithHybridComposition;
}
/// An implementation of [PlatformWebViewWidget] with the Android WebView API.
class AndroidWebViewWidget extends PlatformWebViewWidget {
/// Constructs a [WebKitWebViewWidget].
AndroidWebViewWidget(PlatformWebViewWidgetCreationParams params)
: super.implementation(
params is AndroidWebViewWidgetCreationParams
? params
: AndroidWebViewWidgetCreationParams
.fromPlatformWebViewWidgetCreationParams(params),
);
AndroidWebViewWidgetCreationParams get _androidParams =>
params as AndroidWebViewWidgetCreationParams;
@override
Widget build(BuildContext context) {
return PlatformViewLink(
key: _androidParams.key,
viewType: 'plugins.flutter.io/webview',
surfaceFactory: (
BuildContext context,
PlatformViewController controller,
) {
return AndroidViewSurface(
controller: controller as AndroidViewController,
gestureRecognizers: _androidParams.gestureRecognizers,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
);
},
onCreatePlatformView: (PlatformViewCreationParams params) {
return _initAndroidView(
params,
displayWithHybridComposition:
_androidParams.displayWithHybridComposition,
)
..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
..create();
},
);
}
AndroidViewController _initAndroidView(
PlatformViewCreationParams params, {
required bool displayWithHybridComposition,
}) {
if (displayWithHybridComposition) {
return _androidParams.platformViewsServiceProxy.initExpensiveAndroidView(
id: params.id,
viewType: 'plugins.flutter.io/webview',
layoutDirection: _androidParams.layoutDirection,
creationParams: _androidParams.instanceManager.getIdentifier(
(_androidParams.controller as AndroidWebViewController)._webView),
creationParamsCodec: const StandardMessageCodec(),
);
} else {
return _androidParams.platformViewsServiceProxy.initSurfaceAndroidView(
id: params.id,
viewType: 'plugins.flutter.io/webview',
layoutDirection: _androidParams.layoutDirection,
creationParams: _androidParams.instanceManager.getIdentifier(
(_androidParams.controller as AndroidWebViewController)._webView),
creationParamsCodec: const StandardMessageCodec(),
);
}
}
}
/// Signature for the `loadRequest` callback responsible for loading the [url]
/// after a navigation request has been approved.
typedef LoadRequestCallback = Future<void> Function(LoadRequestParams params);
/// Error returned in `WebView.onWebResourceError` when a web resource loading error has occurred.
@immutable
class AndroidWebResourceError extends WebResourceError {
/// Creates a new [AndroidWebResourceError].
AndroidWebResourceError._({
required super.errorCode,
required super.description,
super.isForMainFrame,
this.failingUrl,
}) : super(
errorType: _errorCodeToErrorType(errorCode),
);
/// Gets the URL for which the failing resource request was made.
final String? failingUrl;
static WebResourceErrorType? _errorCodeToErrorType(int errorCode) {
switch (errorCode) {
case android_webview.WebViewClient.errorAuthentication:
return WebResourceErrorType.authentication;
case android_webview.WebViewClient.errorBadUrl:
return WebResourceErrorType.badUrl;
case android_webview.WebViewClient.errorConnect:
return WebResourceErrorType.connect;
case android_webview.WebViewClient.errorFailedSslHandshake:
return WebResourceErrorType.failedSslHandshake;
case android_webview.WebViewClient.errorFile:
return WebResourceErrorType.file;
case android_webview.WebViewClient.errorFileNotFound:
return WebResourceErrorType.fileNotFound;
case android_webview.WebViewClient.errorHostLookup:
return WebResourceErrorType.hostLookup;
case android_webview.WebViewClient.errorIO:
return WebResourceErrorType.io;
case android_webview.WebViewClient.errorProxyAuthentication:
return WebResourceErrorType.proxyAuthentication;
case android_webview.WebViewClient.errorRedirectLoop:
return WebResourceErrorType.redirectLoop;
case android_webview.WebViewClient.errorTimeout:
return WebResourceErrorType.timeout;
case android_webview.WebViewClient.errorTooManyRequests:
return WebResourceErrorType.tooManyRequests;
case android_webview.WebViewClient.errorUnknown:
return WebResourceErrorType.unknown;
case android_webview.WebViewClient.errorUnsafeResource:
return WebResourceErrorType.unsafeResource;
case android_webview.WebViewClient.errorUnsupportedAuthScheme:
return WebResourceErrorType.unsupportedAuthScheme;
case android_webview.WebViewClient.errorUnsupportedScheme:
return WebResourceErrorType.unsupportedScheme;
}
throw ArgumentError(
'Could not find a WebResourceErrorType for errorCode: $errorCode',
);
}
}
/// Object specifying creation parameters for creating a [AndroidNavigationDelegate].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformNavigationDelegateCreationParams] for
/// more information.
@immutable
class AndroidNavigationDelegateCreationParams
extends PlatformNavigationDelegateCreationParams {
/// Creates a new [AndroidNavigationDelegateCreationParams] instance.
const AndroidNavigationDelegateCreationParams._({
@visibleForTesting this.androidWebViewProxy = const AndroidWebViewProxy(),
}) : super();
/// Creates a [AndroidNavigationDelegateCreationParams] instance based on [PlatformNavigationDelegateCreationParams].
factory AndroidNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformNavigationDelegateCreationParams params, {
@visibleForTesting
AndroidWebViewProxy androidWebViewProxy = const AndroidWebViewProxy(),
}) {
return AndroidNavigationDelegateCreationParams._(
androidWebViewProxy: androidWebViewProxy,
);
}
/// Handles constructing objects and calling static methods for the Android WebView
/// native library.
@visibleForTesting
final AndroidWebViewProxy androidWebViewProxy;
}
/// A place to register callback methods responsible to handle navigation events
/// triggered by the [android_webview.WebView].
class AndroidNavigationDelegate extends PlatformNavigationDelegate {
/// Creates a new [AndroidNavigationDelegate].
AndroidNavigationDelegate(PlatformNavigationDelegateCreationParams params)
: super.implementation(params is AndroidNavigationDelegateCreationParams
? params
: AndroidNavigationDelegateCreationParams
.fromPlatformNavigationDelegateCreationParams(params)) {
final WeakReference<AndroidNavigationDelegate> weakThis =
WeakReference<AndroidNavigationDelegate>(this);
_webViewClient = (this.params as AndroidNavigationDelegateCreationParams)
.androidWebViewProxy
.createAndroidWebViewClient(
onPageFinished: (android_webview.WebView webView, String url) {
if (weakThis.target?._onPageFinished != null) {
weakThis.target!._onPageFinished!(url);
}
},
onPageStarted: (android_webview.WebView webView, String url) {
if (weakThis.target?._onPageStarted != null) {
weakThis.target!._onPageStarted!(url);
}
},
onReceivedRequestError: (
android_webview.WebView webView,
android_webview.WebResourceRequest request,
android_webview.WebResourceError error,
) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(AndroidWebResourceError._(
errorCode: error.errorCode,
description: error.description,
failingUrl: request.url,
isForMainFrame: request.isForMainFrame,
));
}
},
onReceivedError: (
android_webview.WebView webView,
int errorCode,
String description,
String failingUrl,
) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(AndroidWebResourceError._(
errorCode: errorCode,
description: description,
failingUrl: failingUrl,
isForMainFrame: true,
));
}
},
requestLoading: (
android_webview.WebView webView,
android_webview.WebResourceRequest request,
) {
if (weakThis.target != null) {
weakThis.target!._handleNavigation(
request.url,
headers: request.requestHeaders,
isForMainFrame: request.isForMainFrame,
);
}
},
urlLoading: (
android_webview.WebView webView,
String url,
) {
if (weakThis.target != null) {
weakThis.target!._handleNavigation(url, isForMainFrame: true);
}
},
);
_downloadListener = (this.params as AndroidNavigationDelegateCreationParams)
.androidWebViewProxy
.createDownloadListener(
onDownloadStart: (
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
) {
if (weakThis.target != null) {
weakThis.target?._handleNavigation(url, isForMainFrame: true);
}
},
);
}
AndroidNavigationDelegateCreationParams get _androidParams =>
params as AndroidNavigationDelegateCreationParams;
late final android_webview.WebChromeClient _webChromeClient =
_androidParams.androidWebViewProxy.createAndroidWebChromeClient();
/// Gets the native [android_webview.WebChromeClient] that is bridged by this [AndroidNavigationDelegate].
///
/// Used by the [AndroidWebViewController] to set the `android_webview.WebView.setWebChromeClient`.
@Deprecated(
'This value is not used by `AndroidWebViewController` and has no effect on the `WebView`.',
)
android_webview.WebChromeClient get androidWebChromeClient =>
_webChromeClient;
late final android_webview.WebViewClient _webViewClient;
/// Gets the native [android_webview.WebViewClient] that is bridged by this [AndroidNavigationDelegate].
///
/// Used by the [AndroidWebViewController] to set the `android_webview.WebView.setWebViewClient`.
android_webview.WebViewClient get androidWebViewClient => _webViewClient;
late final android_webview.DownloadListener _downloadListener;
/// Gets the native [android_webview.DownloadListener] that is bridged by this [AndroidNavigationDelegate].
///
/// Used by the [AndroidWebViewController] to set the `android_webview.WebView.setDownloadListener`.
android_webview.DownloadListener get androidDownloadListener =>
_downloadListener;
PageEventCallback? _onPageFinished;
PageEventCallback? _onPageStarted;
ProgressCallback? _onProgress;
WebResourceErrorCallback? _onWebResourceError;
NavigationRequestCallback? _onNavigationRequest;
LoadRequestCallback? _onLoadRequest;
void _handleNavigation(
String url, {
required bool isForMainFrame,
Map<String, String> headers = const <String, String>{},
}) {
final LoadRequestCallback? onLoadRequest = _onLoadRequest;
final NavigationRequestCallback? onNavigationRequest = _onNavigationRequest;
if (onNavigationRequest == null || onLoadRequest == null) {
return;
}
final FutureOr<NavigationDecision> returnValue = onNavigationRequest(
NavigationRequest(
url: url,
isMainFrame: isForMainFrame,
),
);
if (returnValue is NavigationDecision &&
returnValue == NavigationDecision.navigate) {
onLoadRequest(LoadRequestParams(
uri: Uri.parse(url),
headers: headers,
));
} else if (returnValue is Future<NavigationDecision>) {
returnValue.then((NavigationDecision shouldLoadUrl) {
if (shouldLoadUrl == NavigationDecision.navigate) {
onLoadRequest(LoadRequestParams(
uri: Uri.parse(url),
headers: headers,
));
}
});
}
}
/// Invoked when loading the url after a navigation request is approved.
Future<void> setOnLoadRequest(
LoadRequestCallback onLoadRequest,
) async {
_onLoadRequest = onLoadRequest;
}
@override
Future<void> setOnNavigationRequest(
NavigationRequestCallback onNavigationRequest,
) async {
_onNavigationRequest = onNavigationRequest;
_webViewClient.setSynchronousReturnValueForShouldOverrideUrlLoading(true);
}
@override
Future<void> setOnPageStarted(
PageEventCallback onPageStarted,
) async {
_onPageStarted = onPageStarted;
}
@override
Future<void> setOnPageFinished(
PageEventCallback onPageFinished,
) async {
_onPageFinished = onPageFinished;
}
@override
Future<void> setOnProgress(
ProgressCallback onProgress,
) async {
_onProgress = onProgress;
}
@override
Future<void> setOnWebResourceError(
WebResourceErrorCallback onWebResourceError,
) async {
_onWebResourceError = onWebResourceError;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart",
"repo_id": "plugins",
"token_count": 11135
} | 1,289 |
// Mocks generated by Mockito 5.3.2 from annotations
// in webview_flutter_android/test/android_webview_controller_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i9;
import 'dart:typed_data' as _i14;
import 'dart:ui' as _i4;
import 'package:flutter/foundation.dart' as _i11;
import 'package:flutter/gestures.dart' as _i12;
import 'package:flutter/material.dart' as _i13;
import 'package:flutter/services.dart' as _i7;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_android/src/android_proxy.dart' as _i10;
import 'package:webview_flutter_android/src/android_webview.dart' as _i2;
import 'package:webview_flutter_android/src/android_webview_controller.dart'
as _i8;
import 'package:webview_flutter_android/src/instance_manager.dart' as _i5;
import 'package:webview_flutter_android/src/platform_views_service_proxy.dart'
as _i6;
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'
as _i3;
// 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 _FakeWebChromeClient_0 extends _i1.SmartFake
implements _i2.WebChromeClient {
_FakeWebChromeClient_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebViewClient_1 extends _i1.SmartFake implements _i2.WebViewClient {
_FakeWebViewClient_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeDownloadListener_2 extends _i1.SmartFake
implements _i2.DownloadListener {
_FakeDownloadListener_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePlatformNavigationDelegateCreationParams_3 extends _i1.SmartFake
implements _i3.PlatformNavigationDelegateCreationParams {
_FakePlatformNavigationDelegateCreationParams_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePlatformWebViewControllerCreationParams_4 extends _i1.SmartFake
implements _i3.PlatformWebViewControllerCreationParams {
_FakePlatformWebViewControllerCreationParams_4(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeObject_5 extends _i1.SmartFake implements Object {
_FakeObject_5(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeOffset_6 extends _i1.SmartFake implements _i4.Offset {
_FakeOffset_6(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebView_7 extends _i1.SmartFake implements _i2.WebView {
_FakeWebView_7(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeFlutterAssetManager_8 extends _i1.SmartFake
implements _i2.FlutterAssetManager {
_FakeFlutterAssetManager_8(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeJavaScriptChannel_9 extends _i1.SmartFake
implements _i2.JavaScriptChannel {
_FakeJavaScriptChannel_9(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeInstanceManager_10 extends _i1.SmartFake
implements _i5.InstanceManager {
_FakeInstanceManager_10(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePlatformViewsServiceProxy_11 extends _i1.SmartFake
implements _i6.PlatformViewsServiceProxy {
_FakePlatformViewsServiceProxy_11(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePlatformWebViewController_12 extends _i1.SmartFake
implements _i3.PlatformWebViewController {
_FakePlatformWebViewController_12(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeSize_13 extends _i1.SmartFake implements _i4.Size {
_FakeSize_13(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeExpensiveAndroidViewController_14 extends _i1.SmartFake
implements _i7.ExpensiveAndroidViewController {
_FakeExpensiveAndroidViewController_14(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeSurfaceAndroidViewController_15 extends _i1.SmartFake
implements _i7.SurfaceAndroidViewController {
_FakeSurfaceAndroidViewController_15(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebSettings_16 extends _i1.SmartFake implements _i2.WebSettings {
_FakeWebSettings_16(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebStorage_17 extends _i1.SmartFake implements _i2.WebStorage {
_FakeWebStorage_17(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [AndroidNavigationDelegate].
///
/// See the documentation for Mockito's code generation for more information.
class MockAndroidNavigationDelegate extends _i1.Mock
implements _i8.AndroidNavigationDelegate {
@override
_i2.WebChromeClient get androidWebChromeClient => (super.noSuchMethod(
Invocation.getter(#androidWebChromeClient),
returnValue: _FakeWebChromeClient_0(
this,
Invocation.getter(#androidWebChromeClient),
),
returnValueForMissingStub: _FakeWebChromeClient_0(
this,
Invocation.getter(#androidWebChromeClient),
),
) as _i2.WebChromeClient);
@override
_i2.WebViewClient get androidWebViewClient => (super.noSuchMethod(
Invocation.getter(#androidWebViewClient),
returnValue: _FakeWebViewClient_1(
this,
Invocation.getter(#androidWebViewClient),
),
returnValueForMissingStub: _FakeWebViewClient_1(
this,
Invocation.getter(#androidWebViewClient),
),
) as _i2.WebViewClient);
@override
_i2.DownloadListener get androidDownloadListener => (super.noSuchMethod(
Invocation.getter(#androidDownloadListener),
returnValue: _FakeDownloadListener_2(
this,
Invocation.getter(#androidDownloadListener),
),
returnValueForMissingStub: _FakeDownloadListener_2(
this,
Invocation.getter(#androidDownloadListener),
),
) as _i2.DownloadListener);
@override
_i3.PlatformNavigationDelegateCreationParams get params =>
(super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformNavigationDelegateCreationParams_3(
this,
Invocation.getter(#params),
),
returnValueForMissingStub:
_FakePlatformNavigationDelegateCreationParams_3(
this,
Invocation.getter(#params),
),
) as _i3.PlatformNavigationDelegateCreationParams);
@override
_i9.Future<void> setOnLoadRequest(_i8.LoadRequestCallback? onLoadRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnLoadRequest,
[onLoadRequest],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setOnNavigationRequest(
_i3.NavigationRequestCallback? onNavigationRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnNavigationRequest,
[onNavigationRequest],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setOnPageStarted(_i3.PageEventCallback? onPageStarted) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageStarted,
[onPageStarted],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setOnPageFinished(_i3.PageEventCallback? onPageFinished) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageFinished,
[onPageFinished],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setOnProgress(_i3.ProgressCallback? onProgress) =>
(super.noSuchMethod(
Invocation.method(
#setOnProgress,
[onProgress],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setOnWebResourceError(
_i3.WebResourceErrorCallback? onWebResourceError) =>
(super.noSuchMethod(
Invocation.method(
#setOnWebResourceError,
[onWebResourceError],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
}
/// A class which mocks [AndroidWebViewController].
///
/// See the documentation for Mockito's code generation for more information.
class MockAndroidWebViewController extends _i1.Mock
implements _i8.AndroidWebViewController {
@override
_i3.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformWebViewControllerCreationParams_4(
this,
Invocation.getter(#params),
),
returnValueForMissingStub:
_FakePlatformWebViewControllerCreationParams_4(
this,
Invocation.getter(#params),
),
) as _i3.PlatformWebViewControllerCreationParams);
@override
_i9.Future<void> loadFile(String? absoluteFilePath) => (super.noSuchMethod(
Invocation.method(
#loadFile,
[absoluteFilePath],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod(
Invocation.method(
#loadFlutterAsset,
[key],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> loadHtmlString(
String? html, {
String? baseUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadHtmlString,
[html],
{#baseUrl: baseUrl},
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> loadRequest(_i3.LoadRequestParams? params) =>
(super.noSuchMethod(
Invocation.method(
#loadRequest,
[params],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<String?> currentUrl() => (super.noSuchMethod(
Invocation.method(
#currentUrl,
[],
),
returnValue: _i9.Future<String?>.value(),
returnValueForMissingStub: _i9.Future<String?>.value(),
) as _i9.Future<String?>);
@override
_i9.Future<bool> canGoBack() => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[],
),
returnValue: _i9.Future<bool>.value(false),
returnValueForMissingStub: _i9.Future<bool>.value(false),
) as _i9.Future<bool>);
@override
_i9.Future<bool> canGoForward() => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[],
),
returnValue: _i9.Future<bool>.value(false),
returnValueForMissingStub: _i9.Future<bool>.value(false),
) as _i9.Future<bool>);
@override
_i9.Future<void> goBack() => (super.noSuchMethod(
Invocation.method(
#goBack,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> goForward() => (super.noSuchMethod(
Invocation.method(
#goForward,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> clearCache() => (super.noSuchMethod(
Invocation.method(
#clearCache,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> clearLocalStorage() => (super.noSuchMethod(
Invocation.method(
#clearLocalStorage,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setPlatformNavigationDelegate(
_i3.PlatformNavigationDelegate? handler) =>
(super.noSuchMethod(
Invocation.method(
#setPlatformNavigationDelegate,
[handler],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> runJavaScript(String? javaScript) => (super.noSuchMethod(
Invocation.method(
#runJavaScript,
[javaScript],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<Object> runJavaScriptReturningResult(String? javaScript) =>
(super.noSuchMethod(
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
returnValue: _i9.Future<Object>.value(_FakeObject_5(
this,
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
)),
returnValueForMissingStub: _i9.Future<Object>.value(_FakeObject_5(
this,
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
)),
) as _i9.Future<Object>);
@override
_i9.Future<void> addJavaScriptChannel(
_i3.JavaScriptChannelParams? javaScriptChannelParams) =>
(super.noSuchMethod(
Invocation.method(
#addJavaScriptChannel,
[javaScriptChannelParams],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> removeJavaScriptChannel(String? javaScriptChannelName) =>
(super.noSuchMethod(
Invocation.method(
#removeJavaScriptChannel,
[javaScriptChannelName],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<String?> getTitle() => (super.noSuchMethod(
Invocation.method(
#getTitle,
[],
),
returnValue: _i9.Future<String?>.value(),
returnValueForMissingStub: _i9.Future<String?>.value(),
) as _i9.Future<String?>);
@override
_i9.Future<void> scrollTo(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollTo,
[
x,
y,
],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> scrollBy(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollBy,
[
x,
y,
],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod(
Invocation.method(
#getScrollPosition,
[],
),
returnValue: _i9.Future<_i4.Offset>.value(_FakeOffset_6(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
returnValueForMissingStub: _i9.Future<_i4.Offset>.value(_FakeOffset_6(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
) as _i9.Future<_i4.Offset>);
@override
_i9.Future<void> enableZoom(bool? enabled) => (super.noSuchMethod(
Invocation.method(
#enableZoom,
[enabled],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setBackgroundColor(_i4.Color? color) => (super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[color],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setJavaScriptMode(_i3.JavaScriptMode? javaScriptMode) =>
(super.noSuchMethod(
Invocation.method(
#setJavaScriptMode,
[javaScriptMode],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setUserAgent(String? userAgent) => (super.noSuchMethod(
Invocation.method(
#setUserAgent,
[userAgent],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setMediaPlaybackRequiresUserGesture(bool? require) =>
(super.noSuchMethod(
Invocation.method(
#setMediaPlaybackRequiresUserGesture,
[require],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setOnShowFileSelector(
_i9.Future<List<String>> Function(_i8.FileSelectorParams)?
onShowFileSelectorCallback) =>
(super.noSuchMethod(
Invocation.method(
#setOnShowFileSelector,
[onShowFileSelectorCallback],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
}
/// A class which mocks [AndroidWebViewProxy].
///
/// See the documentation for Mockito's code generation for more information.
class MockAndroidWebViewProxy extends _i1.Mock
implements _i10.AndroidWebViewProxy {
@override
_i2.WebView Function({required bool useHybridComposition})
get createAndroidWebView => (super.noSuchMethod(
Invocation.getter(#createAndroidWebView),
returnValue: ({required bool useHybridComposition}) =>
_FakeWebView_7(
this,
Invocation.getter(#createAndroidWebView),
),
returnValueForMissingStub: ({required bool useHybridComposition}) =>
_FakeWebView_7(
this,
Invocation.getter(#createAndroidWebView),
),
) as _i2.WebView Function({required bool useHybridComposition}));
@override
_i2.WebChromeClient Function({
void Function(
_i2.WebView,
int,
)?
onProgressChanged,
_i9.Future<List<String>> Function(
_i2.WebView,
_i2.FileChooserParams,
)?
onShowFileChooser,
}) get createAndroidWebChromeClient => (super.noSuchMethod(
Invocation.getter(#createAndroidWebChromeClient),
returnValue: ({
void Function(
_i2.WebView,
int,
)?
onProgressChanged,
_i9.Future<List<String>> Function(
_i2.WebView,
_i2.FileChooserParams,
)?
onShowFileChooser,
}) =>
_FakeWebChromeClient_0(
this,
Invocation.getter(#createAndroidWebChromeClient),
),
returnValueForMissingStub: ({
void Function(
_i2.WebView,
int,
)?
onProgressChanged,
_i9.Future<List<String>> Function(
_i2.WebView,
_i2.FileChooserParams,
)?
onShowFileChooser,
}) =>
_FakeWebChromeClient_0(
this,
Invocation.getter(#createAndroidWebChromeClient),
),
) as _i2.WebChromeClient Function({
void Function(
_i2.WebView,
int,
)?
onProgressChanged,
_i9.Future<List<String>> Function(
_i2.WebView,
_i2.FileChooserParams,
)?
onShowFileChooser,
}));
@override
_i2.WebViewClient Function({
void Function(
_i2.WebView,
String,
)?
onPageFinished,
void Function(
_i2.WebView,
String,
)?
onPageStarted,
void Function(
_i2.WebView,
int,
String,
String,
)?
onReceivedError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
_i2.WebResourceError,
)?
onReceivedRequestError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
)?
requestLoading,
void Function(
_i2.WebView,
String,
)?
urlLoading,
}) get createAndroidWebViewClient => (super.noSuchMethod(
Invocation.getter(#createAndroidWebViewClient),
returnValue: ({
void Function(
_i2.WebView,
String,
)?
onPageFinished,
void Function(
_i2.WebView,
String,
)?
onPageStarted,
void Function(
_i2.WebView,
int,
String,
String,
)?
onReceivedError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
_i2.WebResourceError,
)?
onReceivedRequestError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
)?
requestLoading,
void Function(
_i2.WebView,
String,
)?
urlLoading,
}) =>
_FakeWebViewClient_1(
this,
Invocation.getter(#createAndroidWebViewClient),
),
returnValueForMissingStub: ({
void Function(
_i2.WebView,
String,
)?
onPageFinished,
void Function(
_i2.WebView,
String,
)?
onPageStarted,
void Function(
_i2.WebView,
int,
String,
String,
)?
onReceivedError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
_i2.WebResourceError,
)?
onReceivedRequestError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
)?
requestLoading,
void Function(
_i2.WebView,
String,
)?
urlLoading,
}) =>
_FakeWebViewClient_1(
this,
Invocation.getter(#createAndroidWebViewClient),
),
) as _i2.WebViewClient Function({
void Function(
_i2.WebView,
String,
)?
onPageFinished,
void Function(
_i2.WebView,
String,
)?
onPageStarted,
void Function(
_i2.WebView,
int,
String,
String,
)?
onReceivedError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
_i2.WebResourceError,
)?
onReceivedRequestError,
void Function(
_i2.WebView,
_i2.WebResourceRequest,
)?
requestLoading,
void Function(
_i2.WebView,
String,
)?
urlLoading,
}));
@override
_i2.FlutterAssetManager Function() get createFlutterAssetManager =>
(super.noSuchMethod(
Invocation.getter(#createFlutterAssetManager),
returnValue: () => _FakeFlutterAssetManager_8(
this,
Invocation.getter(#createFlutterAssetManager),
),
returnValueForMissingStub: () => _FakeFlutterAssetManager_8(
this,
Invocation.getter(#createFlutterAssetManager),
),
) as _i2.FlutterAssetManager Function());
@override
_i2.JavaScriptChannel Function(
String, {
required void Function(String) postMessage,
}) get createJavaScriptChannel => (super.noSuchMethod(
Invocation.getter(#createJavaScriptChannel),
returnValue: (
String channelName, {
required void Function(String) postMessage,
}) =>
_FakeJavaScriptChannel_9(
this,
Invocation.getter(#createJavaScriptChannel),
),
returnValueForMissingStub: (
String channelName, {
required void Function(String) postMessage,
}) =>
_FakeJavaScriptChannel_9(
this,
Invocation.getter(#createJavaScriptChannel),
),
) as _i2.JavaScriptChannel Function(
String, {
required void Function(String) postMessage,
}));
@override
_i2.DownloadListener Function(
{required void Function(
String,
String,
String,
String,
int,
)
onDownloadStart}) get createDownloadListener => (super.noSuchMethod(
Invocation.getter(#createDownloadListener),
returnValue: (
{required void Function(
String,
String,
String,
String,
int,
)
onDownloadStart}) =>
_FakeDownloadListener_2(
this,
Invocation.getter(#createDownloadListener),
),
returnValueForMissingStub: (
{required void Function(
String,
String,
String,
String,
int,
)
onDownloadStart}) =>
_FakeDownloadListener_2(
this,
Invocation.getter(#createDownloadListener),
),
) as _i2.DownloadListener Function(
{required void Function(
String,
String,
String,
String,
int,
)
onDownloadStart}));
@override
_i9.Future<void> setWebContentsDebuggingEnabled(bool? enabled) =>
(super.noSuchMethod(
Invocation.method(
#setWebContentsDebuggingEnabled,
[enabled],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
}
/// A class which mocks [AndroidWebViewWidgetCreationParams].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockAndroidWebViewWidgetCreationParams extends _i1.Mock
implements _i8.AndroidWebViewWidgetCreationParams {
@override
_i5.InstanceManager get instanceManager => (super.noSuchMethod(
Invocation.getter(#instanceManager),
returnValue: _FakeInstanceManager_10(
this,
Invocation.getter(#instanceManager),
),
returnValueForMissingStub: _FakeInstanceManager_10(
this,
Invocation.getter(#instanceManager),
),
) as _i5.InstanceManager);
@override
_i6.PlatformViewsServiceProxy get platformViewsServiceProxy =>
(super.noSuchMethod(
Invocation.getter(#platformViewsServiceProxy),
returnValue: _FakePlatformViewsServiceProxy_11(
this,
Invocation.getter(#platformViewsServiceProxy),
),
returnValueForMissingStub: _FakePlatformViewsServiceProxy_11(
this,
Invocation.getter(#platformViewsServiceProxy),
),
) as _i6.PlatformViewsServiceProxy);
@override
bool get displayWithHybridComposition => (super.noSuchMethod(
Invocation.getter(#displayWithHybridComposition),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i3.PlatformWebViewController get controller => (super.noSuchMethod(
Invocation.getter(#controller),
returnValue: _FakePlatformWebViewController_12(
this,
Invocation.getter(#controller),
),
returnValueForMissingStub: _FakePlatformWebViewController_12(
this,
Invocation.getter(#controller),
),
) as _i3.PlatformWebViewController);
@override
_i4.TextDirection get layoutDirection => (super.noSuchMethod(
Invocation.getter(#layoutDirection),
returnValue: _i4.TextDirection.rtl,
returnValueForMissingStub: _i4.TextDirection.rtl,
) as _i4.TextDirection);
@override
Set<_i11.Factory<_i12.OneSequenceGestureRecognizer>> get gestureRecognizers =>
(super.noSuchMethod(
Invocation.getter(#gestureRecognizers),
returnValue: <_i11.Factory<_i12.OneSequenceGestureRecognizer>>{},
returnValueForMissingStub: <
_i11.Factory<_i12.OneSequenceGestureRecognizer>>{},
) as Set<_i11.Factory<_i12.OneSequenceGestureRecognizer>>);
}
/// A class which mocks [ExpensiveAndroidViewController].
///
/// See the documentation for Mockito's code generation for more information.
class MockExpensiveAndroidViewController extends _i1.Mock
implements _i7.ExpensiveAndroidViewController {
@override
bool get requiresViewComposition => (super.noSuchMethod(
Invocation.getter(#requiresViewComposition),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
int get viewId => (super.noSuchMethod(
Invocation.getter(#viewId),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
bool get awaitingCreation => (super.noSuchMethod(
Invocation.getter(#awaitingCreation),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i7.PointTransformer get pointTransformer => (super.noSuchMethod(
Invocation.getter(#pointTransformer),
returnValue: (_i4.Offset position) => _FakeOffset_6(
this,
Invocation.getter(#pointTransformer),
),
returnValueForMissingStub: (_i4.Offset position) => _FakeOffset_6(
this,
Invocation.getter(#pointTransformer),
),
) as _i7.PointTransformer);
@override
set pointTransformer(_i7.PointTransformer? transformer) => super.noSuchMethod(
Invocation.setter(
#pointTransformer,
transformer,
),
returnValueForMissingStub: null,
);
@override
bool get isCreated => (super.noSuchMethod(
Invocation.getter(#isCreated),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
List<_i7.PlatformViewCreatedCallback> get createdCallbacks =>
(super.noSuchMethod(
Invocation.getter(#createdCallbacks),
returnValue: <_i7.PlatformViewCreatedCallback>[],
returnValueForMissingStub: <_i7.PlatformViewCreatedCallback>[],
) as List<_i7.PlatformViewCreatedCallback>);
@override
_i9.Future<void> setOffset(_i4.Offset? off) => (super.noSuchMethod(
Invocation.method(
#setOffset,
[off],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> create({
_i4.Size? size,
_i4.Offset? position,
}) =>
(super.noSuchMethod(
Invocation.method(
#create,
[],
{
#size: size,
#position: position,
},
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<_i4.Size> setSize(_i4.Size? size) => (super.noSuchMethod(
Invocation.method(
#setSize,
[size],
),
returnValue: _i9.Future<_i4.Size>.value(_FakeSize_13(
this,
Invocation.method(
#setSize,
[size],
),
)),
returnValueForMissingStub: _i9.Future<_i4.Size>.value(_FakeSize_13(
this,
Invocation.method(
#setSize,
[size],
),
)),
) as _i9.Future<_i4.Size>);
@override
_i9.Future<void> sendMotionEvent(_i7.AndroidMotionEvent? event) =>
(super.noSuchMethod(
Invocation.method(
#sendMotionEvent,
[event],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
void addOnPlatformViewCreatedListener(
_i7.PlatformViewCreatedCallback? listener) =>
super.noSuchMethod(
Invocation.method(
#addOnPlatformViewCreatedListener,
[listener],
),
returnValueForMissingStub: null,
);
@override
void removeOnPlatformViewCreatedListener(
_i7.PlatformViewCreatedCallback? listener) =>
super.noSuchMethod(
Invocation.method(
#removeOnPlatformViewCreatedListener,
[listener],
),
returnValueForMissingStub: null,
);
@override
_i9.Future<void> setLayoutDirection(_i4.TextDirection? layoutDirection) =>
(super.noSuchMethod(
Invocation.method(
#setLayoutDirection,
[layoutDirection],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> dispatchPointerEvent(_i13.PointerEvent? event) =>
(super.noSuchMethod(
Invocation.method(
#dispatchPointerEvent,
[event],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> clearFocus() => (super.noSuchMethod(
Invocation.method(
#clearFocus,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> dispose() => (super.noSuchMethod(
Invocation.method(
#dispose,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
}
/// A class which mocks [FlutterAssetManager].
///
/// See the documentation for Mockito's code generation for more information.
class MockFlutterAssetManager extends _i1.Mock
implements _i2.FlutterAssetManager {
@override
_i9.Future<List<String?>> list(String? path) => (super.noSuchMethod(
Invocation.method(
#list,
[path],
),
returnValue: _i9.Future<List<String?>>.value(<String?>[]),
returnValueForMissingStub: _i9.Future<List<String?>>.value(<String?>[]),
) as _i9.Future<List<String?>>);
@override
_i9.Future<String> getAssetFilePathByName(String? name) =>
(super.noSuchMethod(
Invocation.method(
#getAssetFilePathByName,
[name],
),
returnValue: _i9.Future<String>.value(''),
returnValueForMissingStub: _i9.Future<String>.value(''),
) as _i9.Future<String>);
}
/// A class which mocks [JavaScriptChannel].
///
/// See the documentation for Mockito's code generation for more information.
class MockJavaScriptChannel extends _i1.Mock implements _i2.JavaScriptChannel {
@override
String get channelName => (super.noSuchMethod(
Invocation.getter(#channelName),
returnValue: '',
returnValueForMissingStub: '',
) as String);
@override
void Function(String) get postMessage => (super.noSuchMethod(
Invocation.getter(#postMessage),
returnValue: (String message) {},
returnValueForMissingStub: (String message) {},
) as void Function(String));
@override
_i2.JavaScriptChannel copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeJavaScriptChannel_9(
this,
Invocation.method(
#copy,
[],
),
),
returnValueForMissingStub: _FakeJavaScriptChannel_9(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.JavaScriptChannel);
}
/// A class which mocks [PlatformViewsServiceProxy].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockPlatformViewsServiceProxy extends _i1.Mock
implements _i6.PlatformViewsServiceProxy {
@override
_i7.ExpensiveAndroidViewController initExpensiveAndroidView({
required int? id,
required String? viewType,
required _i4.TextDirection? layoutDirection,
dynamic creationParams,
_i7.MessageCodec<dynamic>? creationParamsCodec,
_i4.VoidCallback? onFocus,
}) =>
(super.noSuchMethod(
Invocation.method(
#initExpensiveAndroidView,
[],
{
#id: id,
#viewType: viewType,
#layoutDirection: layoutDirection,
#creationParams: creationParams,
#creationParamsCodec: creationParamsCodec,
#onFocus: onFocus,
},
),
returnValue: _FakeExpensiveAndroidViewController_14(
this,
Invocation.method(
#initExpensiveAndroidView,
[],
{
#id: id,
#viewType: viewType,
#layoutDirection: layoutDirection,
#creationParams: creationParams,
#creationParamsCodec: creationParamsCodec,
#onFocus: onFocus,
},
),
),
returnValueForMissingStub: _FakeExpensiveAndroidViewController_14(
this,
Invocation.method(
#initExpensiveAndroidView,
[],
{
#id: id,
#viewType: viewType,
#layoutDirection: layoutDirection,
#creationParams: creationParams,
#creationParamsCodec: creationParamsCodec,
#onFocus: onFocus,
},
),
),
) as _i7.ExpensiveAndroidViewController);
@override
_i7.SurfaceAndroidViewController initSurfaceAndroidView({
required int? id,
required String? viewType,
required _i4.TextDirection? layoutDirection,
dynamic creationParams,
_i7.MessageCodec<dynamic>? creationParamsCodec,
_i4.VoidCallback? onFocus,
}) =>
(super.noSuchMethod(
Invocation.method(
#initSurfaceAndroidView,
[],
{
#id: id,
#viewType: viewType,
#layoutDirection: layoutDirection,
#creationParams: creationParams,
#creationParamsCodec: creationParamsCodec,
#onFocus: onFocus,
},
),
returnValue: _FakeSurfaceAndroidViewController_15(
this,
Invocation.method(
#initSurfaceAndroidView,
[],
{
#id: id,
#viewType: viewType,
#layoutDirection: layoutDirection,
#creationParams: creationParams,
#creationParamsCodec: creationParamsCodec,
#onFocus: onFocus,
},
),
),
returnValueForMissingStub: _FakeSurfaceAndroidViewController_15(
this,
Invocation.method(
#initSurfaceAndroidView,
[],
{
#id: id,
#viewType: viewType,
#layoutDirection: layoutDirection,
#creationParams: creationParams,
#creationParamsCodec: creationParamsCodec,
#onFocus: onFocus,
},
),
),
) as _i7.SurfaceAndroidViewController);
}
/// A class which mocks [SurfaceAndroidViewController].
///
/// See the documentation for Mockito's code generation for more information.
class MockSurfaceAndroidViewController extends _i1.Mock
implements _i7.SurfaceAndroidViewController {
@override
bool get requiresViewComposition => (super.noSuchMethod(
Invocation.getter(#requiresViewComposition),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
int get viewId => (super.noSuchMethod(
Invocation.getter(#viewId),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
bool get awaitingCreation => (super.noSuchMethod(
Invocation.getter(#awaitingCreation),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i7.PointTransformer get pointTransformer => (super.noSuchMethod(
Invocation.getter(#pointTransformer),
returnValue: (_i4.Offset position) => _FakeOffset_6(
this,
Invocation.getter(#pointTransformer),
),
returnValueForMissingStub: (_i4.Offset position) => _FakeOffset_6(
this,
Invocation.getter(#pointTransformer),
),
) as _i7.PointTransformer);
@override
set pointTransformer(_i7.PointTransformer? transformer) => super.noSuchMethod(
Invocation.setter(
#pointTransformer,
transformer,
),
returnValueForMissingStub: null,
);
@override
bool get isCreated => (super.noSuchMethod(
Invocation.getter(#isCreated),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
List<_i7.PlatformViewCreatedCallback> get createdCallbacks =>
(super.noSuchMethod(
Invocation.getter(#createdCallbacks),
returnValue: <_i7.PlatformViewCreatedCallback>[],
returnValueForMissingStub: <_i7.PlatformViewCreatedCallback>[],
) as List<_i7.PlatformViewCreatedCallback>);
@override
_i9.Future<void> setOffset(_i4.Offset? off) => (super.noSuchMethod(
Invocation.method(
#setOffset,
[off],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> create({
_i4.Size? size,
_i4.Offset? position,
}) =>
(super.noSuchMethod(
Invocation.method(
#create,
[],
{
#size: size,
#position: position,
},
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<_i4.Size> setSize(_i4.Size? size) => (super.noSuchMethod(
Invocation.method(
#setSize,
[size],
),
returnValue: _i9.Future<_i4.Size>.value(_FakeSize_13(
this,
Invocation.method(
#setSize,
[size],
),
)),
returnValueForMissingStub: _i9.Future<_i4.Size>.value(_FakeSize_13(
this,
Invocation.method(
#setSize,
[size],
),
)),
) as _i9.Future<_i4.Size>);
@override
_i9.Future<void> sendMotionEvent(_i7.AndroidMotionEvent? event) =>
(super.noSuchMethod(
Invocation.method(
#sendMotionEvent,
[event],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
void addOnPlatformViewCreatedListener(
_i7.PlatformViewCreatedCallback? listener) =>
super.noSuchMethod(
Invocation.method(
#addOnPlatformViewCreatedListener,
[listener],
),
returnValueForMissingStub: null,
);
@override
void removeOnPlatformViewCreatedListener(
_i7.PlatformViewCreatedCallback? listener) =>
super.noSuchMethod(
Invocation.method(
#removeOnPlatformViewCreatedListener,
[listener],
),
returnValueForMissingStub: null,
);
@override
_i9.Future<void> setLayoutDirection(_i4.TextDirection? layoutDirection) =>
(super.noSuchMethod(
Invocation.method(
#setLayoutDirection,
[layoutDirection],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> dispatchPointerEvent(_i13.PointerEvent? event) =>
(super.noSuchMethod(
Invocation.method(
#dispatchPointerEvent,
[event],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> clearFocus() => (super.noSuchMethod(
Invocation.method(
#clearFocus,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> dispose() => (super.noSuchMethod(
Invocation.method(
#dispose,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
}
/// A class which mocks [WebChromeClient].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient {
@override
_i9.Future<void> setSynchronousReturnValueForOnShowFileChooser(bool? value) =>
(super.noSuchMethod(
Invocation.method(
#setSynchronousReturnValueForOnShowFileChooser,
[value],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i2.WebChromeClient copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebChromeClient_0(
this,
Invocation.method(
#copy,
[],
),
),
returnValueForMissingStub: _FakeWebChromeClient_0(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebChromeClient);
}
/// A class which mocks [WebSettings].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebSettings extends _i1.Mock implements _i2.WebSettings {
@override
_i9.Future<void> setDomStorageEnabled(bool? flag) => (super.noSuchMethod(
Invocation.method(
#setDomStorageEnabled,
[flag],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setJavaScriptCanOpenWindowsAutomatically(bool? flag) =>
(super.noSuchMethod(
Invocation.method(
#setJavaScriptCanOpenWindowsAutomatically,
[flag],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setSupportMultipleWindows(bool? support) =>
(super.noSuchMethod(
Invocation.method(
#setSupportMultipleWindows,
[support],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setJavaScriptEnabled(bool? flag) => (super.noSuchMethod(
Invocation.method(
#setJavaScriptEnabled,
[flag],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setUserAgentString(String? userAgentString) =>
(super.noSuchMethod(
Invocation.method(
#setUserAgentString,
[userAgentString],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setMediaPlaybackRequiresUserGesture(bool? require) =>
(super.noSuchMethod(
Invocation.method(
#setMediaPlaybackRequiresUserGesture,
[require],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setSupportZoom(bool? support) => (super.noSuchMethod(
Invocation.method(
#setSupportZoom,
[support],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setLoadWithOverviewMode(bool? overview) =>
(super.noSuchMethod(
Invocation.method(
#setLoadWithOverviewMode,
[overview],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setUseWideViewPort(bool? use) => (super.noSuchMethod(
Invocation.method(
#setUseWideViewPort,
[use],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setDisplayZoomControls(bool? enabled) => (super.noSuchMethod(
Invocation.method(
#setDisplayZoomControls,
[enabled],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setBuiltInZoomControls(bool? enabled) => (super.noSuchMethod(
Invocation.method(
#setBuiltInZoomControls,
[enabled],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setAllowFileAccess(bool? enabled) => (super.noSuchMethod(
Invocation.method(
#setAllowFileAccess,
[enabled],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i2.WebSettings copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebSettings_16(
this,
Invocation.method(
#copy,
[],
),
),
returnValueForMissingStub: _FakeWebSettings_16(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebSettings);
}
/// A class which mocks [WebView].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebView extends _i1.Mock implements _i2.WebView {
@override
bool get useHybridComposition => (super.noSuchMethod(
Invocation.getter(#useHybridComposition),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i2.WebSettings get settings => (super.noSuchMethod(
Invocation.getter(#settings),
returnValue: _FakeWebSettings_16(
this,
Invocation.getter(#settings),
),
returnValueForMissingStub: _FakeWebSettings_16(
this,
Invocation.getter(#settings),
),
) as _i2.WebSettings);
@override
_i9.Future<void> loadData({
required String? data,
String? mimeType,
String? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadData,
[],
{
#data: data,
#mimeType: mimeType,
#encoding: encoding,
},
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> loadDataWithBaseUrl({
String? baseUrl,
required String? data,
String? mimeType,
String? encoding,
String? historyUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadDataWithBaseUrl,
[],
{
#baseUrl: baseUrl,
#data: data,
#mimeType: mimeType,
#encoding: encoding,
#historyUrl: historyUrl,
},
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> loadUrl(
String? url,
Map<String, String>? headers,
) =>
(super.noSuchMethod(
Invocation.method(
#loadUrl,
[
url,
headers,
],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> postUrl(
String? url,
_i14.Uint8List? data,
) =>
(super.noSuchMethod(
Invocation.method(
#postUrl,
[
url,
data,
],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<String?> getUrl() => (super.noSuchMethod(
Invocation.method(
#getUrl,
[],
),
returnValue: _i9.Future<String?>.value(),
returnValueForMissingStub: _i9.Future<String?>.value(),
) as _i9.Future<String?>);
@override
_i9.Future<bool> canGoBack() => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[],
),
returnValue: _i9.Future<bool>.value(false),
returnValueForMissingStub: _i9.Future<bool>.value(false),
) as _i9.Future<bool>);
@override
_i9.Future<bool> canGoForward() => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[],
),
returnValue: _i9.Future<bool>.value(false),
returnValueForMissingStub: _i9.Future<bool>.value(false),
) as _i9.Future<bool>);
@override
_i9.Future<void> goBack() => (super.noSuchMethod(
Invocation.method(
#goBack,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> goForward() => (super.noSuchMethod(
Invocation.method(
#goForward,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> clearCache(bool? includeDiskFiles) => (super.noSuchMethod(
Invocation.method(
#clearCache,
[includeDiskFiles],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<String?> evaluateJavascript(String? javascriptString) =>
(super.noSuchMethod(
Invocation.method(
#evaluateJavascript,
[javascriptString],
),
returnValue: _i9.Future<String?>.value(),
returnValueForMissingStub: _i9.Future<String?>.value(),
) as _i9.Future<String?>);
@override
_i9.Future<String?> getTitle() => (super.noSuchMethod(
Invocation.method(
#getTitle,
[],
),
returnValue: _i9.Future<String?>.value(),
returnValueForMissingStub: _i9.Future<String?>.value(),
) as _i9.Future<String?>);
@override
_i9.Future<void> scrollTo(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollTo,
[
x,
y,
],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> scrollBy(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollBy,
[
x,
y,
],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<int> getScrollX() => (super.noSuchMethod(
Invocation.method(
#getScrollX,
[],
),
returnValue: _i9.Future<int>.value(0),
returnValueForMissingStub: _i9.Future<int>.value(0),
) as _i9.Future<int>);
@override
_i9.Future<int> getScrollY() => (super.noSuchMethod(
Invocation.method(
#getScrollY,
[],
),
returnValue: _i9.Future<int>.value(0),
returnValueForMissingStub: _i9.Future<int>.value(0),
) as _i9.Future<int>);
@override
_i9.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod(
Invocation.method(
#getScrollPosition,
[],
),
returnValue: _i9.Future<_i4.Offset>.value(_FakeOffset_6(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
returnValueForMissingStub: _i9.Future<_i4.Offset>.value(_FakeOffset_6(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
) as _i9.Future<_i4.Offset>);
@override
_i9.Future<void> setWebViewClient(_i2.WebViewClient? webViewClient) =>
(super.noSuchMethod(
Invocation.method(
#setWebViewClient,
[webViewClient],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> addJavaScriptChannel(
_i2.JavaScriptChannel? javaScriptChannel) =>
(super.noSuchMethod(
Invocation.method(
#addJavaScriptChannel,
[javaScriptChannel],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> removeJavaScriptChannel(
_i2.JavaScriptChannel? javaScriptChannel) =>
(super.noSuchMethod(
Invocation.method(
#removeJavaScriptChannel,
[javaScriptChannel],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setDownloadListener(_i2.DownloadListener? listener) =>
(super.noSuchMethod(
Invocation.method(
#setDownloadListener,
[listener],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setWebChromeClient(_i2.WebChromeClient? client) =>
(super.noSuchMethod(
Invocation.method(
#setWebChromeClient,
[client],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i9.Future<void> setBackgroundColor(_i4.Color? color) => (super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[color],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i2.WebView copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebView_7(
this,
Invocation.method(
#copy,
[],
),
),
returnValueForMissingStub: _FakeWebView_7(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebView);
}
/// A class which mocks [WebViewClient].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient {
@override
_i9.Future<void> setSynchronousReturnValueForShouldOverrideUrlLoading(
bool? value) =>
(super.noSuchMethod(
Invocation.method(
#setSynchronousReturnValueForShouldOverrideUrlLoading,
[value],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i2.WebViewClient copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebViewClient_1(
this,
Invocation.method(
#copy,
[],
),
),
returnValueForMissingStub: _FakeWebViewClient_1(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebViewClient);
}
/// A class which mocks [WebStorage].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebStorage extends _i1.Mock implements _i2.WebStorage {
@override
_i9.Future<void> deleteAllData() => (super.noSuchMethod(
Invocation.method(
#deleteAllData,
[],
),
returnValue: _i9.Future<void>.value(),
returnValueForMissingStub: _i9.Future<void>.value(),
) as _i9.Future<void>);
@override
_i2.WebStorage copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebStorage_17(
this,
Invocation.method(
#copy,
[],
),
),
returnValueForMissingStub: _FakeWebStorage_17(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebStorage);
}
/// A class which mocks [InstanceManager].
///
/// See the documentation for Mockito's code generation for more information.
class MockInstanceManager extends _i1.Mock implements _i5.InstanceManager {
@override
void Function(int) get onWeakReferenceRemoved => (super.noSuchMethod(
Invocation.getter(#onWeakReferenceRemoved),
returnValue: (int __p0) {},
returnValueForMissingStub: (int __p0) {},
) as void Function(int));
@override
set onWeakReferenceRemoved(void Function(int)? _onWeakReferenceRemoved) =>
super.noSuchMethod(
Invocation.setter(
#onWeakReferenceRemoved,
_onWeakReferenceRemoved,
),
returnValueForMissingStub: null,
);
@override
int addDartCreatedInstance(_i5.Copyable? instance) => (super.noSuchMethod(
Invocation.method(
#addDartCreatedInstance,
[instance],
),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
int? removeWeakReference(_i5.Copyable? instance) => (super.noSuchMethod(
Invocation.method(
#removeWeakReference,
[instance],
),
returnValueForMissingStub: null,
) as int?);
@override
T? remove<T extends _i5.Copyable>(int? identifier) => (super.noSuchMethod(
Invocation.method(
#remove,
[identifier],
),
returnValueForMissingStub: null,
) as T?);
@override
T? getInstanceWithWeakReference<T extends _i5.Copyable>(int? identifier) =>
(super.noSuchMethod(
Invocation.method(
#getInstanceWithWeakReference,
[identifier],
),
returnValueForMissingStub: null,
) as T?);
@override
int? getIdentifier(_i5.Copyable? instance) => (super.noSuchMethod(
Invocation.method(
#getIdentifier,
[instance],
),
returnValueForMissingStub: null,
) as int?);
@override
void addHostCreatedInstance(
_i5.Copyable? instance,
int? identifier,
) =>
super.noSuchMethod(
Invocation.method(
#addHostCreatedInstance,
[
instance,
identifier,
],
),
returnValueForMissingStub: null,
);
@override
bool containsIdentifier(int? identifier) => (super.noSuchMethod(
Invocation.method(
#containsIdentifier,
[identifier],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
}
| plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart",
"repo_id": "plugins",
"token_count": 32096
} | 1,290 |
// 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 '../types/javascript_channel.dart';
import '../types/javascript_message.dart';
/// Utility class for managing named JavaScript channels and forwarding incoming
/// messages on the correct channel.
class JavascriptChannelRegistry {
/// Constructs a [JavascriptChannelRegistry] initializing it with the given
/// set of [JavascriptChannel]s.
JavascriptChannelRegistry(Set<JavascriptChannel>? channels) {
updateJavascriptChannelsFromSet(channels);
}
/// Maps a channel name to a channel.
final Map<String, JavascriptChannel> channels = <String, JavascriptChannel>{};
/// Invoked when a JavaScript channel message is received.
void onJavascriptChannelMessage(String channel, String message) {
final JavascriptChannel? javascriptChannel = channels[channel];
if (javascriptChannel == null) {
throw ArgumentError('No channel registered with name $channel.');
}
javascriptChannel.onMessageReceived(JavascriptMessage(message));
}
/// Updates the set of [JavascriptChannel]s with the new set.
void updateJavascriptChannelsFromSet(Set<JavascriptChannel>? channels) {
this.channels.clear();
if (channels == null) {
return;
}
for (final JavascriptChannel channel in channels) {
this.channels[channel.name] = channel;
}
}
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/javascript_channel_registry.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/javascript_channel_registry.dart",
"repo_id": "plugins",
"token_count": 411
} | 1,291 |
// 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:typed_data';
/// Defines the supported HTTP methods for loading a page in [WebView].
enum WebViewRequestMethod {
/// HTTP GET method.
get,
/// HTTP POST method.
post,
}
/// Extension methods on the [WebViewRequestMethod] enum.
extension WebViewRequestMethodExtensions on WebViewRequestMethod {
/// Converts [WebViewRequestMethod] to [String] format.
String serialize() {
switch (this) {
case WebViewRequestMethod.get:
return 'get';
case WebViewRequestMethod.post:
return 'post';
}
}
}
/// Defines the parameters that can be used to load a page in the [WebView].
class WebViewRequest {
/// Creates the [WebViewRequest].
WebViewRequest({
required this.uri,
required this.method,
this.headers = const <String, String>{},
this.body,
});
/// URI for the request.
final Uri uri;
/// HTTP method used to make the request.
final WebViewRequestMethod method;
/// Headers for the request.
final Map<String, String> headers;
/// HTTP body for the request.
final Uint8List? body;
/// Serializes the [WebViewRequest] to JSON.
Map<String, dynamic> toJson() => <String, dynamic>{
'uri': uri.toString(),
'method': method.serialize(),
'headers': headers,
'body': body,
};
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_request.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_request.dart",
"repo_id": "plugins",
"token_count": 491
} | 1,292 |
// 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';
/// A cookie that can be set globally for all web views using [WebViewCookieManagerPlatform].
@immutable
class WebViewCookie {
/// Creates a new [WebViewCookieDelegate]
const WebViewCookie({
required this.name,
required this.value,
required this.domain,
this.path = '/',
});
/// The cookie-name of the cookie.
///
/// Its value should match "cookie-name" in RFC6265bis:
/// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1
final String name;
/// The cookie-value of the cookie.
///
/// Its value should match "cookie-value" in RFC6265bis:
/// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1
final String value;
/// The domain-value of the cookie.
///
/// Its value should match "domain-value" in RFC6265bis:
/// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1
final String domain;
/// The path-value of the cookie, set to `/` by default.
///
/// Its value should match "path-value" in RFC6265bis:
/// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1
final String path;
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_cookie.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_cookie.dart",
"repo_id": "plugins",
"token_count": 482
} | 1,293 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This test is run using `flutter drive` by the CI (see /script/tool/README.md
// in this repository for details on driving that tooling manually), but can
// also be run using `flutter test` directly during development.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart';
import 'package:webview_flutter_wkwebview/src/common/weak_reference_utils.dart';
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
Future<void> main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0);
server.forEach((HttpRequest request) {
if (request.uri.path == '/hello.txt') {
request.response.writeln('Hello, world.');
} else if (request.uri.path == '/secondary.txt') {
request.response.writeln('How are you today?');
} else if (request.uri.path == '/headers') {
request.response.writeln('${request.headers}');
} else if (request.uri.path == '/favicon.ico') {
request.response.statusCode = HttpStatus.notFound;
} else {
fail('unexpected request: ${request.method} ${request.uri}');
}
request.response.close();
});
final String prefixUrl = 'http://${server.address.address}:${server.port}';
final String primaryUrl = '$prefixUrl/hello.txt';
final String secondaryUrl = '$prefixUrl/secondary.txt';
final String headersUrl = '$prefixUrl/headers';
testWidgets(
'withWeakReferenceTo allows encapsulating class to be garbage collected',
(WidgetTester tester) async {
final Completer<int> gcCompleter = Completer<int>();
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: gcCompleter.complete,
);
ClassWithCallbackClass? instance = ClassWithCallbackClass();
instanceManager.addHostCreatedInstance(instance.callbackClass, 0);
instance = null;
// Force garbage collection.
await IntegrationTestWidgetsFlutterBinding.instance
.watchPerformance(() async {
await tester.pumpAndSettle();
});
final int gcIdentifier = await gcCompleter.future;
expect(gcIdentifier, 0);
}, timeout: const Timeout(Duration(seconds: 10)));
testWidgets(
'WKWebView is released by garbage collection',
(WidgetTester tester) async {
final Completer<void> webViewGCCompleter = Completer<void>();
late final InstanceManager instanceManager;
instanceManager =
InstanceManager(onWeakReferenceRemoved: (int identifier) {
final Copyable instance =
instanceManager.getInstanceWithWeakReference(identifier)!;
if (instance is WKWebView && !webViewGCCompleter.isCompleted) {
webViewGCCompleter.complete();
}
});
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
WebKitWebViewWidgetCreationParams(
instanceManager: instanceManager,
controller: PlatformWebViewController(
WebKitWebViewControllerCreationParams(
instanceManager: instanceManager,
),
),
),
).build(context);
},
),
);
await tester.pumpAndSettle();
await tester.pumpWidget(Container());
// Force garbage collection.
await IntegrationTestWidgetsFlutterBinding.instance
.watchPerformance(() async {
await tester.pumpAndSettle();
});
await expectLater(webViewGCCompleter.future, completes);
},
timeout: const Timeout(Duration(seconds: 10)),
);
testWidgets('loadRequest', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageFinished.complete()),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageFinished.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets('runJavaScriptReturningResult', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageFinished.complete()),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageFinished.future;
await expectLater(
controller.runJavaScriptReturningResult('1 + 1'),
completion(2),
);
});
testWidgets('loadRequest with headers', (WidgetTester tester) async {
final Map<String, String> headers = <String, String>{
'test_header': 'flutter_test_header'
};
final StreamController<String> pageLoads = StreamController<String>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((String url) => pageLoads.add(url)),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(headersUrl),
headers: headers,
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoads.stream.firstWhere((String url) => url == headersUrl);
final String content = await controller.runJavaScriptReturningResult(
'document.documentElement.innerText',
) as String;
expect(content.contains('flutter_test_header'), isTrue);
});
testWidgets('JavascriptChannel', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageFinished.complete()),
);
final Completer<String> channelCompleter = Completer<String>();
await controller.addJavaScriptChannel(
JavaScriptChannelParams(
name: 'Echo',
onMessageReceived: (JavaScriptMessage message) {
channelCompleter.complete(message.message);
},
),
);
controller.loadHtmlString(
'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageFinished.future;
await controller.runJavaScript('Echo.postMessage("hello");');
await expectLater(channelCompleter.future, completion('hello'));
});
testWidgets('resize webview', (WidgetTester tester) async {
final Completer<void> buttonTapResizeCompleter = Completer<void>();
final Completer<void> onPageFinished = Completer<void>();
bool resizeButtonTapped = false;
await tester.pumpWidget(ResizableWebView(
onResize: () {
if (resizeButtonTapped) {
buttonTapResizeCompleter.complete();
}
},
onPageFinished: () => onPageFinished.complete(),
));
await onPageFinished.future;
resizeButtonTapped = true;
await tester.tap(find.byKey(const ValueKey<String>('resizeButton')));
await tester.pumpAndSettle();
await expectLater(buttonTapResizeCompleter.future, completes);
});
testWidgets('set custom userAgent', (WidgetTester tester) async {
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setUserAgent('Custom_User_Agent1');
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
final String customUserAgent2 = await _getUserAgent(controller);
expect(customUserAgent2, 'Custom_User_Agent1');
});
group('Video playback policy', () {
late String videoTestBase64;
setUpAll(() async {
final ByteData videoData =
await rootBundle.load('assets/sample_video.mp4');
final String base64VideoData =
base64Encode(Uint8List.view(videoData.buffer));
final String videoTest = '''
<!DOCTYPE html><html>
<head><title>Video auto play</title>
<script type="text/javascript">
function play() {
var video = document.getElementById("video");
video.play();
video.addEventListener('timeupdate', videoTimeUpdateHandler, false);
}
function videoTimeUpdateHandler(e) {
var video = document.getElementById("video");
VideoTestTime.postMessage(video.currentTime);
}
function isPaused() {
var video = document.getElementById("video");
return video.paused;
}
function isFullScreen() {
var video = document.getElementById("video");
return video.webkitDisplayingFullscreen;
}
</script>
</head>
<body onload="play();">
<video controls playsinline autoplay id="video">
<source src="data:video/mp4;charset=utf-8;base64,$base64VideoData">
</video>
</body>
</html>
''';
videoTestBase64 = base64Encode(const Utf8Encoder().convert(videoTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
bool isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, false);
pageLoaded = Completer<void>();
controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, true);
});
testWidgets('Video plays inline when allowsInlineMediaPlayback is true',
(WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final Completer<void> videoPlaying = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
allowsInlineMediaPlayback: true,
),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..addJavaScriptChannel(
JavaScriptChannelParams(
name: 'VideoTestTime',
onMessageReceived: (JavaScriptMessage message) {
final double currentTime = double.parse(message.message);
// Let it play for at least 1 second to make sure the related video's properties are set.
if (currentTime > 1 && !videoPlaying.isCompleted) {
videoPlaying.complete(null);
}
},
),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await tester.pumpAndSettle();
await pageLoaded.future;
// Makes sure we get the correct event that indicates the video is actually playing.
await videoPlaying.future;
final bool fullScreen = await controller
.runJavaScriptReturningResult('isFullScreen();') as bool;
expect(fullScreen, false);
});
testWidgets(
'Video plays full screen when allowsInlineMediaPlayback is false',
(WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final Completer<void> videoPlaying = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..addJavaScriptChannel(
JavaScriptChannelParams(
name: 'VideoTestTime',
onMessageReceived: (JavaScriptMessage message) {
final double currentTime = double.parse(message.message);
// Let it play for at least 1 second to make sure the related video's properties are set.
if (currentTime > 1 && !videoPlaying.isCompleted) {
videoPlaying.complete(null);
}
},
),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await tester.pumpAndSettle();
await pageLoaded.future;
// Makes sure we get the correct event that indicates the video is actually playing.
await videoPlaying.future;
final bool fullScreen = await controller
.runJavaScriptReturningResult('isFullScreen();') as bool;
expect(fullScreen, true);
});
});
group('Audio playback policy', () {
late String audioTestBase64;
setUpAll(() async {
final ByteData audioData =
await rootBundle.load('assets/sample_audio.ogg');
final String base64AudioData =
base64Encode(Uint8List.view(audioData.buffer));
final String audioTest = '''
<!DOCTYPE html><html>
<head><title>Audio auto play</title>
<script type="text/javascript">
function play() {
var audio = document.getElementById("audio");
audio.play();
}
function isPaused() {
var audio = document.getElementById("audio");
return audio.paused;
}
</script>
</head>
<body onload="play();">
<audio controls id="audio">
<source src="data:audio/ogg;charset=utf-8;base64,$base64AudioData">
</audio>
</body>
</html>
''';
audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$audioTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
bool isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, false);
pageLoaded = Completer<void>();
controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$audioTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, true);
});
});
testWidgets('getTitle', (WidgetTester tester) async {
const String getTitleTest = '''
<!DOCTYPE html><html>
<head><title>Some title</title>
</head>
<body>
</body>
</html>
''';
final String getTitleTestBase64 =
base64Encode(const Utf8Encoder().convert(getTitleTest));
final Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$getTitleTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
// On at least iOS, it does not appear to be guaranteed that the native
// code has the title when the page load completes. Execute some JavaScript
// before checking the title to ensure that the page has been fully parsed
// and processed.
await controller.runJavaScript('1;');
final String? title = await controller.getTitle();
expect(title, 'Some title');
});
group('Programmatic Scroll', () {
testWidgets('setAndGetScrollPosition', (WidgetTester tester) async {
const String scrollTestPage = '''
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 100%;
width: 100%;
}
#container{
width:5000px;
height:5000px;
}
</style>
</head>
<body>
<div id="container"/>
</body>
</html>
''';
final String scrollTestPageBase64 =
base64Encode(const Utf8Encoder().convert(scrollTestPage));
final Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$scrollTestPageBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
await tester.pumpAndSettle(const Duration(seconds: 3));
Offset scrollPos = await controller.getScrollPosition();
// Check scrollTo()
const int X_SCROLL = 123;
const int Y_SCROLL = 321;
// Get the initial position; this ensures that scrollTo is actually
// changing something, but also gives the native view's scroll position
// time to settle.
expect(scrollPos.dx, isNot(X_SCROLL));
expect(scrollPos.dy, isNot(Y_SCROLL));
await controller.scrollTo(X_SCROLL, Y_SCROLL);
scrollPos = await controller.getScrollPosition();
expect(scrollPos.dx, X_SCROLL);
expect(scrollPos.dy, Y_SCROLL);
// Check scrollBy() (on top of scrollTo())
await controller.scrollBy(X_SCROLL, Y_SCROLL);
scrollPos = await controller.getScrollPosition();
expect(scrollPos.dx, X_SCROLL * 2);
expect(scrollPos.dy, Y_SCROLL * 2);
});
});
group('NavigationDelegate', () {
const String blankPage = '<!DOCTYPE html><head></head><body></body></html>';
final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,'
'${base64Encode(const Utf8Encoder().convert(blankPage))}';
testWidgets('can allow requests', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageLoaded.complete())
..setOnNavigationRequest((NavigationRequest navigationRequest) {
return (navigationRequest.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
}),
)
..loadRequest(
LoadRequestParams(uri: Uri.parse(blankPageEncoded)),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller.runJavaScript('location.href = "$secondaryUrl"');
await pageLoaded.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
testWidgets('onWebResourceError', (WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnWebResourceError((WebResourceError error) {
errorCompleter.complete(error);
}),
)
..loadRequest(
LoadRequestParams(uri: Uri.parse('https://www.notawebsite..com')),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
final WebResourceError error = await errorCompleter.future;
expect(error, isNotNull);
expect((error as WebKitWebResourceError).domain, isNotNull);
});
testWidgets('onWebResourceError is not called with valid url',
(WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final Completer<void> pageFinishCompleter = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageFinishCompleter.complete())
..setOnWebResourceError((WebResourceError error) {
errorCompleter.complete(error);
}),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
expect(errorCompleter.future, doesNotComplete);
await pageFinishCompleter.future;
});
testWidgets(
'onWebResourceError only called for main frame',
(WidgetTester tester) async {
const String iframeTest = '''
<!DOCTYPE html>
<html>
<head>
<title>WebResourceError test</title>
</head>
<body>
<iframe src="https://notawebsite..com"></iframe>
</body>
</html>
''';
final String iframeTestBase64 =
base64Encode(const Utf8Encoder().convert(iframeTest));
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final Completer<void> pageFinishCompleter = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageFinishCompleter.complete())
..setOnWebResourceError((WebResourceError error) {
errorCompleter.complete(error);
}),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$iframeTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
expect(errorCompleter.future, doesNotComplete);
await pageFinishCompleter.future;
},
);
testWidgets('can block requests', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageLoaded.complete())
..setOnNavigationRequest((NavigationRequest navigationRequest) {
return (navigationRequest.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
}),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(blankPageEncoded)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller
.runJavaScript('location.href = "https://www.youtube.com/"');
// There should never be any second page load, since our new URL is
// blocked. Still wait for a potential page change for some time in order
// to give the test a chance to fail.
await pageLoaded.future
.timeout(const Duration(milliseconds: 500), onTimeout: () => '');
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, isNot(contains('youtube.com')));
});
testWidgets('supports asynchronous decisions', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageLoaded.complete())
..setOnNavigationRequest(
(NavigationRequest navigationRequest) async {
NavigationDecision decision = NavigationDecision.prevent;
decision = await Future<NavigationDecision>.delayed(
const Duration(milliseconds: 10),
() => NavigationDecision.navigate);
return decision;
}),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(blankPageEncoded)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller.runJavaScript('location.href = "$secondaryUrl"');
await pageLoaded.future; // Wait for second page to load.
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
});
testWidgets('launches with gestureNavigationEnabled on iOS',
(WidgetTester tester) async {
final WebKitWebViewController controller = WebKitWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setAllowsBackForwardNavigationGestures(true)
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets('target _blank opens in same window',
(WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()));
await controller.runJavaScript('window.open("$primaryUrl", "_blank")');
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets(
'can open new window and go back',
(WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
WebKitWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()))
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
expect(controller.currentUrl(), completion(primaryUrl));
await pageLoaded.future;
pageLoaded = Completer<void>();
await controller.runJavaScript('window.open("$secondaryUrl")');
await pageLoaded.future;
pageLoaded = Completer<void>();
expect(controller.currentUrl(), completion(secondaryUrl));
expect(controller.canGoBack(), completion(true));
await controller.goBack();
await pageLoaded.future;
await expectLater(controller.currentUrl(), completion(primaryUrl));
},
);
}
/// Returns the value used for the HTTP User-Agent: request header in subsequent HTTP requests.
Future<String> _getUserAgent(PlatformWebViewController controller) async {
return await controller.runJavaScriptReturningResult('navigator.userAgent;')
as String;
}
class ResizableWebView extends StatefulWidget {
const ResizableWebView({
Key? key,
required this.onResize,
required this.onPageFinished,
}) : super(key: key);
final VoidCallback onResize;
final VoidCallback onPageFinished;
@override
State<StatefulWidget> createState() => ResizableWebViewState();
}
class ResizableWebViewState extends State<ResizableWebView> {
late final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => widget.onPageFinished()),
)
..addJavaScriptChannel(
JavaScriptChannelParams(
name: 'Resize',
onMessageReceived: (_) {
widget.onResize();
},
),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,${base64Encode(const Utf8Encoder().convert(resizePage))}',
),
),
);
double webViewWidth = 200;
double webViewHeight = 200;
static const String resizePage = '''
<!DOCTYPE html><html>
<head><title>Resize test</title>
<script type="text/javascript">
function onResize() {
Resize.postMessage("resize");
}
function onLoad() {
window.onresize = onResize;
}
</script>
</head>
<body onload="onLoad();" bgColor="blue">
</body>
</html>
''';
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
SizedBox(
width: webViewWidth,
height: webViewHeight,
child: PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context),
),
TextButton(
key: const Key('resizeButton'),
onPressed: () {
setState(() {
webViewWidth += 100.0;
webViewHeight += 100.0;
});
},
child: const Text('ResizeButton'),
),
],
),
);
}
}
class CopyableObjectWithCallback with Copyable {
CopyableObjectWithCallback(this.callback);
final VoidCallback callback;
@override
CopyableObjectWithCallback copy() {
return CopyableObjectWithCallback(callback);
}
}
class ClassWithCallbackClass {
ClassWithCallbackClass() {
callbackClass = CopyableObjectWithCallback(
withWeakRefenceTo(
this,
(WeakReference<ClassWithCallbackClass> weakReference) {
return () {
// Weak reference to `this` in callback.
// ignore: unnecessary_statements
weakReference;
};
},
),
);
}
late final CopyableObjectWithCallback callbackClass;
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart",
"repo_id": "plugins",
"token_count": 16964
} | 1,294 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFWebViewConfigurationHostApiTests : XCTestCase
@end
@implementation FWFWebViewConfigurationHostApiTests
- (void)testCreateWithIdentifier {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFWebViewConfigurationHostApiImpl *hostAPI = [[FWFWebViewConfigurationHostApiImpl alloc]
initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
FlutterError *error;
[hostAPI createWithIdentifier:@0 error:&error];
WKWebViewConfiguration *configuration =
(WKWebViewConfiguration *)[instanceManager instanceForIdentifier:0];
XCTAssertTrue([configuration isKindOfClass:[WKWebViewConfiguration class]]);
XCTAssertNil(error);
}
- (void)testCreateFromWebViewWithIdentifier {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFWebViewConfigurationHostApiImpl *hostAPI = [[FWFWebViewConfigurationHostApiImpl alloc]
initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
WKWebView *mockWebView = OCMClassMock([WKWebView class]);
OCMStub([mockWebView configuration]).andReturn(OCMClassMock([WKWebViewConfiguration class]));
[instanceManager addDartCreatedInstance:mockWebView withIdentifier:0];
FlutterError *error;
[hostAPI createFromWebViewWithIdentifier:@1 webViewIdentifier:@0 error:&error];
WKWebViewConfiguration *configuration =
(WKWebViewConfiguration *)[instanceManager instanceForIdentifier:1];
XCTAssertTrue([configuration isKindOfClass:[WKWebViewConfiguration class]]);
XCTAssertNil(error);
}
- (void)testSetAllowsInlineMediaPlayback {
WKWebViewConfiguration *mockWebViewConfiguration = OCMClassMock([WKWebViewConfiguration class]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockWebViewConfiguration withIdentifier:0];
FWFWebViewConfigurationHostApiImpl *hostAPI = [[FWFWebViewConfigurationHostApiImpl alloc]
initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
FlutterError *error;
[hostAPI setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:@0
isAllowed:@NO
error:&error];
OCMVerify([mockWebViewConfiguration setAllowsInlineMediaPlayback:NO]);
XCTAssertNil(error);
}
- (void)testSetMediaTypesRequiringUserActionForPlayback {
WKWebViewConfiguration *mockWebViewConfiguration = OCMClassMock([WKWebViewConfiguration class]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockWebViewConfiguration withIdentifier:0];
FWFWebViewConfigurationHostApiImpl *hostAPI = [[FWFWebViewConfigurationHostApiImpl alloc]
initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
FlutterError *error;
[hostAPI
setMediaTypesRequiresUserActionForConfigurationWithIdentifier:@0
forTypes:@[
[FWFWKAudiovisualMediaTypeEnumData
makeWithValue:
FWFWKAudiovisualMediaTypeEnumAudio],
[FWFWKAudiovisualMediaTypeEnumData
makeWithValue:
FWFWKAudiovisualMediaTypeEnumVideo]
]
error:&error];
OCMVerify([mockWebViewConfiguration
setMediaTypesRequiringUserActionForPlayback:(WKAudiovisualMediaTypeAudio |
WKAudiovisualMediaTypeVideo)]);
XCTAssertNil(error);
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewConfigurationHostApiTests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewConfigurationHostApiTests.m",
"repo_id": "plugins",
"token_count": 1929
} | 1,295 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFGeneratedWebKitApis.h"
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Converts an FWFNSUrlRequestData to an NSURLRequest.
*
* @param data The data object containing information to create an NSURLRequest.
*
* @return An NSURLRequest or nil if data could not be converted.
*/
extern NSURLRequest *_Nullable FWFNSURLRequestFromRequestData(FWFNSUrlRequestData *data);
/**
* Converts an FWFNSHttpCookieData to an NSHTTPCookie.
*
* @param data The data object containing information to create an NSHTTPCookie.
*
* @return An NSHTTPCookie or nil if data could not be converted.
*/
extern NSHTTPCookie *_Nullable FWFNSHTTPCookieFromCookieData(FWFNSHttpCookieData *data);
/**
* Converts an FWFNSKeyValueObservingOptionsEnumData to an NSKeyValueObservingOptions.
*
* @param data The data object containing information to create an NSKeyValueObservingOptions.
*
* @return An NSKeyValueObservingOptions or -1 if data could not be converted.
*/
extern NSKeyValueObservingOptions FWFNSKeyValueObservingOptionsFromEnumData(
FWFNSKeyValueObservingOptionsEnumData *data);
/**
* Converts an FWFNSHTTPCookiePropertyKeyEnumData to an NSHTTPCookiePropertyKey.
*
* @param data The data object containing information to create an NSHTTPCookiePropertyKey.
*
* @return An NSHttpCookiePropertyKey or nil if data could not be converted.
*/
extern NSHTTPCookiePropertyKey _Nullable FWFNSHTTPCookiePropertyKeyFromEnumData(
FWFNSHttpCookiePropertyKeyEnumData *data);
/**
* Converts a WKUserScriptData to a WKUserScript.
*
* @param data The data object containing information to create a WKUserScript.
*
* @return A WKUserScript or nil if data could not be converted.
*/
extern WKUserScript *FWFWKUserScriptFromScriptData(FWFWKUserScriptData *data);
/**
* Converts an FWFWKUserScriptInjectionTimeEnumData to a WKUserScriptInjectionTime.
*
* @param data The data object containing information to create a WKUserScriptInjectionTime.
*
* @return A WKUserScriptInjectionTime or -1 if data could not be converted.
*/
extern WKUserScriptInjectionTime FWFWKUserScriptInjectionTimeFromEnumData(
FWFWKUserScriptInjectionTimeEnumData *data);
/**
* Converts an FWFWKAudiovisualMediaTypeEnumData to a WKAudiovisualMediaTypes.
*
* @param data The data object containing information to create a WKAudiovisualMediaTypes.
*
* @return A WKAudiovisualMediaType or -1 if data could not be converted.
*/
API_AVAILABLE(ios(10.0))
extern WKAudiovisualMediaTypes FWFWKAudiovisualMediaTypeFromEnumData(
FWFWKAudiovisualMediaTypeEnumData *data);
/**
* Converts an FWFWKWebsiteDataTypeEnumData to a WKWebsiteDataType.
*
* @param data The data object containing information to create a WKWebsiteDataType.
*
* @return A WKWebsiteDataType or nil if data could not be converted.
*/
extern NSString *_Nullable FWFWKWebsiteDataTypeFromEnumData(FWFWKWebsiteDataTypeEnumData *data);
/**
* Converts a WKNavigationAction to an FWFWKNavigationActionData.
*
* @param action The object containing information to create a WKNavigationActionData.
*
* @return A FWFWKNavigationActionData.
*/
extern FWFWKNavigationActionData *FWFWKNavigationActionDataFromNavigationAction(
WKNavigationAction *action);
/**
* Converts a NSURLRequest to an FWFNSUrlRequestData.
*
* @param request The object containing information to create a WKNavigationActionData.
*
* @return A FWFNSUrlRequestData.
*/
extern FWFNSUrlRequestData *FWFNSUrlRequestDataFromNSURLRequest(NSURLRequest *request);
/**
* Converts a WKFrameInfo to an FWFWKFrameInfoData.
*
* @param info The object containing information to create a FWFWKFrameInfoData.
*
* @return A FWFWKFrameInfoData.
*/
extern FWFWKFrameInfoData *FWFWKFrameInfoDataFromWKFrameInfo(WKFrameInfo *info);
/**
* Converts an FWFWKNavigationActionPolicyEnumData to a WKNavigationActionPolicy.
*
* @param data The data object containing information to create a WKNavigationActionPolicy.
*
* @return A WKNavigationActionPolicy or -1 if data could not be converted.
*/
extern WKNavigationActionPolicy FWFWKNavigationActionPolicyFromEnumData(
FWFWKNavigationActionPolicyEnumData *data);
/**
* Converts a NSError to an FWFNSErrorData.
*
* @param error The object containing information to create a FWFNSErrorData.
*
* @return A FWFNSErrorData.
*/
extern FWFNSErrorData *FWFNSErrorDataFromNSError(NSError *error);
/**
* Converts an NSKeyValueChangeKey to a FWFNSKeyValueChangeKeyEnumData.
*
* @param key The data object containing information to create a FWFNSKeyValueChangeKeyEnumData.
*
* @return A FWFNSKeyValueChangeKeyEnumData or nil if data could not be converted.
*/
extern FWFNSKeyValueChangeKeyEnumData *FWFNSKeyValueChangeKeyEnumDataFromNSKeyValueChangeKey(
NSKeyValueChangeKey key);
/**
* Converts a WKScriptMessage to an FWFWKScriptMessageData.
*
* @param message The object containing information to create a FWFWKScriptMessageData.
*
* @return A FWFWKScriptMessageData.
*/
extern FWFWKScriptMessageData *FWFWKScriptMessageDataFromWKScriptMessage(WKScriptMessage *message);
/**
* Converts a WKNavigationType to an FWFWKNavigationType.
*
* @param type The object containing information to create a FWFWKNavigationType
*
* @return A FWFWKNavigationType.
*/
extern FWFWKNavigationType FWFWKNavigationTypeFromWKNavigationType(WKNavigationType type);
NS_ASSUME_NONNULL_END
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.h/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.h",
"repo_id": "plugins",
"token_count": 1732
} | 1,296 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFScriptMessageHandlerHostApi.h"
#import "FWFDataConverters.h"
@interface FWFScriptMessageHandlerFlutterApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFScriptMessageHandlerFlutterApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self initWithBinaryMessenger:binaryMessenger];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (long)identifierForHandler:(FWFScriptMessageHandler *)instance {
return [self.instanceManager identifierWithStrongReferenceForInstance:instance];
}
- (void)didReceiveScriptMessageForHandler:(FWFScriptMessageHandler *)instance
userContentController:(WKUserContentController *)userContentController
message:(WKScriptMessage *)message
completion:(void (^)(NSError *_Nullable))completion {
NSNumber *userContentControllerIdentifier =
@([self.instanceManager identifierWithStrongReferenceForInstance:userContentController]);
FWFWKScriptMessageData *messageData = FWFWKScriptMessageDataFromWKScriptMessage(message);
[self didReceiveScriptMessageForHandlerWithIdentifier:@([self identifierForHandler:instance])
userContentControllerIdentifier:userContentControllerIdentifier
message:messageData
completion:completion];
}
@end
@implementation FWFScriptMessageHandler
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [super initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager];
if (self) {
_scriptMessageHandlerAPI =
[[FWFScriptMessageHandlerFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager];
}
return self;
}
- (void)userContentController:(nonnull WKUserContentController *)userContentController
didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
[self.scriptMessageHandlerAPI didReceiveScriptMessageForHandler:self
userContentController:userContentController
message:message
completion:^(NSError *error) {
NSAssert(!error, @"%@", error);
}];
}
@end
@interface FWFScriptMessageHandlerHostApiImpl ()
// BinaryMessenger must be weak to prevent a circular reference with the host API it
// references.
@property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger;
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFScriptMessageHandlerHostApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_binaryMessenger = binaryMessenger;
_instanceManager = instanceManager;
}
return self;
}
- (FWFScriptMessageHandler *)scriptMessageHandlerForIdentifier:(NSNumber *)identifier {
return (FWFScriptMessageHandler *)[self.instanceManager
instanceForIdentifier:identifier.longValue];
}
- (void)createWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable *_Nonnull)error {
FWFScriptMessageHandler *scriptMessageHandler =
[[FWFScriptMessageHandler alloc] initWithBinaryMessenger:self.binaryMessenger
instanceManager:self.instanceManager];
[self.instanceManager addDartCreatedInstance:scriptMessageHandler
withIdentifier:identifier.longValue];
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScriptMessageHandlerHostApi.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScriptMessageHandlerHostApi.m",
"repo_id": "plugins",
"token_count": 1740
} | 1,297 |
// 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 "FWFWebsiteDataStoreHostApi.h"
#import "FWFDataConverters.h"
#import "FWFWebViewConfigurationHostApi.h"
@interface FWFWebsiteDataStoreHostApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFWebsiteDataStoreHostApiImpl
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (WKWebsiteDataStore *)websiteDataStoreForIdentifier:(NSNumber *)identifier {
return (WKWebsiteDataStore *)[self.instanceManager instanceForIdentifier:identifier.longValue];
}
- (void)createFromWebViewConfigurationWithIdentifier:(nonnull NSNumber *)identifier
configurationIdentifier:(nonnull NSNumber *)configurationIdentifier
error:(FlutterError *_Nullable *_Nonnull)error {
WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager
instanceForIdentifier:configurationIdentifier.longValue];
[self.instanceManager addDartCreatedInstance:configuration.websiteDataStore
withIdentifier:identifier.longValue];
}
- (void)createDefaultDataStoreWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
[self.instanceManager addDartCreatedInstance:[WKWebsiteDataStore defaultDataStore]
withIdentifier:identifier.longValue];
}
- (void)
removeDataFromDataStoreWithIdentifier:(nonnull NSNumber *)identifier
ofTypes:
(nonnull NSArray<FWFWKWebsiteDataTypeEnumData *> *)dataTypes
modifiedSince:(nonnull NSNumber *)modificationTimeInSecondsSinceEpoch
completion:(nonnull void (^)(NSNumber *_Nullable,
FlutterError *_Nullable))completion {
NSMutableSet<NSString *> *stringDataTypes = [NSMutableSet set];
for (FWFWKWebsiteDataTypeEnumData *type in dataTypes) {
[stringDataTypes addObject:FWFWKWebsiteDataTypeFromEnumData(type)];
}
WKWebsiteDataStore *dataStore = [self websiteDataStoreForIdentifier:identifier];
[dataStore
fetchDataRecordsOfTypes:stringDataTypes
completionHandler:^(NSArray<WKWebsiteDataRecord *> *records) {
[dataStore
removeDataOfTypes:stringDataTypes
modifiedSince:[NSDate dateWithTimeIntervalSince1970:
modificationTimeInSecondsSinceEpoch.doubleValue]
completionHandler:^{
completion([NSNumber numberWithBool:(records.count > 0)], nil);
}];
}];
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebsiteDataStoreHostApi.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebsiteDataStoreHostApi.m",
"repo_id": "plugins",
"token_count": 1357
} | 1,298 |
// 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 'common/instance_manager.dart';
import 'foundation/foundation.dart';
import 'web_kit/web_kit.dart';
// This convenience method was added because Dart doesn't support constant
// function literals: https://github.com/dart-lang/language/issues/1048.
WKWebsiteDataStore _defaultWebsiteDataStore() =>
WKWebsiteDataStore.defaultDataStore;
/// Handles constructing objects and calling static methods for the WebKit
/// native library.
///
/// This class provides dependency injection for the implementations of the
/// platform interface classes. Improving the ease of unit testing and/or
/// overriding the underlying WebKit classes.
///
/// By default each function calls the default constructor of the WebKit class
/// it intends to return.
class WebKitProxy {
/// Constructs a [WebKitProxy].
const WebKitProxy({
this.createWebView = WKWebView.new,
this.createWebViewConfiguration = WKWebViewConfiguration.new,
this.createScriptMessageHandler = WKScriptMessageHandler.new,
this.defaultWebsiteDataStore = _defaultWebsiteDataStore,
this.createNavigationDelegate = WKNavigationDelegate.new,
this.createUIDelegate = WKUIDelegate.new,
});
/// Constructs a [WKWebView].
final WKWebView Function(
WKWebViewConfiguration configuration, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)?
observeValue,
InstanceManager? instanceManager,
}) createWebView;
/// Constructs a [WKWebViewConfiguration].
final WKWebViewConfiguration Function({
InstanceManager? instanceManager,
}) createWebViewConfiguration;
/// Constructs a [WKScriptMessageHandler].
final WKScriptMessageHandler Function({
required void Function(
WKUserContentController userContentController,
WKScriptMessage message,
)
didReceiveScriptMessage,
}) createScriptMessageHandler;
/// The default [WKWebsiteDataStore].
final WKWebsiteDataStore Function() defaultWebsiteDataStore;
/// Constructs a [WKNavigationDelegate].
final WKNavigationDelegate Function({
void Function(WKWebView webView, String? url)? didFinishNavigation,
void Function(WKWebView webView, String? url)?
didStartProvisionalNavigation,
Future<WKNavigationActionPolicy> Function(
WKWebView webView,
WKNavigationAction navigationAction,
)?
decidePolicyForNavigationAction,
void Function(WKWebView webView, NSError error)? didFailNavigation,
void Function(WKWebView webView, NSError error)?
didFailProvisionalNavigation,
void Function(WKWebView webView)? webViewWebContentProcessDidTerminate,
}) createNavigationDelegate;
/// Constructs a [WKUIDelegate].
final WKUIDelegate Function({
void Function(
WKWebView webView,
WKWebViewConfiguration configuration,
WKNavigationAction navigationAction,
)?
onCreateWebView,
}) createUIDelegate;
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_proxy.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_proxy.dart",
"repo_id": "plugins",
"token_count": 970
} | 1,299 |
// 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:math';
import 'package:flutter/material.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/ui_kit/ui_kit.dart';
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart';
import '../common/test_web_kit.g.dart';
import 'ui_kit_test.mocks.dart';
@GenerateMocks(<Type>[
TestWKWebViewConfigurationHostApi,
TestWKWebViewHostApi,
TestUIScrollViewHostApi,
TestUIViewHostApi,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('UIKit', () {
late InstanceManager instanceManager;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
});
group('UIScrollView', () {
late MockTestUIScrollViewHostApi mockPlatformHostApi;
late UIScrollView scrollView;
late int scrollViewInstanceId;
setUp(() {
mockPlatformHostApi = MockTestUIScrollViewHostApi();
TestUIScrollViewHostApi.setup(mockPlatformHostApi);
TestWKWebViewConfigurationHostApi.setup(
MockTestWKWebViewConfigurationHostApi(),
);
TestWKWebViewHostApi.setup(MockTestWKWebViewHostApi());
final WKWebView webView = WKWebView(
WKWebViewConfiguration(instanceManager: instanceManager),
instanceManager: instanceManager,
);
scrollView = UIScrollView.fromWebView(
webView,
instanceManager: instanceManager,
);
scrollViewInstanceId = instanceManager.getIdentifier(scrollView)!;
});
tearDown(() {
TestUIScrollViewHostApi.setup(null);
TestWKWebViewConfigurationHostApi.setup(null);
TestWKWebViewHostApi.setup(null);
});
test('getContentOffset', () async {
when(mockPlatformHostApi.getContentOffset(scrollViewInstanceId))
.thenReturn(<double>[4.0, 10.0]);
expect(
scrollView.getContentOffset(),
completion(const Point<double>(4.0, 10.0)),
);
});
test('scrollBy', () async {
await scrollView.scrollBy(const Point<double>(4.0, 10.0));
verify(mockPlatformHostApi.scrollBy(scrollViewInstanceId, 4.0, 10.0));
});
test('setContentOffset', () async {
await scrollView.setContentOffset(const Point<double>(4.0, 10.0));
verify(mockPlatformHostApi.setContentOffset(
scrollViewInstanceId,
4.0,
10.0,
));
});
});
group('UIView', () {
late MockTestUIViewHostApi mockPlatformHostApi;
late UIView view;
late int viewInstanceId;
setUp(() {
mockPlatformHostApi = MockTestUIViewHostApi();
TestUIViewHostApi.setup(mockPlatformHostApi);
view = UIView.detached(instanceManager: instanceManager);
viewInstanceId = instanceManager.addDartCreatedInstance(view);
});
tearDown(() {
TestUIViewHostApi.setup(null);
});
test('setBackgroundColor', () async {
await view.setBackgroundColor(Colors.red);
verify(mockPlatformHostApi.setBackgroundColor(
viewInstanceId,
Colors.red.value,
));
});
test('setOpaque', () async {
await view.setOpaque(false);
verify(mockPlatformHostApi.setOpaque(viewInstanceId, false));
});
});
});
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/ui_kit/ui_kit_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/ui_kit/ui_kit_test.dart",
"repo_id": "plugins",
"token_count": 1546
} | 1,300 |
# Currently missing: https://github.com/flutter/flutter/issues/82208
- ios_platform_images
# Can't use Flutter integration tests due to native modal UI.
- file_selector_ios
- file_selector | plugins/script/configs/exclude_integration_ios.yaml/0 | {
"file_path": "plugins/script/configs/exclude_integration_ios.yaml",
"repo_id": "plugins",
"token_count": 58
} | 1,301 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'dart:math';
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:git/git.dart';
import 'package:path/path.dart' as p;
import 'package:platform/platform.dart';
import 'package:yaml/yaml.dart';
import 'core.dart';
import 'git_version_finder.dart';
import 'process_runner.dart';
import 'repository_package.dart';
/// An entry in package enumeration for APIs that need to include extra
/// data about the entry.
class PackageEnumerationEntry {
/// Creates a new entry for the given package.
PackageEnumerationEntry(this.package, {required this.excluded});
/// The package this entry corresponds to. Be sure to check `excluded` before
/// using this, as having an entry does not necessarily mean that the package
/// should be included in the processing of the enumeration.
final RepositoryPackage package;
/// Whether or not this package was excluded by the command invocation.
final bool excluded;
}
/// Interface definition for all commands in this tool.
// TODO(stuartmorgan): Move most of this logic to PackageLoopingCommand.
abstract class PackageCommand extends Command<void> {
/// Creates a command to operate on [packagesDir] with the given environment.
PackageCommand(
this.packagesDir, {
this.processRunner = const ProcessRunner(),
this.platform = const LocalPlatform(),
GitDir? gitDir,
}) : _gitDir = gitDir {
argParser.addMultiOption(
_packagesArg,
help:
'Specifies which packages the command should run on (before sharding).\n',
valueHelp: 'package1,package2,...',
aliases: <String>[_pluginsLegacyAliasArg],
);
argParser.addOption(
_shardIndexArg,
help: 'Specifies the zero-based index of the shard to '
'which the command applies.',
valueHelp: 'i',
defaultsTo: '0',
);
argParser.addOption(
_shardCountArg,
help: 'Specifies the number of shards into which packages are divided.',
valueHelp: 'n',
defaultsTo: '1',
);
argParser.addMultiOption(
_excludeArg,
abbr: 'e',
help: 'A list of packages to exclude from from this command.\n\n'
'Alternately, a list of one or more YAML files that contain a list '
'of packages to exclude.',
defaultsTo: <String>[],
);
argParser.addFlag(_runOnChangedPackagesArg,
help: 'Run the command on changed packages.\n'
'If no packages have changed, or if there have been changes that may\n'
'affect all packages, the command runs on all packages.\n'
'Packages excluded with $_excludeArg are excluded even if changed.\n'
'See $_baseShaArg if a custom base is needed to determine the diff.\n\n'
'Cannot be combined with $_packagesArg.\n');
argParser.addFlag(_runOnDirtyPackagesArg,
help:
'Run the command on packages with changes that have not been committed.\n'
'Packages excluded with $_excludeArg are excluded even if changed.\n'
'Cannot be combined with $_packagesArg.\n',
hide: true);
argParser.addFlag(_packagesForBranchArg,
help: 'This runs on all packages changed in the last commit on main '
'(or master), and behaves like --run-on-changed-packages on '
'any other branch.\n\n'
'Cannot be combined with $_packagesArg.\n\n'
'This is intended for use in CI.\n',
hide: true);
argParser.addOption(_baseShaArg,
help: 'The base sha used to determine git diff. \n'
'This is useful when $_runOnChangedPackagesArg is specified.\n'
'If not specified, merge-base is used as base sha.');
argParser.addFlag(_logTimingArg,
help: 'Logs timing information.\n\n'
'Currently only logs per-package timing for multi-package commands, '
'but more information may be added in the future.');
}
static const String _baseShaArg = 'base-sha';
static const String _excludeArg = 'exclude';
static const String _logTimingArg = 'log-timing';
static const String _packagesArg = 'packages';
static const String _packagesForBranchArg = 'packages-for-branch';
static const String _pluginsLegacyAliasArg = 'plugins';
static const String _runOnChangedPackagesArg = 'run-on-changed-packages';
static const String _runOnDirtyPackagesArg = 'run-on-dirty-packages';
static const String _shardCountArg = 'shardCount';
static const String _shardIndexArg = 'shardIndex';
/// The directory containing the packages.
final Directory packagesDir;
/// The process runner.
///
/// This can be overridden for testing.
final ProcessRunner processRunner;
/// The current platform.
///
/// This can be overridden for testing.
final Platform platform;
/// The git directory to use. If unset, [gitDir] populates it from the
/// packages directory's enclosing repository.
///
/// This can be mocked for testing.
GitDir? _gitDir;
int? _shardIndex;
int? _shardCount;
// Cached set of explicitly excluded packages.
Set<String>? _excludedPackages;
/// A context that matches the default for [platform].
p.Context get path => platform.isWindows ? p.windows : p.posix;
/// The command to use when running `flutter`.
String get flutterCommand => platform.isWindows ? 'flutter.bat' : 'flutter';
/// The shard of the overall command execution that this instance should run.
int get shardIndex {
if (_shardIndex == null) {
_checkSharding();
}
return _shardIndex!;
}
/// The number of shards this command is divided into.
int get shardCount {
if (_shardCount == null) {
_checkSharding();
}
return _shardCount!;
}
/// Returns the [GitDir] containing [packagesDir].
Future<GitDir> get gitDir async {
GitDir? gitDir = _gitDir;
if (gitDir != null) {
return gitDir;
}
// Ensure there are no symlinks in the path, as it can break
// GitDir's allowSubdirectory:true.
final String packagesPath = packagesDir.resolveSymbolicLinksSync();
if (!await GitDir.isGitDir(packagesPath)) {
printError('$packagesPath is not a valid Git repository.');
throw ToolExit(2);
}
gitDir =
await GitDir.fromExisting(packagesDir.path, allowSubdirectory: true);
_gitDir = gitDir;
return gitDir;
}
/// Convenience accessor for boolean arguments.
bool getBoolArg(String key) {
return (argResults![key] as bool?) ?? false;
}
/// Convenience accessor for String arguments.
String getStringArg(String key) {
return (argResults![key] as String?) ?? '';
}
/// Convenience accessor for List<String> arguments.
List<String> getStringListArg(String key) {
// Clone the list so that if a caller modifies the result it won't change
// the actual arguments list for future queries.
return List<String>.from(argResults![key] as List<String>? ?? <String>[]);
}
/// If true, commands should log timing information that might be useful in
/// analyzing their runtime (e.g., the per-package time for multi-package
/// commands).
bool get shouldLogTiming => getBoolArg(_logTimingArg);
void _checkSharding() {
final int? shardIndex = int.tryParse(getStringArg(_shardIndexArg));
final int? shardCount = int.tryParse(getStringArg(_shardCountArg));
if (shardIndex == null) {
usageException('$_shardIndexArg must be an integer');
}
if (shardCount == null) {
usageException('$_shardCountArg must be an integer');
}
if (shardCount < 1) {
usageException('$_shardCountArg must be positive');
}
if (shardIndex < 0 || shardCount <= shardIndex) {
usageException(
'$_shardIndexArg must be in the half-open range [0..$shardCount[');
}
_shardIndex = shardIndex;
_shardCount = shardCount;
}
/// Returns the set of packages to exclude based on the `--exclude` argument.
Set<String> getExcludedPackageNames() {
final Set<String> excludedPackages = _excludedPackages ??
getStringListArg(_excludeArg).expand<String>((String item) {
if (item.endsWith('.yaml')) {
final File file = packagesDir.fileSystem.file(item);
return (loadYaml(file.readAsStringSync()) as YamlList)
.toList()
.cast<String>();
}
return <String>[item];
}).toSet();
// Cache for future calls.
_excludedPackages = excludedPackages;
return excludedPackages;
}
/// Returns the root diretories of the packages involved in this command
/// execution.
///
/// Depending on the command arguments, this may be a user-specified set of
/// packages, the set of packages that should be run for a given diff, or all
/// packages.
///
/// By default, packages excluded via --exclude will not be in the stream, but
/// they can be included by passing false for [filterExcluded].
Stream<PackageEnumerationEntry> getTargetPackages(
{bool filterExcluded = true}) async* {
// To avoid assuming consistency of `Directory.list` across command
// invocations, we collect and sort the package folders before sharding.
// This is considered an implementation detail which is why the API still
// uses streams.
final List<PackageEnumerationEntry> allPackages =
await _getAllPackages().toList();
allPackages.sort((PackageEnumerationEntry p1, PackageEnumerationEntry p2) =>
p1.package.path.compareTo(p2.package.path));
final int shardSize = allPackages.length ~/ shardCount +
(allPackages.length % shardCount == 0 ? 0 : 1);
final int start = min(shardIndex * shardSize, allPackages.length);
final int end = min(start + shardSize, allPackages.length);
for (final PackageEnumerationEntry package
in allPackages.sublist(start, end)) {
if (!(filterExcluded && package.excluded)) {
yield package;
}
}
}
/// Returns the root Dart package folders of the packages involved in this
/// command execution, assuming there is only one shard. Depending on the
/// command arguments, this may be a user-specified set of packages, the
/// set of packages that should be run for a given diff, or all packages.
///
/// This will return packages that have been excluded by the --exclude
/// parameter, annotated in the entry as excluded.
///
/// Packages can exist in the following places relative to the packages
/// directory:
///
/// 1. As a Dart package in a directory which is a direct child of the
/// packages directory. This is a non-plugin package, or a non-federated
/// plugin.
/// 2. Several plugin packages may live in a directory which is a direct
/// child of the packages directory. This directory groups several Dart
/// packages which implement a single plugin. This directory contains an
/// "app-facing" package which declares the API for the plugin, a
/// platform interface package which declares the API for implementations,
/// and one or more platform-specific implementation packages.
/// 3./4. Either of the above, but in a third_party/packages/ directory that
/// is a sibling of the packages directory. This is used for a small number
/// of packages in the flutter/packages repository.
Stream<PackageEnumerationEntry> _getAllPackages() async* {
final Set<String> packageSelectionFlags = <String>{
_packagesArg,
_runOnChangedPackagesArg,
_runOnDirtyPackagesArg,
_packagesForBranchArg,
};
if (packageSelectionFlags
.where((String flag) => argResults!.wasParsed(flag))
.length >
1) {
printError('Only one of --$_packagesArg, --$_runOnChangedPackagesArg, or '
'--$_packagesForBranchArg can be provided.');
throw ToolExit(exitInvalidArguments);
}
Set<String> packages = Set<String>.from(getStringListArg(_packagesArg));
final GitVersionFinder? changedFileFinder;
if (getBoolArg(_runOnChangedPackagesArg)) {
changedFileFinder = await retrieveVersionFinder();
} else if (getBoolArg(_packagesForBranchArg)) {
final String? branch = await _getBranch();
if (branch == null) {
printError('Unable to determine branch; --$_packagesForBranchArg can '
'only be used in a git repository.');
throw ToolExit(exitInvalidArguments);
} else {
// Configure the change finder the correct mode for the branch.
// Log the mode to make it easier to audit logs to see that the
// intended diff was used (or why).
final bool lastCommitOnly;
if (branch == 'main' || branch == 'master') {
print('--$_packagesForBranchArg: running on default branch.');
lastCommitOnly = true;
} else if (await _isCheckoutFromBranch('main')) {
print(
'--$_packagesForBranchArg: running on a commit from default branch.');
lastCommitOnly = true;
} else {
print('--$_packagesForBranchArg: running on branch "$branch".');
lastCommitOnly = false;
}
if (lastCommitOnly) {
print(
'--$_packagesForBranchArg: using parent commit as the diff base.');
changedFileFinder = GitVersionFinder(await gitDir, 'HEAD~');
} else {
changedFileFinder = await retrieveVersionFinder();
}
}
} else {
changedFileFinder = null;
}
if (changedFileFinder != null) {
final String baseSha = await changedFileFinder.getBaseSha();
final List<String> changedFiles =
await changedFileFinder.getChangedFiles();
if (_changesRequireFullTest(changedFiles)) {
print('Running for all packages, since a file has changed that could '
'affect the entire repository.');
} else {
print(
'Running for all packages that have diffs relative to "$baseSha"\n');
packages = _getChangedPackageNames(changedFiles);
}
} else if (getBoolArg(_runOnDirtyPackagesArg)) {
final GitVersionFinder gitVersionFinder =
GitVersionFinder(await gitDir, 'HEAD');
print('Running for all packages that have uncommitted changes\n');
// _changesRequireFullTest is deliberately not used here, as this flag is
// intended for use in CI to re-test packages changed by
// 'make-deps-path-based'.
packages = _getChangedPackageNames(
await gitVersionFinder.getChangedFiles(includeUncommitted: true));
// For the same reason, empty is not treated as "all packages" as it is
// for other flags.
if (packages.isEmpty) {
return;
}
}
final Directory thirdPartyPackagesDirectory = packagesDir.parent
.childDirectory('third_party')
.childDirectory('packages');
final Set<String> excludedPackageNames = getExcludedPackageNames();
for (final Directory dir in <Directory>[
packagesDir,
if (thirdPartyPackagesDirectory.existsSync()) thirdPartyPackagesDirectory,
]) {
await for (final FileSystemEntity entity
in dir.list(followLinks: false)) {
// A top-level Dart package is a standard package.
if (isPackage(entity)) {
if (packages.isEmpty || packages.contains(p.basename(entity.path))) {
yield PackageEnumerationEntry(
RepositoryPackage(entity as Directory),
excluded: excludedPackageNames.contains(entity.basename));
}
} else if (entity is Directory) {
// Look for Dart packages under this top-level directory; this is the
// standard structure for federated plugins.
await for (final FileSystemEntity subdir
in entity.list(followLinks: false)) {
if (isPackage(subdir)) {
// There are three ways for a federated plugin to match:
// - package name (path_provider_android)
// - fully specified name (path_provider/path_provider_android)
// - group name (path_provider), which matches all packages in
// the group
final Set<String> possibleMatches = <String>{
path.basename(subdir.path), // package name
path.basename(entity.path), // group name
path.relative(subdir.path, from: dir.path), // fully specified
};
if (packages.isEmpty ||
packages.intersection(possibleMatches).isNotEmpty) {
yield PackageEnumerationEntry(
RepositoryPackage(subdir as Directory),
excluded: excludedPackageNames
.intersection(possibleMatches)
.isNotEmpty);
}
}
}
}
}
}
}
/// Returns all Dart package folders (typically, base package + example) of
/// the packages involved in this command execution.
///
/// By default, packages excluded via --exclude will not be in the stream, but
/// they can be included by passing false for [filterExcluded].
///
/// Subpackages are guaranteed to be after the containing package in the
/// stream.
Stream<PackageEnumerationEntry> getTargetPackagesAndSubpackages(
{bool filterExcluded = true}) async* {
await for (final PackageEnumerationEntry package
in getTargetPackages(filterExcluded: filterExcluded)) {
yield package;
yield* getSubpackages(package.package).map(
(RepositoryPackage subPackage) =>
PackageEnumerationEntry(subPackage, excluded: package.excluded));
}
}
/// Returns all Dart package folders (e.g., examples) under the given package.
Stream<RepositoryPackage> getSubpackages(RepositoryPackage package,
{bool filterExcluded = true}) async* {
yield* package.directory
.list(recursive: true, followLinks: false)
.where(isPackage)
.map((FileSystemEntity directory) =>
// isPackage guarantees that this cast is valid.
RepositoryPackage(directory as Directory));
}
/// Returns the files contained, recursively, within the packages
/// involved in this command execution.
Stream<File> getFiles() {
return getTargetPackages().asyncExpand<File>(
(PackageEnumerationEntry entry) => getFilesForPackage(entry.package));
}
/// Returns the files contained, recursively, within [package].
Stream<File> getFilesForPackage(RepositoryPackage package) {
return package.directory
.list(recursive: true, followLinks: false)
.where((FileSystemEntity entity) => entity is File)
.cast<File>();
}
/// Retrieve an instance of [GitVersionFinder] based on `_baseShaArg` and [gitDir].
///
/// Throws tool exit if [gitDir] nor root directory is a git directory.
Future<GitVersionFinder> retrieveVersionFinder() async {
final String baseSha = getStringArg(_baseShaArg);
final GitVersionFinder gitVersionFinder =
GitVersionFinder(await gitDir, baseSha);
return gitVersionFinder;
}
// Returns the names of packages that have been changed given a list of
// changed files.
//
// The names will either be the actual package names, or potentially
// group/name specifiers (for example, path_provider/path_provider) for
// packages in federated plugins.
//
// The paths must use POSIX separators (e.g., as provided by git output).
Set<String> _getChangedPackageNames(List<String> changedFiles) {
final Set<String> packages = <String>{};
// A helper function that returns true if candidatePackageName looks like an
// implementation package of a plugin called pluginName. Used to determine
// if .../packages/parentName/candidatePackageName/...
// looks like a path in a federated plugin package (candidatePackageName)
// rather than a top-level package (parentName).
bool isFederatedPackage(String candidatePackageName, String parentName) {
return candidatePackageName == parentName ||
candidatePackageName.startsWith('${parentName}_');
}
for (final String path in changedFiles) {
final List<String> pathComponents = p.posix.split(path);
final int packagesIndex =
pathComponents.indexWhere((String element) => element == 'packages');
if (packagesIndex != -1) {
// Find the name of the directory directly under packages. This is
// either the name of the package, or a plugin group directory for
// a federated plugin.
final String topLevelName = pathComponents[packagesIndex + 1];
String packageName = topLevelName;
if (packagesIndex + 2 < pathComponents.length &&
isFederatedPackage(
pathComponents[packagesIndex + 2], topLevelName)) {
// This looks like a federated package; use the full specifier if
// the name would be ambiguous (i.e., for the app-facing package).
packageName = pathComponents[packagesIndex + 2];
if (packageName == topLevelName) {
packageName = '$topLevelName/$packageName';
}
}
packages.add(packageName);
}
}
if (packages.isEmpty) {
print('No changed packages.');
} else {
final String changedPackages = packages.join(',');
print('Changed packages: $changedPackages');
}
return packages;
}
// Returns true if the current checkout is on an ancestor of [branch].
//
// This is used because CI may check out a specific hash rather than a branch,
// in which case branch-name detection won't work.
Future<bool> _isCheckoutFromBranch(String branchName) async {
// The target branch may not exist locally; try some common remote names for
// the branch as well.
final List<String> candidateBranchNames = <String>[
branchName,
'origin/$branchName',
'upstream/$branchName',
];
for (final String branch in candidateBranchNames) {
final io.ProcessResult result = await (await gitDir).runCommand(
<String>['merge-base', '--is-ancestor', 'HEAD', branch],
throwOnError: false);
if (result.exitCode == 0) {
return true;
} else if (result.exitCode == 1) {
// 1 indicates that the branch was successfully checked, but it's not
// an ancestor.
return false;
}
// Any other return code is an error, such as `branch` not being a valid
// name in the repository, so try other name variants.
}
return false;
}
Future<String?> _getBranch() async {
final io.ProcessResult branchResult = await (await gitDir).runCommand(
<String>['rev-parse', '--abbrev-ref', 'HEAD'],
throwOnError: false);
if (branchResult.exitCode != 0) {
return null;
}
return (branchResult.stdout as String).trim();
}
// Returns true if one or more files changed that have the potential to affect
// any packages (e.g., CI script changes).
bool _changesRequireFullTest(List<String> changedFiles) {
const List<String> specialFiles = <String>[
'.ci.yaml', // LUCI config.
'.cirrus.yml', // Cirrus config.
'.clang-format', // ObjC and C/C++ formatting options.
'analysis_options.yaml', // Dart analysis settings.
];
const List<String> specialDirectories = <String>[
'.ci/', // Support files for CI.
'script/', // This tool, and its wrapper scripts.
];
// Directory entries must end with / to avoid over-matching, since the
// check below is done via string prefixing.
assert(specialDirectories.every((String dir) => dir.endsWith('/')));
return changedFiles.any((String path) =>
specialFiles.contains(path) ||
specialDirectories.any((String dir) => path.startsWith(dir)));
}
}
| plugins/script/tool/lib/src/common/package_command.dart/0 | {
"file_path": "plugins/script/tool/lib/src/common/package_command.dart",
"repo_id": "plugins",
"token_count": 8533
} | 1,302 |
# Add-to-App Samples
This directory contains Android and iOS projects that import and use a Flutter
module. They're designed to show recommended approaches for [adding Flutter to
existing Android and iOS apps](https://docs.flutter.dev/add-to-app).
## Samples Listing
* [`fullscreen`](./fullscreen) — Embeds a full screen instance of
Flutter into an existing iOS or Android app.
* [`prebuilt_module`](./prebuilt_module) — Embeds a full screen
instance of Flutter as a prebuilt library that can be loaded into an existing
iOS or Android app.
* [`plugin`](./plugin) — Embeds a full screen Flutter instance that
is using plugins into an existing iOS or Android app.
* [`books`](./books) — Mimics a real world use-case of embedding Flutter into an
existing Android app and demonstrates using
[Pigeon](https://pub.dev/packages/pigeon) to communicate between Flutter and
the host application.
* [`multiple_flutters`](./multiple_flutters) — Shows the usage of the Flutter
Engine Group APIs to embed multiple instances of Flutter into an existing app
with low memory cost.
* [`android_view`](./android_view) — Shows how to integrate a Flutter
add-to-app module at a view level for Android.
## Goals for these samples
* Show developers how to add Flutter to their existing applications.
* Show the following options:
* Whether to build the Flutter module from source each time the app builds or
rely on a separately pre-built module.
* Whether plugins are needed by the Flutter module used in the app.
* Show Flutter being integrated ergonomically with applications with existing
middleware and business logic data classes.
## Installing Cocoapods
The iOS samples in this repo require the latest version of Cocoapods. To make
sure you've got it, run the following command on a macOS machine:
```bash
sudo gem install cocoapods
```
See https://guides.cocoapods.org/using/getting-started.html for more details.
## Debugging
You can `flutter attach` to the running host application to [debug the Flutter
module](https://docs.flutter.dev/add-to-app/debugging). This will
allow you to hot reload, set breakpoints, and use DevTools and other debugging
functionality, similar to a full Flutter app.
## Questions/issues
If you have a general question about incorporating Flutter into an existing
iOS or Android app, the best places to go are:
* [The FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev)
* [The Flutter Gitter channel](https://gitter.im/flutter/flutter)
* [StackOverflow](https://stackoverflow.com/questions/tagged/flutter)
If you run into an issue with the sample itself, please file an issue
in the [main Flutter repo](https://github.com/flutter/flutter/issues).
| samples/add_to_app/README.md/0 | {
"file_path": "samples/add_to_app/README.md",
"repo_id": "samples",
"token_count": 746
} | 1,303 |
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout> | samples/add_to_app/android_view/android_view/app/src/main/res/layout/activity_main.xml/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/layout/activity_main.xml",
"repo_id": "samples",
"token_count": 216
} | 1,304 |
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources> | samples/add_to_app/android_view/android_view/app/src/main/res/values/dimens.xml/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/values/dimens.xml",
"repo_id": "samples",
"token_count": 67
} | 1,305 |
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_module_using_plugin/main.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
class MockCounterModel extends ChangeNotifier implements CounterModel {
int _count = 0;
@override
int get count => _count;
@override
void increment() {
_count++;
notifyListeners();
}
}
void main() {
testWidgets('MiniView smoke test', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(
MaterialApp(
home: ChangeNotifierProvider<CounterModel>.value(
value: MockCounterModel(),
child: const Contents(),
),
),
);
// Verify that our counter starts at 0.
expect(find.text('Taps: 0'), findsOneWidget);
expect(find.text('Taps: 1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.text('Tap me!'));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('Taps: 0'), findsNothing);
expect(find.text('Taps: 1'), findsOneWidget);
});
}
| samples/add_to_app/android_view/flutter_module_using_plugin/test/widget_test.dart/0 | {
"file_path": "samples/add_to_app/android_view/flutter_module_using_plugin/test/widget_test.dart",
"repo_id": "samples",
"token_count": 499
} | 1,306 |
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="21dp"
android:layout_marginStart="21dp"
android:layout_marginEnd="21dp"
android:layout_marginBottom="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?attr/textAppearanceHeadline5"
tools:text="Title" />
<TextView
android:id="@+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textAppearance="?attr/textAppearanceSubtitle1"
android:textColor="?android:attr/textColorSecondary"
tools:text="subtitle" />
<TextView
android:id="@+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textAppearance="?attr/textAppearanceBody1"
android:textColor="?android:attr/textColorSecondary"
tools:text="Author" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="horizontal"
android:layout_gravity="end">
<com.google.android.material.button.MaterialButton
android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/edit"
style="?attr/borderlessButtonStyle"
/>
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</FrameLayout>
| samples/add_to_app/books/android_books/app/src/main/res/layout/book_card.xml/0 | {
"file_path": "samples/add_to_app/books/android_books/app/src/main/res/layout/book_card.xml",
"repo_id": "samples",
"token_count": 1270
} | 1,307 |
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.6.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.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/books/android_books/build.gradle/0 | {
"file_path": "samples/add_to_app/books/android_books/build.gradle",
"repo_id": "samples",
"token_count": 256
} | 1,308 |
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
| samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/values/styles.xml/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/values/styles.xml",
"repo_id": "samples",
"token_count": 139
} | 1,309 |
// 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_driver/driver_extension.dart';
import 'package:flutter_module/main.dart' as app;
// This alternate entrypoint is used for espresso testing. See
// https://pub.dev/packages/espresso for details.
void main() {
enableFlutterDriverExtension();
app.main();
}
| samples/add_to_app/fullscreen/flutter_module/test_driver/example.dart/0 | {
"file_path": "samples/add_to_app/fullscreen/flutter_module/test_driver/example.dart",
"repo_id": "samples",
"token_count": 129
} | 1,310 |
// 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
@testable import IOSFullScreen
class IOSFullScreenTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreenTests/IOSFullScreenTests.swift/0 | {
"file_path": "samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreenTests/IOSFullScreenTests.swift",
"repo_id": "samples",
"token_count": 304
} | 1,311 |
package dev.flutter.multipleflutters
import android.app.Activity
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
/**
* This interface represents the notifications an EngineBindings may be receiving from the Flutter
* instance.
*
* What methods this interface has depends on the messages that are sent over the EngineBinding's
* channel in `main.dart`. Messages that interact with the DataModel are handled automatically
* by the EngineBindings.
*
* @see main.dart for what messages are getting sent from Flutter.
*/
interface EngineBindingsDelegate {
fun onNext()
}
/**
* This binds a FlutterEngine instance with the DataModel and a channel for communicating with that
* engine.
*
* Messages involving the DataModel are handled by the EngineBindings, other messages are forwarded
* to the EngineBindingsDelegate.
*
* @see main.dart for what messages are getting sent from Flutter.
*/
class EngineBindings(activity: Activity, delegate: EngineBindingsDelegate, entrypoint: String) :
DataModelObserver {
val channel: MethodChannel
val engine: FlutterEngine
val delegate: EngineBindingsDelegate
init {
val app = activity.applicationContext as App
// This has to be lazy to avoid creation before the FlutterEngineGroup.
val dartEntrypoint =
DartExecutor.DartEntrypoint(
FlutterInjector.instance().flutterLoader().findAppBundlePath(), entrypoint
)
engine = app.engines.createAndRunEngine(activity, dartEntrypoint)
this.delegate = delegate
channel = MethodChannel(engine.dartExecutor.binaryMessenger, "multiple-flutters")
}
/**
* This setups the messaging connections on the platform channel and the DataModel.
*/
fun attach() {
DataModel.instance.addObserver(this)
channel.invokeMethod("setCount", DataModel.instance.counter)
channel.setMethodCallHandler { call, result ->
when (call.method) {
"incrementCount" -> {
DataModel.instance.counter = DataModel.instance.counter + 1
result.success(null)
}
"next" -> {
this.delegate.onNext()
result.success(null)
}
else -> {
result.notImplemented()
}
}
}
}
/**
* This tears down the messaging connections on the platform channel and the DataModel.
*/
fun detach() {
engine.destroy();
DataModel.instance.removeObserver(this)
channel.setMethodCallHandler(null)
}
override fun onCountUpdate(newCount: Int) {
channel.invokeMethod("setCount", newCount)
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/EngineBindings.kt/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/EngineBindings.kt",
"repo_id": "samples",
"token_count": 1079
} | 1,312 |
# multiple_flutters_ios
This is an add-to-app sample that uses the Flutter Engine Group API to host
multiple instances of Flutter in an iOS app.
## Getting Started
```sh
cd ../multiple_flutters_module
flutter pub get
cd -
pod install
open MultipleFluttersIos.xcworkspace
# (build and run)
```
For more information see: [multiple_flutters/README.md](../README.md)
| samples/add_to_app/multiple_flutters/multiple_flutters_ios/README.md/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/README.md",
"repo_id": "samples",
"token_count": 116
} | 1,313 |
<resources>
<string name="app_name">AndroidUsingPlugin</string>
</resources>
| samples/add_to_app/plugin/android_using_plugin/app/src/main/res/values/strings.xml/0 | {
"file_path": "samples/add_to_app/plugin/android_using_plugin/app/src/main/res/values/strings.xml",
"repo_id": "samples",
"token_count": 26
} | 1,314 |
name: analysis_defaults
description: Analysis defaults for flutter/samples
publish_to: none
environment:
sdk: ^3.2.0
# NOTE: Code is not allowed in this package. Do not add more dependencies.
# The `flutter_lints` dependency is required for `lib/flutter.yaml`.
dependencies:
flutter_lints: ^3.0.0
| samples/analysis_defaults/pubspec.yaml/0 | {
"file_path": "samples/analysis_defaults/pubspec.yaml",
"repo_id": "samples",
"token_count": 100
} | 1,315 |
// 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';
class AnimatedListDemo extends StatefulWidget {
const AnimatedListDemo({super.key});
static String routeName = 'misc/animated_list';
@override
State<AnimatedListDemo> createState() => _AnimatedListDemoState();
}
class _AnimatedListDemoState extends State<AnimatedListDemo> {
final GlobalKey<AnimatedListState> _listKey = GlobalKey();
final listData = [
UserModel(0, 'Govind', 'Dixit'),
UserModel(1, 'Greta', 'Stoll'),
UserModel(2, 'Monty', 'Carlo'),
UserModel(3, 'Petey', 'Cruiser'),
UserModel(4, 'Barry', 'Cade'),
];
final initialListSize = 5;
void addUser() {
setState(() {
var index = listData.length;
listData.add(
UserModel(++_maxIdValue, 'New', 'Person'),
);
_listKey.currentState!
.insertItem(index, duration: const Duration(milliseconds: 300));
});
}
void deleteUser(int id) {
setState(() {
final index = listData.indexWhere((u) => u.id == id);
var user = listData.removeAt(index);
_listKey.currentState!.removeItem(
index,
(context, animation) {
return FadeTransition(
opacity: CurvedAnimation(
parent: animation, curve: const Interval(0.5, 1.0)),
child: SizeTransition(
sizeFactor: CurvedAnimation(
parent: animation, curve: const Interval(0.0, 1.0)),
axisAlignment: 0.0,
child: _buildItem(user),
),
);
},
duration: const Duration(milliseconds: 600),
);
});
}
Widget _buildItem(UserModel user) {
return ListTile(
key: ValueKey<UserModel>(user),
title: Text(user.firstName),
subtitle: Text(user.lastName),
leading: const CircleAvatar(
child: Icon(Icons.person),
),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () => deleteUser(user.id),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AnimatedList'),
actions: [
IconButton(
icon: const Icon(Icons.add),
onPressed: addUser,
),
],
),
body: SafeArea(
child: AnimatedList(
key: _listKey,
initialItemCount: 5,
itemBuilder: (context, index, animation) {
return FadeTransition(
opacity: animation,
child: _buildItem(listData[index]),
);
},
),
),
);
}
}
class UserModel {
UserModel(
this.id,
this.firstName,
this.lastName,
);
final int id;
final String firstName;
final String lastName;
}
int _maxIdValue = 4;
| samples/animations/lib/src/misc/animated_list.dart/0 | {
"file_path": "samples/animations/lib/src/misc/animated_list.dart",
"repo_id": "samples",
"token_count": 1315
} | 1,316 |
A server app built using [Shelf](https://pub.dev/packages/shelf),
configured to enable running with [Docker](https://www.docker.com/).
This sample code handles HTTP GET requests to `/` and `/echo/<message>`
# Running the sample
## Running with the Dart SDK
You can run the example with the [Dart SDK](https://dart.dev/get-dart)
like this:
```
$ dart run bin/server.dart
Server listening on port 8080
```
And then from a second terminal:
```
$ curl http://0.0.0.0:8080
Hello, World!
$ curl http://0.0.0.0:8080/echo/I_love_Dart
I_love_Dart
```
## Running with Docker
If you have [Docker Desktop](https://www.docker.com/get-started) installed, you
can build and run with the `docker` command:
```
$ docker build . -t myserver
$ docker run -it -p 8080:8080 myserver
Server listening on port 8080
```
And then from a second terminal:
```
$ curl http://0.0.0.0:8080
Hello, World!
$ curl http://0.0.0.0:8080/echo/I_love_Dart
I_love_Dart
```
You should see the logging printed in the first terminal:
```
2021-05-06T15:47:04.620417 0:00:00.000158 GET [200] /
2021-05-06T15:47:08.392928 0:00:00.001216 GET [200] /echo/I_love_Dart
```
| samples/code_sharing/server/README.md/0 | {
"file_path": "samples/code_sharing/server/README.md",
"repo_id": "samples",
"token_count": 442
} | 1,317 |
const String kCodeUrl =
'https://github.com/flutter/samples/blob/experimental/context_menus/lib';
| samples/context_menus/lib/constants.dart/0 | {
"file_path": "samples/context_menus/lib/constants.dart",
"repo_id": "samples",
"token_count": 37
} | 1,318 |
import 'package:context_menus/field_types_page.dart';
import 'package:context_menus/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.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 FieldTypesPage example.
await tester.dragUntilVisible(
find.text(FieldTypesPage.title),
find.byType(ListView),
const Offset(0.0, -100.0),
);
await tester.pumpAndSettle();
await tester.tap(find.text(FieldTypesPage.title));
await tester.pumpAndSettle();
expect(
find.descendant(
of: find.byType(AppBar),
matching: find.text(FieldTypesPage.title),
),
findsOneWidget,
);
// Right click on the TextField.
TestGesture gesture = await tester.startGesture(
tester.getTopLeft(find.byType(TextField)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The default context menu for the current platform is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(find.byType(CupertinoTextSelectionToolbar), findsOneWidget);
case TargetPlatform.android:
expect(find.byType(TextSelectionToolbar), findsOneWidget);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(find.byType(DesktopTextSelectionToolbar), findsOneWidget);
case TargetPlatform.macOS:
expect(find.byType(CupertinoDesktopTextSelectionToolbar),
findsOneWidget);
}
// Tap the next field to hide the context menu.
await tester.tap(find.byType(EditableText).at(1));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Right click on the first CupertinoTextField.
gesture = await tester.startGesture(
tester.getTopLeft(find.byType(CupertinoTextField).first),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The default Cupertino context menu is shown.
expect(
find.byType(CupertinoAdaptiveTextSelectionToolbar), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
expect(find.byType(CupertinoTextSelectionToolbar), findsOneWidget);
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(find.byType(CupertinoDesktopTextSelectionToolbar),
findsOneWidget);
}
// Tap the next field to hide the context menu.
await tester.tap(find.byType(CupertinoTextField).at(1));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing);
// Right click on the fixed CupertinoTextField.
gesture = await tester.startGesture(
tester.getTopLeft(find.byType(CupertinoTextField).at(1)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The default adaptive context menu is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(find.byType(CupertinoTextSelectionToolbar), findsOneWidget);
case TargetPlatform.android:
expect(find.byType(TextSelectionToolbar), findsOneWidget);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(find.byType(DesktopTextSelectionToolbar), findsOneWidget);
case TargetPlatform.macOS:
expect(find.byType(CupertinoDesktopTextSelectionToolbar),
findsOneWidget);
}
// Tap the next field to hide the context menu.
await tester.tap(find.byType(CupertinoTextField).at(2));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Right click on the forced CupertinoTextField.
gesture = await tester.startGesture(
tester.getTopLeft(find.byType(CupertinoTextField).at(2)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The DesktopTextSelectionToolbar is shown for all platforms.
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing);
expect(find.byType(DesktopTextSelectionToolbar), findsOneWidget);
// Tap the next field to hide the context menu.
await tester.tap(find.byType(EditableText).last);
await tester.pumpAndSettle();
expect(find.byType(DesktopTextSelectionToolbar), findsNothing);
// Right click on the EditableText.
gesture = await tester.startGesture(
tester.getTopLeft(find.byType(EditableText).first),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// Shows the default context menu.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(find.byType(CupertinoTextSelectionToolbar), findsOneWidget);
case TargetPlatform.android:
expect(find.byType(TextSelectionToolbar), findsOneWidget);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(find.byType(DesktopTextSelectionToolbar), findsOneWidget);
case TargetPlatform.macOS:
expect(find.byType(CupertinoDesktopTextSelectionToolbar),
findsOneWidget);
}
},
variant: TargetPlatformVariant.all(),
// TODO(justinmc): https://github.com/flutter/samples/issues/2086
skip: true,
);
}
| samples/context_menus/test/field_types_page_test.dart/0 | {
"file_path": "samples/context_menus/test/field_types_page_test.dart",
"repo_id": "samples",
"token_count": 2733
} | 1,319 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/deeplink_store_example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/deeplink_store_example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,320 |
// 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 'api_error.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<ApiError> _$apiErrorSerializer = new _$ApiErrorSerializer();
class _$ApiErrorSerializer implements StructuredSerializer<ApiError> {
@override
final Iterable<Type> types = const [ApiError, _$ApiError];
@override
final String wireName = 'ApiError';
@override
Iterable<Object?> serialize(Serializers serializers, ApiError object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[];
Object? value;
value = object.errors;
if (value != null) {
result
..add('errors')
..add(serializers.serialize(value,
specifiedType:
const FullType(BuiltList, const [const FullType(String)])));
}
return result;
}
@override
ApiError deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new ApiErrorBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'errors':
result.errors.replace(serializers.deserialize(value,
specifiedType: const FullType(
BuiltList, const [const FullType(String)]))!
as BuiltList<Object?>);
break;
}
}
return result.build();
}
}
class _$ApiError extends ApiError {
@override
final BuiltList<String>? errors;
factory _$ApiError([void Function(ApiErrorBuilder)? updates]) =>
(new ApiErrorBuilder()..update(updates))._build();
_$ApiError._({this.errors}) : super._();
@override
ApiError rebuild(void Function(ApiErrorBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
ApiErrorBuilder toBuilder() => new ApiErrorBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is ApiError && errors == other.errors;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, errors.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'ApiError')..add('errors', errors))
.toString();
}
}
class ApiErrorBuilder implements Builder<ApiError, ApiErrorBuilder> {
_$ApiError? _$v;
ListBuilder<String>? _errors;
ListBuilder<String> get errors =>
_$this._errors ??= new ListBuilder<String>();
set errors(ListBuilder<String>? errors) => _$this._errors = errors;
ApiErrorBuilder();
ApiErrorBuilder get _$this {
final $v = _$v;
if ($v != null) {
_errors = $v.errors?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(ApiError other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$ApiError;
}
@override
void update(void Function(ApiErrorBuilder)? updates) {
if (updates != null) updates(this);
}
@override
ApiError build() => _build();
_$ApiError _build() {
_$ApiError _$result;
try {
_$result = _$v ?? new _$ApiError._(errors: _errors?.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'errors';
_errors?.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'ApiError', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/api_error.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/api_error.g.dart",
"repo_id": "samples",
"token_count": 1523
} | 1,321 |
// 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 'tags.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Tags> _$tagsSerializer = new _$TagsSerializer();
class _$TagsSerializer implements StructuredSerializer<Tags> {
@override
final Iterable<Type> types = const [Tags, _$Tags];
@override
final String wireName = 'Tags';
@override
Iterable<Object?> serialize(Serializers serializers, Tags object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'title',
serializers.serialize(object.title,
specifiedType: const FullType(String)),
];
return result;
}
@override
Tags deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new TagsBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'title':
result.title = serializers.deserialize(value,
specifiedType: const FullType(String))! as String;
break;
}
}
return result.build();
}
}
class _$Tags extends Tags {
@override
final String title;
factory _$Tags([void Function(TagsBuilder)? updates]) =>
(new TagsBuilder()..update(updates))._build();
_$Tags._({required this.title}) : super._() {
BuiltValueNullFieldError.checkNotNull(title, r'Tags', 'title');
}
@override
Tags rebuild(void Function(TagsBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
TagsBuilder toBuilder() => new TagsBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Tags && title == other.title;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, title.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'Tags')..add('title', title))
.toString();
}
}
class TagsBuilder implements Builder<Tags, TagsBuilder> {
_$Tags? _$v;
String? _title;
String? get title => _$this._title;
set title(String? title) => _$this._title = title;
TagsBuilder();
TagsBuilder get _$this {
final $v = _$v;
if ($v != null) {
_title = $v.title;
_$v = null;
}
return this;
}
@override
void replace(Tags other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Tags;
}
@override
void update(void Function(TagsBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Tags build() => _build();
_$Tags _build() {
final _$result = _$v ??
new _$Tags._(
title:
BuiltValueNullFieldError.checkNotNull(title, r'Tags', 'title'));
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/tags.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/tags.g.dart",
"repo_id": "samples",
"token_count": 1208
} | 1,322 |
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <file_selector_linux/file_selector_plugin.h>
#include <menubar/menubar_plugin.h>
#include <url_launcher_linux/url_launcher_plugin.h>
#include <window_size/window_size_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
g_autoptr(FlPluginRegistrar) menubar_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "MenubarPlugin");
menubar_plugin_register_with_registrar(menubar_registrar);
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
g_autoptr(FlPluginRegistrar) window_size_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "WindowSizePlugin");
window_size_plugin_register_with_registrar(window_size_registrar);
}
| samples/desktop_photo_search/fluent_ui/linux/flutter/generated_plugin_registrant.cc/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/linux/flutter/generated_plugin_registrant.cc",
"repo_id": "samples",
"token_count": 455
} | 1,323 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/desktop_photo_search/material/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/desktop_photo_search/material/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,324 |
# federated_plugin
A Flutter plugin sample that shows how to implement a federated plugin to retrieve current battery level on different platforms.
This sample is currently being built. Not all platforms and functionality are in place.
## Goals for this sample
* Show how to develop a federated plugin which supports Android, iOS, web & desktop.
* Demonstrate how to use Platform Channels to communicate with different platforms including Web and Desktop.
## Questions/issues
If you have a general question about Flutter, the best places to go are:
* [The FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev)
* [The Flutter Gitter channel](https://gitter.im/flutter/flutter)
* [StackOverflow](https://stackoverflow.com/questions/tagged/flutter)
If you run into an issue with the sample itself, please file an issue [here](https://github.com/flutter/samples/issues). | samples/experimental/federated_plugin/README.md/0 | {
"file_path": "samples/experimental/federated_plugin/README.md",
"repo_id": "samples",
"token_count": 231
} | 1,325 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/experimental/federated_plugin/federated_plugin/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,326 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint federated_plugin_macos.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'federated_plugin_macos'
s.version = '0.0.1'
s.summary = 'A new flutter plugin project.'
s.description = <<-DESC
A new flutter plugin project.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'FlutterMacOS'
s.platform = :osx, '10.11'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.swift_version = '5.0'
end
| samples/experimental/federated_plugin/federated_plugin_macos/macos/federated_plugin_macos.podspec/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_macos/macos/federated_plugin_macos.podspec",
"repo_id": "samples",
"token_count": 378
} | 1,327 |
// 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:http/http.dart' as http;
import 'package:linting_tool/model/profiles_store.dart';
import 'package:linting_tool/model/rules_store.dart';
import 'package:linting_tool/routes.dart' as routes;
import 'package:linting_tool/theme/app_theme.dart';
import 'package:linting_tool/widgets/adaptive_nav.dart';
import 'package:provider/provider.dart';
final client = http.Client();
class LintingTool extends StatefulWidget {
const LintingTool({super.key});
static const String homeRoute = routes.homeRoute;
@override
State<LintingTool> createState() => _LintingToolState();
}
class _LintingToolState extends State<LintingTool> {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<RuleStore>(
create: (context) => RuleStore(client),
),
ChangeNotifierProvider<ProfilesStore>(
create: (context) => ProfilesStore(client),
),
],
child: MaterialApp(
title: 'Flutter Linting Tool',
theme: AppTheme.buildReplyLightTheme(context),
darkTheme: AppTheme.buildReplyDarkTheme(context),
themeMode: ThemeMode.light,
initialRoute: LintingTool.homeRoute,
onGenerateRoute: (settings) {
switch (settings.name) {
case LintingTool.homeRoute:
return MaterialPageRoute<void>(
builder: (context) => const AdaptiveNav(),
settings: settings,
);
}
return null;
},
),
);
}
}
| samples/experimental/linting_tool/lib/app.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/app.dart",
"repo_id": "samples",
"token_count": 706
} | 1,328 |
// 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:hive/hive.dart';
class HiveService {
static Future<bool> addBox<T>(T item, String boxName) async {
final openBox = await Hive.openLazyBox<T>(
boxName,
);
final List<T> existingProducts = await getBoxes(boxName);
if (!existingProducts.contains(item)) {
await openBox.add(item);
return true;
}
return false;
}
static Future addBoxes<T>(List<T> items, String boxName) async {
final openBox = await Hive.openLazyBox<T>(
boxName,
);
final Set<T> existingProducts = Set.unmodifiable(await getBoxes(boxName));
for (final item in items) {
if (!existingProducts.contains(item)) {
await openBox.add(item);
}
}
}
static Future deleteBox<T>(T item, String boxName) async {
final openBox = await Hive.openLazyBox<T>(
boxName,
);
final List<T> boxes = await getBoxes(boxName);
for (final box in boxes) {
if (box == item) {
await openBox.deleteAt(boxes.indexOf(item));
}
}
}
static Future updateBox<T>(T item, T newItem, String boxName) async {
final openBox = await Hive.openLazyBox<T>(
boxName,
);
final List<T> boxes = await getBoxes(boxName);
for (final box in boxes) {
if (box == item) {
await openBox.putAt(boxes.indexOf(item), newItem);
}
}
}
static Future<List<T>> getBoxes<T>(String boxName, [String? query]) async {
final openBox = await Hive.openLazyBox<T>(boxName);
final length = openBox.length;
final boxList = <T>[
for (int i = 0; i < length; i++) await openBox.getAt(i) as T
];
return boxList;
}
}
| samples/experimental/linting_tool/lib/repository/hive_service.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/repository/hive_service.dart",
"repo_id": "samples",
"token_count": 716
} | 1,329 |
// The Android Gradle Plugin builds the native code with the Android NDK.
group 'dev.flutter.pedometer'
version '1.0'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
// The Android Gradle Plugin knows how to build native code with the NDK.
classpath 'com.android.tools.build:gradle:7.3.0'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
// Bumping the plugin compileSdkVersion requires all clients of this plugin
// to bump the version in their app.
compileSdkVersion 31
// Bumping the plugin ndkVersion requires all clients of this plugin to bump
// the version in their app and to download a newer version of the NDK.
ndkVersion "23.1.7779620"
// Invoke the shared CMake build with the Android Gradle Plugin.
externalNativeBuild {
cmake {
path "../src/health_connect/CMakeLists.txt"
// The default CMake version for the Android Gradle Plugin is 3.10.2.
// https://developer.android.com/studio/projects/install-ndk#vanilla_cmake
//
// The Flutter tooling requires that developers have CMake 3.10 or later
// installed. You should not increase this version, as doing so will cause
// the plugin to fail to compile for some customers of the plugin.
// version "3.10.2"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
minSdkVersion 21
}
}
| samples/experimental/pedometer/android/build.gradle/0 | {
"file_path": "samples/experimental/pedometer/android/build.gradle",
"repo_id": "samples",
"token_count": 638
} | 1,330 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Pedometer</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>pedometer_example</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>NSMotionUsageDescription</key>
<string>Live stream pedometer</string>
<key>UIApplicationSupportsIndirectInputEvents</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/>
</dict>
</plist>
| samples/experimental/pedometer/example/ios/Runner/Info.plist/0 | {
"file_path": "samples/experimental/pedometer/example/ios/Runner/Info.plist",
"repo_id": "samples",
"token_count": 693
} | 1,331 |
/*
* Copyright (c) 2013, 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_NATIVE_API_H_
#define RUNTIME_INCLUDE_DART_NATIVE_API_H_
#include "dart_api.h" /* NOLINT */
/*
* ==========================================
* Message sending/receiving from native code
* ==========================================
*/
/**
* A Dart_CObject is used for representing Dart objects as native C
* data outside the Dart heap. These objects are totally detached from
* the Dart heap. Only a subset of the Dart objects have a
* representation as a Dart_CObject.
*
* The string encoding in the 'value.as_string' is UTF-8.
*
* All the different types from dart:typed_data are exposed as type
* kTypedData. The specific type from dart:typed_data is in the type
* field of the as_typed_data structure. The length in the
* as_typed_data structure is always in bytes.
*
* The data for kTypedData is copied on message send and ownership remains with
* the caller. The ownership of data for kExternalTyped is passed to the VM on
* message send and returned when the VM invokes the
* Dart_HandleFinalizer callback; a non-NULL callback must be provided.
*/
typedef enum {
Dart_CObject_kNull = 0,
Dart_CObject_kBool,
Dart_CObject_kInt32,
Dart_CObject_kInt64,
Dart_CObject_kDouble,
Dart_CObject_kString,
Dart_CObject_kArray,
Dart_CObject_kTypedData,
Dart_CObject_kExternalTypedData,
Dart_CObject_kSendPort,
Dart_CObject_kCapability,
Dart_CObject_kNativePointer,
Dart_CObject_kUnsupported,
Dart_CObject_kNumberOfTypes
} Dart_CObject_Type;
typedef struct _Dart_CObject {
Dart_CObject_Type type;
union {
bool as_bool;
int32_t as_int32;
int64_t as_int64;
double as_double;
char* as_string;
struct {
Dart_Port id;
Dart_Port origin_id;
} as_send_port;
struct {
int64_t id;
} as_capability;
struct {
intptr_t length;
struct _Dart_CObject** values;
} as_array;
struct {
Dart_TypedData_Type type;
intptr_t length; /* in elements, not bytes */
uint8_t* values;
} as_typed_data;
struct {
Dart_TypedData_Type type;
intptr_t length; /* in elements, not bytes */
uint8_t* data;
void* peer;
Dart_HandleFinalizer callback;
} as_external_typed_data;
struct {
intptr_t ptr;
intptr_t size;
Dart_HandleFinalizer callback;
} as_native_pointer;
} value;
} Dart_CObject;
// This struct is versioned by DART_API_DL_MAJOR_VERSION, bump the version when
// changing this struct.
/**
* Posts a message on some port. The message will contain the Dart_CObject
* object graph rooted in 'message'.
*
* While the message is being sent the state of the graph of Dart_CObject
* structures rooted in 'message' should not be accessed, as the message
* generation will make temporary modifications to the data. When the message
* has been sent the graph will be fully restored.
*
* If true is returned, the message was enqueued, and finalizers for external
* typed data will eventually run, even if the receiving isolate shuts down
* before processing the message. If false is returned, the message was not
* enqueued and ownership of external typed data in the message remains with the
* caller.
*
* This function may be called on any thread when the VM is running (that is,
* after Dart_Initialize has returned and before Dart_Cleanup has been called).
*
* \param port_id The destination port.
* \param message The message to send.
*
* \return True if the message was posted.
*/
DART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message);
/**
* Posts a message on some port. The message will contain the integer 'message'.
*
* \param port_id The destination port.
* \param message The message to send.
*
* \return True if the message was posted.
*/
DART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message);
/**
* A native message handler.
*
* This handler is associated with a native port by calling
* Dart_NewNativePort.
*
* The message received is decoded into the message structure. The
* lifetime of the message data is controlled by the caller. All the
* data references from the message are allocated by the caller and
* will be reclaimed when returning to it.
*/
typedef void (*Dart_NativeMessageHandler)(Dart_Port dest_port_id,
Dart_CObject* message);
/**
* Creates a new native port. When messages are received on this
* native port, then they will be dispatched to the provided native
* message handler.
*
* \param name The name of this port in debugging messages.
* \param handler The C handler to run when messages arrive on the port.
* \param handle_concurrently Is it okay to process requests on this
* native port concurrently?
*
* \return If successful, returns the port id for the native port. In
* case of error, returns ILLEGAL_PORT.
*/
DART_EXPORT Dart_Port Dart_NewNativePort(const char* name,
Dart_NativeMessageHandler handler,
bool handle_concurrently);
/* TODO(turnidge): Currently handle_concurrently is ignored. */
/**
* Closes the native port with the given id.
*
* The port must have been allocated by a call to Dart_NewNativePort.
*
* \param native_port_id The id of the native port to close.
*
* \return Returns true if the port was closed successfully.
*/
DART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id);
/*
* ==================
* Verification Tools
* ==================
*/
/**
* Forces all loaded classes and functions to be compiled eagerly in
* the current isolate..
*
* TODO(turnidge): Document.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CompileAll();
/**
* Finalizes all classes.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_FinalizeAllClasses();
/* This function is intentionally undocumented.
*
* It should not be used outside internal tests.
*/
DART_EXPORT void* Dart_ExecuteInternalCommand(const char* command, void* arg);
#endif /* INCLUDE_DART_NATIVE_API_H_ */ /* NOLINT */
| samples/experimental/pedometer/src/dart-sdk/include/dart_native_api.h/0 | {
"file_path": "samples/experimental/pedometer/src/dart-sdk/include/dart_native_api.h",
"repo_id": "samples",
"token_count": 2081
} | 1,332 |
<?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>Varfont Shader Puzzle</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>varfont_shader_puzzle</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>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
</dict>
</plist>
| samples/experimental/varfont_shader_puzzle/ios/Runner/Info.plist/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/ios/Runner/Info.plist",
"repo_id": "samples",
"token_count": 655
} | 1,333 |
// 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/pages_flow.dart';
import '../styles.dart';
class PageWidth extends SinglePage {
const PageWidth({
super.key,
required super.pageConfig,
});
@override
State<SinglePage> createState() => _PageWidthState();
}
class _PageWidthState extends SinglePageState {
@override
Widget createTopicIntro() {
return LightboxedPanel(
pageConfig: widget.pageConfig,
content: [
Text(
'Width'.toUpperCase(),
style: TextStyles.headlineStyle(),
textAlign: TextAlign.left,
),
Text(
'Fonts can vary by width as well. Choosing a new width setting is better '
'than stretching letters in an image editor, which would just distort the letter. '
'Solve this letter puzzle to clear the glitch and set the width!',
style: TextStyles.bodyStyle(),
textAlign: TextAlign.left,
),
],
);
}
@override
List<Widget> buildWonkyChars() {
return <Widget>[
Positioned(
left: widget.pageConfig.wonkyCharLargeSize * -0.17,
top: widget.pageConfig.wonkyCharLargeSize * -0.2,
child: WonkyChar(
text: 'r',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -0.15 * pi,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
),
WonkyAnimPalette.width(
from: 120,
to: 125,
)
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.3,
top: widget.pageConfig.wonkyCharLargeSize * 0.42,
child: WonkyChar(
text: 'x',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.12 * pi,
animDurationMillis: 3200,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
curve: Curves.easeInOut,
),
WonkyAnimPalette.width(
from: 70,
to: 50,
),
WonkyAnimPalette.offsetY(
from: -6,
to: 2,
curve: Curves.easeInOut,
),
WonkyAnimPalette.rotation(
from: -0.04 * pi,
to: 0.005 * pi,
),
],
),
),
Positioned(
right: widget.pageConfig.wonkyCharLargeSize * 0,
top: widget.pageConfig.wonkyCharLargeSize * -0.2,
child: WonkyChar(
text: 'F',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: 0.15 * pi,
animDurationMillis: 3200,
animationSettings: [
WonkyAnimPalette.width(
from: 120,
to: 125,
),
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
),
],
),
),
// lower half --------------------------------------
Positioned(
left: widget.pageConfig.wonkyCharLargeSize * -0.2,
bottom: widget.pageConfig.wonkyCharLargeSize * -0.3,
child: WonkyChar(
text: 'W',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -0.15 * pi,
animDurationMillis: 6000,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
),
WonkyAnimPalette.width(
from: 75,
to: 50,
),
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.4,
bottom: widget.pageConfig.wonkyCharLargeSize * 0.1,
child: WonkyChar(
text: 'h',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.15 * pi,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
),
WonkyAnimPalette.width(
from: 90,
to: 115,
)
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.75,
bottom: widget.pageConfig.wonkyCharSmallSize * -0.24,
child: WonkyChar(
text: 'K',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.15 * pi,
animDurationMillis: 5000,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
),
WonkyAnimPalette.width(
from: 125,
to: 90,
startAt: 0.3,
endAt: 0.7,
),
],
),
),
Positioned(
right: widget.pageConfig.wonkyCharLargeSize * 0.0,
bottom: widget.pageConfig.wonkyCharLargeSize * 0.1,
child: WonkyChar(
text: '?',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -1.67 * pi,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
),
WonkyAnimPalette.width(
from: 110,
to: 60,
)
],
),
),
];
}
@override
Widget createPuzzle() {
return RotatorPuzzle(
pageConfig: widget.pageConfig,
numTiles: 16,
puzzleNum: 2,
shader: Shader.bwSplit,
shaderDuration: 2000,
tileShadedString: 'S',
tileShadedStringPadding: EdgeInsets.only(
left: 0.349 * widget.pageConfig.puzzleSize,
right: 0.349 * widget.pageConfig.puzzleSize),
tileShadedStringSize: 3.256 * widget.pageConfig.puzzleSize,
tileScaleModifier: 2.34,
tileShadedStringAnimDuration: 2000,
tileShadedStringAnimSettings: [
WonkyAnimPalette.weight(from: 200, to: 200),
WonkyAnimPalette.width(from: 50, to: 125),
],
);
}
}
| samples/experimental/varfont_shader_puzzle/lib/page_content/page_width.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/page_content/page_width.dart",
"repo_id": "samples",
"token_count": 3341
} | 1,334 |
// 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;
int speed;
// wavy
speed = 1;
float xAdj = texCoord.x * 3 * PI;
float waveFnVal = sin((xAdj + piTime * speed));
float hackAdj = 0.0;
float offset = ( ((pow(waveFnVal, 2) * 0.5 - 0.5) * 0.2) + hackAdj ) * uDampener;
vec2 offsetTexCoord = vec2(texCoord.x, texCoord.y + offset);
fragColor = texture(uTexture, offsetTexCoord);
}
| samples/experimental/varfont_shader_puzzle/shaders/wavy.frag/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/shaders/wavy.frag",
"repo_id": "samples",
"token_count": 293
} | 1,335 |
// 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 'dart:async';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:uuid/uuid.dart' as uuid;
import 'api.dart';
class MockDashboardApi implements DashboardApi {
@override
final EntryApi entries = MockEntryApi();
@override
final CategoryApi categories = MockCategoryApi();
MockDashboardApi();
/// Creates a [MockDashboardApi] filled with mock data for the last 30 days.
Future<void> fillWithMockData() async {
await Future<void>.delayed(const Duration(seconds: 1));
var category1 = await categories.insert(Category('Coffee (oz)'));
var category2 = await categories.insert(Category('Running (miles)'));
var category3 = await categories.insert(Category('Git Commits'));
var monthAgo = DateTime.now().subtract(const Duration(days: 30));
for (var category in [category1, category2, category3]) {
for (var i = 0; i < 30; i++) {
var date = monthAgo.add(Duration(days: i));
var value = Random().nextInt(6) + 1;
await entries.insert(category.id!, Entry(value, date));
}
}
}
}
class MockCategoryApi implements CategoryApi {
final Map<String, Category> _storage = {};
final StreamController<List<Category>> _streamController =
StreamController<List<Category>>.broadcast();
@override
Future<Category?> delete(String id) async {
var removed = _storage.remove(id);
_emit();
return removed;
}
@override
Future<Category?> get(String id) async {
return _storage[id];
}
@override
Future<Category> insert(Category category) async {
var id = const uuid.Uuid().v4();
var newCategory = Category(category.name)..id = id;
_storage[id] = newCategory;
_emit();
return newCategory;
}
@override
Future<List<Category>> list() async {
return _storage.values.toList();
}
@override
Future<Category> update(Category category, String id) async {
_storage[id] = category;
_emit();
return category..id = id;
}
@override
Stream<List<Category>> subscribe() => _streamController.stream;
void _emit() {
_streamController.add(_storage.values.toList());
}
}
class MockEntryApi implements EntryApi {
final Map<String, Entry> _storage = {};
final StreamController<_EntriesEvent> _streamController =
StreamController.broadcast();
@override
Future<Entry?> delete(String categoryId, String id) async {
_emit(categoryId);
return _storage.remove('$categoryId-$id');
}
@override
Future<Entry> insert(String categoryId, Entry entry) async {
var id = const uuid.Uuid().v4();
var newEntry = Entry(entry.value, entry.time)..id = id;
_storage['$categoryId-$id'] = newEntry;
_emit(categoryId);
return newEntry;
}
@override
Future<List<Entry>> list(String categoryId) async {
var list = _storage.keys
.where((k) => k.startsWith(categoryId))
.map((k) => _storage[k])
.whereNotNull()
.toList();
return list;
}
@override
Future<Entry> update(String categoryId, String id, Entry entry) async {
_storage['$categoryId-$id'] = entry;
_emit(categoryId);
return entry..id = id;
}
@override
Stream<List<Entry>> subscribe(String categoryId) {
return _streamController.stream
.where((event) => event.categoryId == categoryId)
.map((event) => event.entries);
}
void _emit(String categoryId) {
var entries = _storage.keys
.where((k) => k.startsWith(categoryId))
.map((k) => _storage[k]!)
.toList();
_streamController.add(_EntriesEvent(categoryId, entries));
}
@override
Future<Entry?> get(String categoryId, String id) async {
return _storage['$categoryId-$id'];
}
}
class _EntriesEvent {
final String categoryId;
final List<Entry> entries;
_EntriesEvent(this.categoryId, this.entries);
}
| samples/experimental/web_dashboard/lib/src/api/mock.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/api/mock.dart",
"repo_id": "samples",
"token_count": 1448
} | 1,336 |
// 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/material.dart';
bool _isLargeScreen(BuildContext context) {
return MediaQuery.of(context).size.width > 960.0;
}
bool _isMediumScreen(BuildContext context) {
return MediaQuery.of(context).size.width > 640.0;
}
/// See bottomNavigationBarItem or NavigationRailDestination
class AdaptiveScaffoldDestination {
final String title;
final IconData icon;
const AdaptiveScaffoldDestination({
required this.title,
required this.icon,
});
}
/// A widget that adapts to the current display size, displaying a [Drawer],
/// [NavigationRail], or [BottomNavigationBar]. Navigation destinations are
/// defined in the [destinations] parameter.
class AdaptiveScaffold extends StatefulWidget {
final Widget? title;
final List<Widget> actions;
final Widget? body;
final int currentIndex;
final List<AdaptiveScaffoldDestination> destinations;
final ValueChanged<int>? onNavigationIndexChange;
final FloatingActionButton? floatingActionButton;
const AdaptiveScaffold({
this.title,
this.body,
this.actions = const [],
required this.currentIndex,
required this.destinations,
this.onNavigationIndexChange,
this.floatingActionButton,
super.key,
});
@override
State<AdaptiveScaffold> createState() => _AdaptiveScaffoldState();
}
class _AdaptiveScaffoldState extends State<AdaptiveScaffold> {
@override
Widget build(BuildContext context) {
// Show a Drawer
if (_isLargeScreen(context)) {
return Row(
children: [
Drawer(
child: Column(
children: [
DrawerHeader(
child: Center(
child: widget.title,
),
),
for (var d in widget.destinations)
ListTile(
leading: Icon(d.icon),
title: Text(d.title),
selected:
widget.destinations.indexOf(d) == widget.currentIndex,
onTap: () => _destinationTapped(d),
),
],
),
),
VerticalDivider(
width: 1,
thickness: 1,
color: Colors.grey[300],
),
Expanded(
child: Scaffold(
appBar: AppBar(
actions: widget.actions,
),
body: widget.body,
floatingActionButton: widget.floatingActionButton,
),
),
],
);
}
// Show a navigation rail
if (_isMediumScreen(context)) {
return Scaffold(
appBar: AppBar(
title: widget.title,
actions: widget.actions,
),
body: Row(
children: [
NavigationRail(
leading: widget.floatingActionButton,
destinations: [
...widget.destinations.map(
(d) => NavigationRailDestination(
icon: Icon(d.icon),
label: Text(d.title),
),
),
],
selectedIndex: widget.currentIndex,
onDestinationSelected: widget.onNavigationIndexChange ?? (_) {},
),
VerticalDivider(
width: 1,
thickness: 1,
color: Colors.grey[300],
),
Expanded(
child: widget.body!,
),
],
),
);
}
// Show a bottom app bar
return Scaffold(
body: widget.body,
appBar: AppBar(
title: widget.title,
actions: widget.actions,
),
bottomNavigationBar: BottomNavigationBar(
items: [
...widget.destinations.map(
(d) => BottomNavigationBarItem(
icon: Icon(d.icon),
label: d.title,
),
),
],
currentIndex: widget.currentIndex,
onTap: widget.onNavigationIndexChange,
),
floatingActionButton: widget.floatingActionButton,
);
}
void _destinationTapped(AdaptiveScaffoldDestination destination) {
var idx = widget.destinations.indexOf(destination);
if (idx != widget.currentIndex) {
widget.onNavigationIndexChange!(idx);
}
}
}
| samples/experimental/web_dashboard/lib/src/widgets/third_party/adaptive_scaffold.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/widgets/third_party/adaptive_scaffold.dart",
"repo_id": "samples",
"token_count": 2122
} | 1,337 |
include: package:analysis_defaults/flutter.yaml
| samples/form_app/analysis_options.yaml/0 | {
"file_path": "samples/form_app/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,338 |
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
// Set up a mock HTTP client.
final http.Client mockClient = MockClient(_mockHandler);
Future<http.Response> _mockHandler(http.Request request) async {
var decodedJson = Map<String, dynamic>.from(
json.decode(request.body) as Map<String, dynamic>);
if (decodedJson['email'] == 'root' && decodedJson['password'] == 'password') {
return http.Response('', 200);
}
return http.Response('', 401);
}
| samples/form_app/lib/src/http/mock_client.dart/0 | {
"file_path": "samples/form_app/lib/src/http/mock_client.dart",
"repo_id": "samples",
"token_count": 176
} | 1,339 |
// 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/foundation.dart';
/// Encapsulates a score and the arithmetic to compute it.
@immutable
class Score {
final int score;
final Duration duration;
final int level;
factory Score(int level, int difficulty, Duration duration) {
// The higher the difficulty, the higher the score.
var score = difficulty;
// The lower the time to beat the level, the higher the score.
score *= 10000 ~/ (duration.inSeconds.abs() + 1);
return Score._(score, duration, level);
}
const Score._(this.score, this.duration, this.level);
String get formattedTime {
final buf = StringBuffer();
if (duration.inHours > 0) {
buf.write('${duration.inHours}');
buf.write(':');
}
final minutes = duration.inMinutes % Duration.minutesPerHour;
if (minutes > 9) {
buf.write('$minutes');
} else {
buf.write('0');
buf.write('$minutes');
}
buf.write(':');
buf.write((duration.inSeconds % Duration.secondsPerMinute)
.toString()
.padLeft(2, '0'));
return buf.toString();
}
@override
String toString() => 'Score<$score,$formattedTime,$level>';
}
| samples/game_template/lib/src/games_services/score.dart/0 | {
"file_path": "samples/game_template/lib/src/games_services/score.dart",
"repo_id": "samples",
"token_count": 473
} | 1,340 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../in_app_purchase/in_app_purchase.dart';
import '../player_progress/player_progress.dart';
import '../style/palette.dart';
import '../style/responsive_screen.dart';
import 'custom_name_dialog.dart';
import 'settings.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
static const _gap = SizedBox(height: 60);
@override
Widget build(BuildContext context) {
final settings = context.watch<SettingsController>();
final palette = context.watch<Palette>();
return Scaffold(
backgroundColor: palette.backgroundSettings,
body: ResponsiveScreen(
squarishMainArea: ListView(
children: [
_gap,
const Text(
'Settings',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Permanent Marker',
fontSize: 55,
height: 1,
),
),
_gap,
const _NameChangeLine(
'Name',
),
ValueListenableBuilder<bool>(
valueListenable: settings.soundsOn,
builder: (context, soundsOn, child) => _SettingsLine(
'Sound FX',
Icon(soundsOn ? Icons.graphic_eq : Icons.volume_off),
onSelected: () => settings.toggleSoundsOn(),
),
),
ValueListenableBuilder<bool>(
valueListenable: settings.musicOn,
builder: (context, musicOn, child) => _SettingsLine(
'Music',
Icon(musicOn ? Icons.music_note : Icons.music_off),
onSelected: () => settings.toggleMusicOn(),
),
),
Consumer<InAppPurchaseController?>(
builder: (context, inAppPurchase, child) {
if (inAppPurchase == null) {
// In-app purchases are not supported yet.
// Go to lib/main.dart and uncomment the lines that create
// the InAppPurchaseController.
return const SizedBox.shrink();
}
Widget icon;
VoidCallback? callback;
if (inAppPurchase.adRemoval.active) {
icon = const Icon(Icons.check);
} else if (inAppPurchase.adRemoval.pending) {
icon = const CircularProgressIndicator();
} else {
icon = const Icon(Icons.ad_units);
callback = () {
inAppPurchase.buy();
};
}
return _SettingsLine(
'Remove ads',
icon,
onSelected: callback,
);
}),
_SettingsLine(
'Reset progress',
const Icon(Icons.delete),
onSelected: () {
context.read<PlayerProgress>().reset();
final messenger = ScaffoldMessenger.of(context);
messenger.showSnackBar(
const SnackBar(
content: Text('Player progress has been reset.')),
);
},
),
_gap,
],
),
rectangularMenuArea: FilledButton(
onPressed: () {
GoRouter.of(context).pop();
},
child: const Text('Back'),
),
),
);
}
}
class _NameChangeLine extends StatelessWidget {
final String title;
const _NameChangeLine(this.title);
@override
Widget build(BuildContext context) {
final settings = context.watch<SettingsController>();
return InkResponse(
highlightShape: BoxShape.rectangle,
onTap: () => showCustomNameDialog(context),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(title,
style: const TextStyle(
fontFamily: 'Permanent Marker',
fontSize: 30,
)),
const Spacer(),
ValueListenableBuilder(
valueListenable: settings.playerName,
builder: (context, name, child) => Text(
'‘$name’',
style: const TextStyle(
fontFamily: 'Permanent Marker',
fontSize: 30,
),
),
),
],
),
),
);
}
}
class _SettingsLine extends StatelessWidget {
final String title;
final Widget icon;
final VoidCallback? onSelected;
const _SettingsLine(this.title, this.icon, {this.onSelected});
@override
Widget build(BuildContext context) {
return InkResponse(
highlightShape: BoxShape.rectangle,
onTap: onSelected,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: 'Permanent Marker',
fontSize: 30,
),
),
),
icon,
],
),
),
);
}
}
| samples/game_template/lib/src/settings/settings_screen.dart/0 | {
"file_path": "samples/game_template/lib/src/settings/settings_screen.dart",
"repo_id": "samples",
"token_count": 2916
} | 1,341 |
name: infinitelist
description: >
A sample implementation of an infinite list.
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
meta: ^1.3.0
provider: ^6.0.2
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| samples/infinite_list/pubspec.yaml/0 | {
"file_path": "samples/infinite_list/pubspec.yaml",
"repo_id": "samples",
"token_count": 211
} | 1,342 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| samples/isolate_example/android/gradle.properties/0 | {
"file_path": "samples/isolate_example/android/gradle.properties",
"repo_id": "samples",
"token_count": 30
} | 1,343 |
// 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';
import 'constants.dart';
import 'home.dart';
void main() async {
var analyzer = WebStartupAnalyzer(additionalFrameCount: 10);
debugPrint(json.encode(analyzer.startupTiming));
analyzer.onFirstFrame.addListener(() {
debugPrint(json.encode({'firstFrame': analyzer.onFirstFrame.value}));
});
analyzer.onFirstPaint.addListener(() {
debugPrint(json.encode({
'firstPaint': analyzer.onFirstPaint.value?.$1,
'firstContentfulPaint': analyzer.onFirstPaint.value?.$2,
}));
});
analyzer.onAdditionalFrames.addListener(() {
debugPrint(json.encode({
'additionalFrames': analyzer.onAdditionalFrames.value,
}));
});
runApp(
const App(),
);
}
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
bool useMaterial3 = true;
ThemeMode themeMode = ThemeMode.system;
ColorSeed colorSelected = ColorSeed.baseColor;
ColorImageProvider imageSelected = ColorImageProvider.leaves;
ColorScheme? imageColorScheme = const ColorScheme.light();
ColorSelectionMethod colorSelectionMethod = ColorSelectionMethod.colorSeed;
bool get useLightMode => switch (themeMode) {
ThemeMode.system =>
View.of(context).platformDispatcher.platformBrightness ==
Brightness.light,
ThemeMode.light => true,
ThemeMode.dark => false
};
void handleBrightnessChange(bool useLightMode) {
setState(() {
themeMode = useLightMode ? ThemeMode.light : ThemeMode.dark;
});
}
void handleMaterialVersionChange() {
setState(() {
useMaterial3 = !useMaterial3;
});
}
void handleColorSelect(int value) {
setState(() {
colorSelectionMethod = ColorSelectionMethod.colorSeed;
colorSelected = ColorSeed.values[value];
});
}
void handleImageSelect(int value) {
final String url = ColorImageProvider.values[value].url;
ColorScheme.fromImageProvider(provider: NetworkImage(url))
.then((newScheme) {
setState(() {
colorSelectionMethod = ColorSelectionMethod.image;
imageSelected = ColorImageProvider.values[value];
imageColorScheme = newScheme;
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material 3',
themeMode: themeMode,
theme: ThemeData(
colorSchemeSeed: colorSelectionMethod == ColorSelectionMethod.colorSeed
? colorSelected.color
: null,
colorScheme: colorSelectionMethod == ColorSelectionMethod.image
? imageColorScheme
: null,
useMaterial3: useMaterial3,
brightness: Brightness.light,
),
darkTheme: ThemeData(
colorSchemeSeed: colorSelectionMethod == ColorSelectionMethod.colorSeed
? colorSelected.color
: imageColorScheme!.primary,
useMaterial3: useMaterial3,
brightness: Brightness.dark,
),
home: Home(
useLightMode: useLightMode,
useMaterial3: useMaterial3,
colorSelected: colorSelected,
imageSelected: imageSelected,
handleBrightnessChange: handleBrightnessChange,
handleMaterialVersionChange: handleMaterialVersionChange,
handleColorSelect: handleColorSelect,
handleImageSelect: handleImageSelect,
colorSelectionMethod: colorSelectionMethod,
),
);
}
}
| samples/material_3_demo/lib/main.dart/0 | {
"file_path": "samples/material_3_demo/lib/main.dart",
"repo_id": "samples",
"token_count": 1430
} | 1,344 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/material_3_demo/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/material_3_demo/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,345 |
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
class BooksScreen extends StatefulWidget {
final Widget child;
final ValueChanged<int> onTap;
final int selectedIndex;
const BooksScreen({
required this.child,
required this.onTap,
required this.selectedIndex,
super.key,
});
@override
State<BooksScreen> createState() => _BooksScreenState();
}
class _BooksScreenState extends State<BooksScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this)
..addListener(_handleTabIndexChanged);
}
@override
void dispose() {
_tabController.removeListener(_handleTabIndexChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
_tabController.index = widget.selectedIndex;
return Scaffold(
appBar: AppBar(
title: const Text('Books'),
bottom: TabBar(
controller: _tabController,
tabs: const [
Tab(
text: 'Popular',
icon: Icon(Icons.people),
),
Tab(
text: 'New',
icon: Icon(Icons.new_releases),
),
Tab(
text: 'All',
icon: Icon(Icons.list),
),
],
),
),
body: widget.child,
);
}
void _handleTabIndexChanged() {
widget.onTap(_tabController.index);
}
}
| samples/navigation_and_routing/lib/src/screens/books.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/screens/books.dart",
"repo_id": "samples",
"token_count": 700
} | 1,346 |
// 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:provider/provider.dart';
import 'place.dart';
import 'place_tracker_app.dart';
class PlaceList extends StatefulWidget {
const PlaceList({super.key});
@override
State<PlaceList> createState() => _PlaceListState();
}
class _PlaceListState extends State<PlaceList> {
final ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
var state = Provider.of<AppState>(context);
return Column(
children: [
_ListCategoryButtonBar(
selectedCategory: state.selectedCategory,
onCategoryChanged: (value) => _onCategoryChanged(value),
),
Expanded(
child: ListView(
padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 8.0),
controller: _scrollController,
shrinkWrap: true,
children: state.places
.where((place) => place.category == state.selectedCategory)
.map((place) => _PlaceListTile(place: place))
.toList(),
),
),
],
);
}
void _onCategoryChanged(PlaceCategory newCategory) {
_scrollController.jumpTo(0.0);
Provider.of<AppState>(context, listen: false)
.setSelectedCategory(newCategory);
}
}
class _CategoryButton extends StatelessWidget {
final PlaceCategory category;
final bool selected;
final ValueChanged<PlaceCategory> onCategoryChanged;
const _CategoryButton({
required this.category,
required this.selected,
required this.onCategoryChanged,
});
@override
Widget build(BuildContext context) {
final buttonText = switch (category) {
PlaceCategory.favorite => 'Favorites',
PlaceCategory.visited => 'Visited',
PlaceCategory.wantToGo => 'Want To Go'
};
return Container(
margin: const EdgeInsets.symmetric(vertical: 12.0),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: selected ? Colors.blue : Colors.transparent,
),
),
),
child: ButtonTheme(
height: 50.0,
child: TextButton(
child: Text(
buttonText,
style: TextStyle(
fontSize: selected ? 20.0 : 18.0,
color: selected ? Colors.blue : Colors.black87,
),
),
onPressed: () => onCategoryChanged(category),
),
),
);
}
}
class _ListCategoryButtonBar extends StatelessWidget {
final PlaceCategory selectedCategory;
final ValueChanged<PlaceCategory> onCategoryChanged;
const _ListCategoryButtonBar({
required this.selectedCategory,
required this.onCategoryChanged,
});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_CategoryButton(
category: PlaceCategory.favorite,
selected: selectedCategory == PlaceCategory.favorite,
onCategoryChanged: onCategoryChanged,
),
_CategoryButton(
category: PlaceCategory.visited,
selected: selectedCategory == PlaceCategory.visited,
onCategoryChanged: onCategoryChanged,
),
_CategoryButton(
category: PlaceCategory.wantToGo,
selected: selectedCategory == PlaceCategory.wantToGo,
onCategoryChanged: onCategoryChanged,
),
],
);
}
}
class _PlaceListTile extends StatelessWidget {
final Place place;
const _PlaceListTile({
required this.place,
});
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => context.go('/place/${place.id}'),
child: Container(
padding: const EdgeInsets.only(top: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
place.name,
textAlign: TextAlign.left,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
maxLines: 3,
),
Row(
children: List.generate(5, (index) {
return Icon(
Icons.star,
size: 28.0,
color: place.starRating > index
? Colors.amber
: Colors.grey[400],
);
}).toList(),
),
Text(
place.description ?? '',
style: Theme.of(context).textTheme.titleMedium,
maxLines: 4,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 16.0),
Divider(
height: 2.0,
color: Colors.grey[700],
),
],
),
),
);
}
}
| samples/place_tracker/lib/place_list.dart/0 | {
"file_path": "samples/place_tracker/lib/place_list.dart",
"repo_id": "samples",
"token_count": 2285
} | 1,347 |
include: package:analysis_defaults/flutter.yaml
| samples/platform_channels/analysis_options.yaml/0 | {
"file_path": "samples/platform_channels/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,348 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform_channels/src/event_channel_demo.dart';
void main() {
group('EventChannel Demo tests', () {
final sensorValues = [1.3556, 2.3, -0.12];
setUpAll(() {
// By default EventChannel uses StandardMethodCodec to communicate with
// platform.
const standardMethod = StandardMethodCodec();
// This function handles the incoming messages from the platform. It
// calls the BinaryMessenger.setMessageHandler registered for the EventChannel
// and add the incoming message to the StreamController used by the EventChannel
// after decoding the message with codec used by the EventChannel.
void emitValues(ByteData? event) {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
'eventChannelDemo',
event,
(reply) {},
);
}
// Register a mock for EventChannel. EventChannel under the hood uses
// MethodChannel to listen and cancel the created stream.
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMessageHandler('eventChannelDemo', (message) async {
// Decode the message into MethodCallHandler.
final methodCall = standardMethod.decodeMethodCall(message);
if (methodCall.method == 'listen') {
// Emit new sensor values.
emitValues(standardMethod.encodeSuccessEnvelope(sensorValues));
emitValues(null);
return standardMethod.encodeSuccessEnvelope(null);
} else if (methodCall.method == 'cancel') {
return standardMethod.encodeSuccessEnvelope(null);
} else {
fail('Expected listen or cancel');
}
});
});
testWidgets('EventChannel AccelerometerReadings Stream test',
(tester) async {
await tester.pumpWidget(const MaterialApp(
home: EventChannelDemo(),
));
await tester.pumpAndSettle();
// Check the values of axis. The value is rounded to 3 decimal places.
expect(
find.text('x axis: ${sensorValues[0].toStringAsFixed(3)}'),
findsOneWidget,
);
expect(
find.text('y axis: ${sensorValues[1].toStringAsFixed(3)}'),
findsOneWidget,
);
expect(
find.text('z axis: ${sensorValues[2].toStringAsFixed(3)}'),
findsOneWidget,
);
});
});
}
| samples/platform_channels/test/src/event_channel_demo_test.dart/0 | {
"file_path": "samples/platform_channels/test/src/event_channel_demo_test.dart",
"repo_id": "samples",
"token_count": 1010
} | 1,349 |
#include "Generated.xcconfig"
| samples/platform_design/ios/Flutter/Release.xcconfig/0 | {
"file_path": "samples/platform_design/ios/Flutter/Release.xcconfig",
"repo_id": "samples",
"token_count": 12
} | 1,350 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:window_size/window_size.dart';
void main() {
setupWindow();
runApp(
// Provide the model to all widgets within the app. We're using
// ChangeNotifierProvider because that's a simple way to rebuild
// widgets when a model changes. We could also just use
// Provider, but then we would have to listen to Counter ourselves.
//
// Read Provider's docs to learn about all the available providers.
ChangeNotifierProvider(
// Initialize the model in the builder. That way, Provider
// can own Counter's lifecycle, making sure to call `dispose`
// when not needed anymore.
create: (context) => Counter(),
child: const MyApp(),
),
);
}
const double windowWidth = 360;
const double windowHeight = 640;
void setupWindow() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
WidgetsFlutterBinding.ensureInitialized();
setWindowTitle('Provider Counter');
setWindowMinSize(const Size(windowWidth, windowHeight));
setWindowMaxSize(const Size(windowWidth, windowHeight));
getCurrentScreen().then((screen) {
setWindowFrame(Rect.fromCenter(
center: screen!.frame.center,
width: windowWidth,
height: windowHeight,
));
});
}
}
/// Simplest possible model, with just one field.
///
/// [ChangeNotifier] is a class in `flutter:foundation`. [Counter] does
/// _not_ depend on Provider.
class Counter with ChangeNotifier {
int value = 0;
void increment() {
value += 1;
notifyListeners();
}
}
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 MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo Home Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button this many times:'),
// Consumer looks for an ancestor Provider widget
// and retrieves its model (Counter, in this case).
// Then it uses that model to build widgets, and will trigger
// rebuilds if the model is updated.
Consumer<Counter>(
builder: (context, counter, child) => Text(
'${counter.value}',
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// You can access your providers anywhere you have access
// to the context. One way is to use Provider.of<Counter>(context).
//
// The provider package also defines extension methods on context
// itself. You can call context.watch<Counter>() in a build method
// of any widget to access the current state of Counter, and to ask
// Flutter to rebuild your widget anytime Counter changes.
//
// You can't use context.watch() outside build methods, because that
// often leads to subtle bugs. Instead, you should use
// context.read<Counter>(), which gets the current state
// but doesn't ask Flutter for future rebuilds.
//
// Since we're in a callback that will be called whenever the user
// taps the FloatingActionButton, we are not in the build method here.
// We should use context.read().
var counter = context.read<Counter>();
counter.increment();
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
| samples/provider_counter/lib/main.dart/0 | {
"file_path": "samples/provider_counter/lib/main.dart",
"repo_id": "samples",
"token_count": 1586
} | 1,351 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/provider_counter/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/provider_counter/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,352 |
import 'package:flutter/widgets.dart';
import 'app_state.dart';
class AppStateManager extends InheritedWidget {
const AppStateManager({
super.key,
required super.child,
required AppState state,
}) : _appState = state;
static AppStateManager of(BuildContext context) {
final AppStateManager? result =
context.dependOnInheritedWidgetOfExactType<AppStateManager>();
assert(result != null, 'No AppStateManager found in context');
return result!;
}
final AppState _appState;
AppState get appState => _appState;
@override
bool updateShouldNotify(AppStateManager oldWidget) {
return appState != oldWidget.appState;
}
}
| samples/simplistic_editor/lib/app_state_manager.dart/0 | {
"file_path": "samples/simplistic_editor/lib/app_state_manager.dart",
"repo_id": "samples",
"token_count": 219
} | 1,353 |
// 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:developer';
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() {
return integrationDriver(
responseDataCallback: (data) async {
// If the tests reported any data, save it to the disk.
if (data != null) {
for (var entry in data.entries) {
log('Writing ${entry.key} to the disk.');
// Default storage destination is the 'build' directory.
await writeResponseData(
entry.value as Map<String, dynamic>,
testOutputFilename: entry.key,
);
}
}
},
);
}
| samples/testing_app/integration_test/perf_driver.dart/0 | {
"file_path": "samples/testing_app/integration_test/perf_driver.dart",
"repo_id": "samples",
"token_count": 290
} | 1,354 |
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:veggieseasons/styles.dart';
/// Partially overlays and then blurs its child's background.
class FrostedBox extends StatelessWidget {
const FrostedBox({
this.child,
super.key,
});
final Widget? child;
@override
Widget build(BuildContext context) {
return BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: DecoratedBox(
decoration: const BoxDecoration(
color: Styles.frostedBackground,
),
child: child,
),
);
}
}
/// An Icon that implicitly animates changes to its color.
class ColorChangingIcon extends ImplicitlyAnimatedWidget {
const ColorChangingIcon(
this.icon, {
this.color = CupertinoColors.black,
this.size,
required super.duration,
super.key,
});
final Color color;
final IconData icon;
final double? size;
@override
AnimatedWidgetBaseState<ColorChangingIcon> createState() =>
_ColorChangingIconState();
}
class _ColorChangingIconState
extends AnimatedWidgetBaseState<ColorChangingIcon> {
ColorTween? _colorTween;
@override
Widget build(BuildContext context) {
return Icon(
widget.icon,
semanticLabel: 'Close button',
size: widget.size,
color: _colorTween?.evaluate(animation),
);
}
@override
void forEachTween(TweenVisitor<dynamic> visitor) {
_colorTween = visitor(
_colorTween,
widget.color,
(dynamic value) => ColorTween(begin: value as Color?),
) as ColorTween?;
}
}
/// A simple "close this modal" button that invokes a callback when pressed.
class CloseButton extends StatefulWidget {
const CloseButton(this.onPressed, {super.key});
final VoidCallback onPressed;
@override
State<CloseButton> createState() => _CloseButtonState();
}
class _CloseButtonState extends State<CloseButton> {
bool tapInProgress = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (details) {
setState(() => tapInProgress = true);
},
onTapUp: (details) {
setState(() => tapInProgress = false);
widget.onPressed();
},
onTapCancel: () {
setState(() => tapInProgress = false);
},
child: ClipOval(
child: FrostedBox(
child: Container(
width: 30,
height: 30,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
child: Center(
child: ColorChangingIcon(
CupertinoIcons.clear_thick,
duration: const Duration(milliseconds: 300),
color: tapInProgress
? Styles.closeButtonPressed
: Styles.closeButtonUnpressed,
size: 20,
),
),
),
),
),
);
}
}
| samples/veggieseasons/lib/widgets/close_button.dart/0 | {
"file_path": "samples/veggieseasons/lib/widgets/close_button.dart",
"repo_id": "samples",
"token_count": 1279
} | 1,355 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "f5fb61b953a631f47191124a31169701911ee1f4"
channel: "main"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: f5fb61b953a631f47191124a31169701911ee1f4
base_revision: f5fb61b953a631f47191124a31169701911ee1f4
- platform: android
create_revision: f5fb61b953a631f47191124a31169701911ee1f4
base_revision: f5fb61b953a631f47191124a31169701911ee1f4
- platform: ios
create_revision: f5fb61b953a631f47191124a31169701911ee1f4
base_revision: f5fb61b953a631f47191124a31169701911ee1f4
- platform: linux
create_revision: f5fb61b953a631f47191124a31169701911ee1f4
base_revision: f5fb61b953a631f47191124a31169701911ee1f4
- platform: macos
create_revision: f5fb61b953a631f47191124a31169701911ee1f4
base_revision: f5fb61b953a631f47191124a31169701911ee1f4
- platform: web
create_revision: f5fb61b953a631f47191124a31169701911ee1f4
base_revision: f5fb61b953a631f47191124a31169701911ee1f4
- platform: windows
create_revision: f5fb61b953a631f47191124a31169701911ee1f4
base_revision: f5fb61b953a631f47191124a31169701911ee1f4
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| samples/web/_packages/web_startup_analyzer/example/.metadata/0 | {
"file_path": "samples/web/_packages/web_startup_analyzer/example/.metadata",
"repo_id": "samples",
"token_count": 738
} | 1,356 |
# Configuration for https://pub.dartlang.org/packages/peanut
directories:
- animations/web
- provider_shopper/web
- charts/web
- filipino_cuisine/web
- github_dataviz/web
- particle_background/web
- slide_puzzle/web
- form_app/web
- web_dashboard/web
- place_tracker/web
post-build-dart-script: _tool/peanut_post_build.dart
| samples/web/peanut.yaml/0 | {
"file_path": "samples/web/peanut.yaml",
"repo_id": "samples",
"token_count": 122
} | 1,357 |
name: samples_index
description: A visual index of Flutter samples.
homepage: https://github.com/flutter/samples/tree/main/web/samples_index
version: 0.0.1
publish_to: none
environment:
sdk: ^3.2.0
dependencies:
checked_yaml: ^2.0.3
json_annotation: ^4.8.1
mdc_web: ^0.6.0
path: ^1.8.3
sass_builder: ^2.2.1
yaml: ^3.1.2
dev_dependencies:
build: ^2.4.0
build_runner: ^2.4.2
build_web_compilers: ^4.0.3
grinder: ^0.9.4
image: ^4.1.3
json_serializable: ^6.6.2
lints: ^3.0.0
test: ^1.24.2
# package:mdc_web needs to upgrade the version of material-components-web 12.0.0
# or above, which includes this fix for the division operator:
# https://github.com/material-components/material-components-web/pull/7158
#
# Until then, dart-sass produces a warning that this operator is being removed
# in favor of calc().
#
# See this issue for details:
# https://github.com/dart-lang/dart-pad/issues/2388
dependency_overrides:
sass: ^1.62.0 | samples/web/samples_index/pubspec.yaml/0 | {
"file_path": "samples/web/samples_index/pubspec.yaml",
"repo_id": "samples",
"token_count": 392
} | 1,358 |
# element_embedding_demo
This package contains the application used to demonstrate the
upcoming Flutter web feature: "Element Embedding".
This was first shown on the Flutter Forward event in Nairobi (Kenya), by Tim
Sneath. [See the replay here](https://www.youtube.com/watch?v=zKQYGKAe5W8&t=5799s).
## Running the demo
The demo is a Flutter web app, so it can be run as:
```terminal
$ flutter run -d chrome
```
## Points of Interest
* Check the new JS Interop:
* Look at `lib/main.dart`, find the `@js.JSExport()` annotation.
* Find the JS code that interacts with Dart in `web/js/demo-js-interop.js`.
* See how the Flutter web application is embedded into the page now:
* Find `hostElement` in `web/index.html`.
_(Built by @ditman, @kevmoo and @malloc-error)_
| samples/web_embedding/element_embedding_demo/README.md/0 | {
"file_path": "samples/web_embedding/element_embedding_demo/README.md",
"repo_id": "samples",
"token_count": 257
} | 1,359 |
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<meta charset="UTF-8" />
<meta content="IE=Edge" http-equiv="X-UA-Compatible" />
<meta name="description" content="A Flutter Web Element embedding demo." />
<!-- 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="Flutter Element embedding" />
<link rel="apple-touch-icon" href="icons/Icon-192.png" />
<link rel="preload" as="image" href="icons/unsplash-x9WGMWwp1NM.png" />
<!-- Favicon -->
<link rel="icon" type="image/png" href="icons/favicon.png" />
<title>Element embedding</title>
<link rel="manifest" href="manifest.json" />
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<section class="contents">
<article>
<div id="flutter_target"></div>
</article>
<aside id="demo_controls">
<h1>Element embedding</h1>
<fieldset id="fx">
<legend>Effects</legend>
<input value="Shadow" data-fx="shadow" type="button" class="fx" />
<input value="Mirror 🧪" data-fx="mirror" type="button" class="fx" />
<input value="Resize" data-fx="resize" type="button" class="fx align-top" />
<div class="tight">
<input value="Spin" data-fx="spin" type="button" class="fx" />
<input type="range" value="0" min="-180" max="180" list="markers" id="rotation" class="tight" />
<datalist id="markers">
<option value="-180"></option>
<option value="-135"></option>
<option value="-45"></option>
<option value="0"></option>
<option value="45"></option>
<option value="135"></option>
<option value="180"></option>
</datalist>
</div>
<input value="Device" data-fx="handheld" type="button" class="fx" />
</fieldset>
<fieldset id="interop">
<legend>JS Interop</legend>
<label for="screen-selector">
Screen
<select name="screen-select" id="screen-selector" class="screen">
<option value="counter">Counter</option>
<option value="textField">TextField</option>
<option value="custom">Custom App</option>
</select>
</label>
<label for="value">
Value
<input id="value" value="" type="text" readonly />
</label>
<input
id="increment"
value="Increment"
type="button"
/>
</fieldset>
</aside>
</section>
<script>
window.addEventListener("load", function (ev) {
// Embed flutter into div#flutter_target
let target = document.querySelector("#flutter_target");
_flutter.loader.loadEntrypoint({
onEntrypointLoaded: async function (engineInitializer) {
let appRunner = await engineInitializer.initializeEngine({
hostElement: target,
});
await appRunner.runApp();
},
});
});
</script>
<script src="js/demo-js-interop.js" defer></script>
<script src="js/demo-css-fx.js" defer></script>
</body>
</html>
| samples/web_embedding/element_embedding_demo/web/index.html/0 | {
"file_path": "samples/web_embedding/element_embedding_demo/web/index.html",
"repo_id": "samples",
"token_count": 1595
} | 1,360 |
import 'package:flutter/material.dart';
class TextFieldDemo extends StatefulWidget {
const TextFieldDemo({super.key, required this.text});
final ValueNotifier<String> text;
@override
State<TextFieldDemo> createState() => _TextFieldDemoState();
}
class _TextFieldDemoState extends State<TextFieldDemo> {
late TextEditingController textController;
@override
void initState() {
super.initState();
// Initial value of the text box
textController = TextEditingController.fromValue(TextEditingValue(
text: widget.text.value,
selection: TextSelection.collapsed(offset: widget.text.value.length)));
// Report changes
textController.addListener(_onTextControllerChange);
// Listen to changes from the outside
widget.text.addListener(_onTextStateChanged);
}
void _onTextControllerChange() {
widget.text.value = textController.text;
}
void _onTextStateChanged() {
textController.value = TextEditingValue(
text: widget.text.value,
selection: TextSelection.collapsed(offset: widget.text.value.length),
);
}
@override
void dispose() {
super.dispose();
textController.dispose();
widget.text.removeListener(_onTextStateChanged);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('Text Field'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(14.0),
child: TextField(
controller: textController,
maxLines: null,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'Type something!',
),
),
),
),
);
}
}
| samples/web_embedding/ng-flutter/flutter/lib/pages/text.dart/0 | {
"file_path": "samples/web_embedding/ng-flutter/flutter/lib/pages/text.dart",
"repo_id": "samples",
"token_count": 697
} | 1,361 |
import { Component, AfterViewInit, SimpleChanges, ViewChild, ElementRef, Input, EventEmitter, Output } from '@angular/core';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
// The global _flutter namespace
declare var _flutter: any;
declare var window: {
_debug: any
};
@Component({
selector: 'ng-flutter',
standalone: true,
template: `
<div #flutterTarget>
<div class="spinner">
<mat-spinner></mat-spinner>
</div>
</div>
`,
styles: [`
:host div {
width: 100%;
height: 100%;
}
.spinner {
display: flex;
justify-content: center;
align-items: center;
}`,
],
imports: [
MatProgressSpinnerModule,
],
})
export class NgFlutterComponent implements AfterViewInit {
// The target that will host the Flutter app.
@ViewChild('flutterTarget') flutterTarget!: ElementRef;
@Input() src: String = 'main.dart.js';
@Input() assetBase: String = '';
@Output() appLoaded: EventEmitter<Object> = new EventEmitter<Object>();
ngAfterViewInit(): void {
const target: HTMLElement = this.flutterTarget.nativeElement;
_flutter.loader.loadEntrypoint({
entrypointUrl: this.src,
onEntrypointLoaded: async (engineInitializer: any) => {
let appRunner = await engineInitializer.initializeEngine({
hostElement: target,
assetBase: this.assetBase,
});
await appRunner.runApp();
}
});
target.addEventListener("flutter-initialized", (event: Event) => {
let state = (event as CustomEvent).detail;
window._debug = state;
this.appLoaded.emit(state);
}, {
once: true,
});
}
}
| samples/web_embedding/ng-flutter/src/app/ng-flutter/ng-flutter.component.ts/0 | {
"file_path": "samples/web_embedding/ng-flutter/src/app/ng-flutter/ng-flutter.component.ts",
"repo_id": "samples",
"token_count": 641
} | 1,362 |
#!/bin/bash
set -e
deploy_to_firebase_staging_channel () {
echo "Deploying website to a staging channel on firebase..."
# Deploy to firebase, but save the output to a variable so we can grep the
# url from the output and save it to FIREBASE_STAGING_URL for future use.
FIREBASE_DEPLOY_RESPONSE=$(firebase hosting:channel:deploy --expires 7d pr$PR_NUMBER-$HEAD_BRANCH --project=$PROJECT_ID)
echo "$FIREBASE_DEPLOY_RESPONSE"
FIREBASE_STAGING_URL=$(grep -Eo "https://$PROJECT_ID--[a-zA-Z0-9./?=_%:-]*" <<< "$FIREBASE_DEPLOY_RESPONSE")
}
login_to_github() {
echo "Logging into github under bot account..."
echo $GH_PAT_TOKEN > token
gh auth login --with-token < token
}
comment_staging_url_on_github () {
echo "Commenting staging url on the PR..."
COMMENT_BODY=$(echo -e "Visit the preview URL for this PR (updated for commit $COMMIT_SHA):\n\n$FIREBASE_STAGING_URL")
# The github CLI throws an error if --edit-last doesn't find a previous
# comment, so this edits the last comment, but if it doesn't exist,
# leave a new comment.
gh pr comment $PR_NUMBER --edit-last --body "$COMMENT_BODY" --repo $REPO_FULL_NAME || \
gh pr comment $PR_NUMBER --body "$COMMENT_BODY" --repo $REPO_FULL_NAME
}
deploy_to_firebase_staging_channel
login_to_github
comment_staging_url_on_github
| website/cloud_build/scripts/stage_site_and_comment_on_github.sh/0 | {
"file_path": "website/cloud_build/scripts/stage_site_and_comment_on_github.sh",
"repo_id": "website",
"token_count": 517
} | 1,363 |
The samples in this folder used to be under `src/_includes/code`. Despite that,
the sources were not being included anywhere. It is likely that the sources
appear in some pages none-the-less. What needs to be done is the following:
- Each app/sample needs to be fully reviewed (and potentially simplified).
- If the sources are in fact being used in site pages, then they need to be
integrated as proper code excerpts. See [Code excerpts][] for details.
- Each app/sample should be tested, at least with a smoke test.
As these changes are completed for a given app/sample folder, then move the
folder into `examples/animation`. One `examples/_animation` is empty, it can be
deleted.
[Code excerpts]: https://github.com/dart-lang/site-shared/blob/main/doc/code-excerpts.md
| website/examples/_animation/README.md/0 | {
"file_path": "website/examples/_animation/README.md",
"repo_id": "website",
"token_count": 207
} | 1,364 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tap on the source route's photo to push a new route,
// containing the same photo at a different location and scale.
// Return to the previous route by tapping the image, or by using the
// device's back-to-the-previous-screen gesture.
// You can slow the transition using the timeDilation property.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
class PhotoHero extends StatelessWidget {
const PhotoHero({
super.key,
required this.photo,
this.onTap,
required this.width,
});
final String photo;
final VoidCallback? onTap;
final double width;
@override
Widget build(BuildContext context) {
return SizedBox(
width: width,
child: Hero(
tag: photo,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Image.asset(
photo,
fit: BoxFit.contain,
),
),
),
),
);
}
}
class HeroAnimation extends StatelessWidget {
const HeroAnimation({super.key});
@override
Widget build(BuildContext context) {
timeDilation = 10.0; // 1.0 means normal animation speed.
return Scaffold(
appBar: AppBar(
title: const Text('Basic Hero Animation'),
),
body: Center(
child: PhotoHero(
photo: 'images/flippers-alpha.png',
width: 300,
onTap: () {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flippers Page'),
),
body: Container(
// Set background to blue to emphasize that it's a new route.
color: Colors.lightBlueAccent,
padding: const EdgeInsets.all(16),
alignment: Alignment.topLeft,
child: PhotoHero(
photo: 'images/flippers-alpha.png',
width: 100,
onTap: () {
Navigator.of(context).pop();
},
),
),
);
},
));
},
),
),
);
}
}
void main() {
runApp(
const MaterialApp(
home: HeroAnimation(),
),
);
}
| website/examples/_animation/hero_animation/lib/main.dart/0 | {
"file_path": "website/examples/_animation/hero_animation/lib/main.dart",
"repo_id": "website",
"token_count": 1241
} | 1,365 |
import 'package:flutter/material.dart';
void main() => runApp(const LogoApp());
class AnimatedLogo extends AnimatedWidget {
const AnimatedLogo({super.key, required Animation<double> animation})
: super(listenable: animation);
@override
Widget build(BuildContext context) {
final animation = listenable as Animation<double>;
return Center(
child: Container(
margin: const EdgeInsets.symmetric(vertical: 10),
height: animation.value,
width: animation.value,
child: const FlutterLogo(),
),
);
}
}
class LogoApp extends StatefulWidget {
const LogoApp({super.key});
@override
State<LogoApp> createState() => _LogoAppState();
}
// #docregion print-state
class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin {
late Animation<double> animation;
late AnimationController controller;
@override
void initState() {
super.initState();
controller =
AnimationController(duration: const Duration(seconds: 2), vsync: this);
animation = Tween<double>(begin: 0, end: 300).animate(controller)
// #enddocregion print-state
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
controller.reverse();
} else if (status == AnimationStatus.dismissed) {
controller.forward();
}
})
// #docregion print-state
..addStatusListener((status) => print('$status'));
controller.forward();
}
// #enddocregion print-state
@override
Widget build(BuildContext context) => AnimatedLogo(animation: animation);
@override
void dispose() {
controller.dispose();
super.dispose();
}
// #docregion print-state
}
| website/examples/animation/animate3/lib/main.dart/0 | {
"file_path": "website/examples/animation/animate3/lib/main.dart",
"repo_id": "website",
"token_count": 605
} | 1,366 |
import 'dart:math';
import 'package:flutter/material.dart';
void main() => runApp(const AnimatedContainerApp());
class AnimatedContainerApp extends StatefulWidget {
const AnimatedContainerApp({super.key});
@override
State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}
class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
// Define the various properties with default values. Update these properties
// when the user taps a FloatingActionButton.
double _width = 50;
double _height = 50;
Color _color = Colors.green;
BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('AnimatedContainer Demo'),
),
body: Center(
// #docregion AnimatedContainer
child: AnimatedContainer(
// Use the properties stored in the State class.
width: _width,
height: _height,
decoration: BoxDecoration(
color: _color,
borderRadius: _borderRadius,
),
// Define how long the animation should take.
duration: const Duration(seconds: 1),
// Provide an optional curve to make the animation feel smoother.
curve: Curves.fastOutSlowIn,
),
// #enddocregion AnimatedContainer
),
// #docregion FAB
floatingActionButton: FloatingActionButton(
// When the user taps the button
onPressed: () {
// Use setState to rebuild the widget with new values.
setState(() {
// Create a random number generator.
final random = Random();
// Generate a random width and height.
_width = random.nextInt(300).toDouble();
_height = random.nextInt(300).toDouble();
// Generate a random color.
_color = Color.fromRGBO(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
1,
);
// Generate a random border radius.
_borderRadius =
BorderRadius.circular(random.nextInt(100).toDouble());
});
},
child: const Icon(Icons.play_arrow),
),
// #enddocregion FAB
),
);
}
}
| website/examples/cookbook/animation/animated_container/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/animation/animated_container/lib/main.dart",
"repo_id": "website",
"token_count": 1084
} | 1,367 |
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: PhysicsCardDragDemo()));
}
class PhysicsCardDragDemo extends StatelessWidget {
const PhysicsCardDragDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: const DraggableCard(
child: FlutterLogo(
size: 128,
),
),
);
}
}
class DraggableCard extends StatefulWidget {
const DraggableCard({required this.child, super.key});
final Widget child;
@override
State<DraggableCard> createState() => _DraggableCardState();
}
// #docregion animation
class _DraggableCardState extends State<DraggableCard>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Alignment> _animation;
Alignment _dragAlignment = Alignment.center;
// #enddocregion animation
// #docregion initState
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 1));
_controller.addListener(() {
setState(() {
_dragAlignment = _animation.value;
});
});
}
// #enddocregion initState
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
// #docregion gesture
return GestureDetector(
onPanDown: (details) {
_controller.stop();
},
onPanUpdate: (details) {
setState(() {
_dragAlignment += Alignment(
details.delta.dx / (size.width / 2),
details.delta.dy / (size.height / 2),
);
});
},
onPanEnd: (details) {
_runAnimation();
},
// #docregion align
child: Align(
alignment: _dragAlignment,
child: Card(
child: widget.child,
),
),
// #enddocregion align
);
// #enddocregion gesture
}
// #docregion runAnimation
void _runAnimation() {
_animation = _controller.drive(
AlignmentTween(
begin: _dragAlignment,
end: Alignment.center,
),
);
_controller.reset();
_controller.forward();
}
// #enddocregion runAnimation
}
| website/examples/cookbook/animation/physics_simulation/lib/step3.dart/0 | {
"file_path": "website/examples/cookbook/animation/physics_simulation/lib/step3.dart",
"repo_id": "website",
"token_count": 944
} | 1,368 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// #docregion DisplayText
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
super.key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: AnimatedOpacity(
duration: transitionDuration,
opacity: isDownloading || isFetching ? 0.0 : 1.0,
curve: Curves.ease,
child: Text(
isDownloaded ? 'OPEN' : 'GET',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.bold,
color: CupertinoColors.activeBlue,
),
),
),
),
);
}
}
// #enddocregion DisplayText
| website/examples/cookbook/effects/download_button/lib/display_text.dart/0 | {
"file_path": "website/examples/cookbook/effects/download_button/lib/display_text.dart",
"repo_id": "website",
"token_count": 655
} | 1,369 |
// ignore_for_file: unused_element
import 'package:flutter/material.dart';
@immutable
class ExampleInstagramFilterSelection extends StatefulWidget {
const ExampleInstagramFilterSelection({super.key});
@override
State<ExampleInstagramFilterSelection> createState() =>
_ExampleInstagramFilterSelectionState();
}
class _ExampleInstagramFilterSelectionState
extends State<ExampleInstagramFilterSelection> {
final _filters = [
Colors.white,
...List.generate(
Colors.primaries.length,
(index) => Colors.primaries[(index * 4) % Colors.primaries.length],
)
];
final _filterColor = ValueNotifier<Color>(Colors.white);
void _onFilterChanged(Color value) {
_filterColor.value = value;
}
@override
Widget build(BuildContext context) {
return Material(
color: Colors.black,
child: Stack(
children: [
Positioned.fill(
child: _buildPhotoWithFilter(),
),
Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: FilterSelector(
onFilterChanged: _onFilterChanged,
filters: _filters,
),
),
],
),
);
}
Widget _buildPhotoWithFilter() {
return ValueListenableBuilder(
valueListenable: _filterColor,
builder: (context, color, child) {
return Image.network(
'https://docs.flutter.dev/cookbook/img-files'
'/effects/instagram-buttons/millennial-dude.jpg',
color: color.withOpacity(0.5),
colorBlendMode: BlendMode.color,
fit: BoxFit.cover,
);
},
);
}
}
@immutable
class FilterSelector extends StatefulWidget {
const FilterSelector({
super.key,
required this.filters,
required this.onFilterChanged,
this.padding = const EdgeInsets.symmetric(vertical: 24),
});
final List<Color> filters;
final void Function(Color selectedColor) onFilterChanged;
final EdgeInsets padding;
@override
State<FilterSelector> createState() => _FilterSelectorState();
}
class _FilterSelectorState extends State<FilterSelector> {
static const _filtersPerScreen = 5;
static const _viewportFractionPerItem = 1.0 / _filtersPerScreen;
late final PageController _controller;
Color itemColor(int index) => widget.filters[index % widget.filters.length];
@override
void initState() {
super.initState();
_controller = PageController(
viewportFraction: _viewportFractionPerItem,
);
_controller.addListener(_onPageChanged);
}
void _onPageChanged() {
final page = (_controller.page ?? 0).round();
widget.onFilterChanged(widget.filters[page]);
}
// #docregion FilterTapped
void _onFilterTapped(int index) {
_controller.animateToPage(
index,
duration: const Duration(milliseconds: 450),
curve: Curves.ease,
);
}
// #enddocregion FilterTapped
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
final itemSize = constraints.maxWidth * _viewportFractionPerItem;
return Stack(
alignment: Alignment.bottomCenter,
children: [
_buildShadowGradient(itemSize),
_buildCarousel(itemSize),
_buildSelectionRing(itemSize),
],
);
});
}
Widget _buildShadowGradient(double itemSize) {
return SizedBox(
height: itemSize * 2 + widget.padding.vertical,
child: const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black,
],
),
),
child: SizedBox.expand(),
),
);
}
// #docregion FinalBuildCarousel
Widget _buildCarousel(double itemSize) {
return Container(
height: itemSize,
margin: widget.padding,
child: PageView.builder(
controller: _controller,
itemCount: widget.filters.length,
itemBuilder: (context, index) {
return Center(
child: AnimatedBuilder(
animation: _controller,
builder: (context, child) {
if (!_controller.hasClients ||
!_controller.position.hasContentDimensions) {
// The PageViewController isn't connected to the
// PageView widget yet. Return an empty box.
return const SizedBox();
}
// The integer index of the current page,
// 0, 1, 2, 3, and so on
final selectedIndex = _controller.page!.roundToDouble();
// The fractional amount that the current filter
// is dragged to the left or right, for example, 0.25 when
// the current filter is dragged 25% to the left.
final pageScrollAmount = _controller.page! - selectedIndex;
// The page-distance of a filter just before it
// moves off-screen.
const maxScrollDistance = _filtersPerScreen / 2;
// The page-distance of this filter item from the
// currently selected filter item.
final pageDistanceFromSelected =
(selectedIndex - index + pageScrollAmount).abs();
// The distance of this filter item from the
// center of the carousel as a percentage, that is, where the selector
// ring sits.
final percentFromCenter =
1.0 - pageDistanceFromSelected / maxScrollDistance;
final itemScale = 0.5 + (percentFromCenter * 0.5);
final opacity = 0.25 + (percentFromCenter * 0.75);
return Transform.scale(
scale: itemScale,
child: Opacity(
opacity: opacity,
// #docregion OnFilterTapped
child: FilterItem(
color: itemColor(index),
onFilterSelected: () => () {},
),
// #enddocregion OnFilterTapped
),
);
},
),
);
},
),
);
}
// #enddocregion FinalBuildCarousel
Widget _buildSelectionRing(double itemSize) {
return IgnorePointer(
child: Padding(
padding: widget.padding,
child: SizedBox(
width: itemSize,
height: itemSize,
child: const DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.fromBorderSide(
BorderSide(width: 6, color: Colors.white),
),
),
),
),
),
);
}
}
// #docregion FilterItem
@immutable
class FilterItem extends StatelessWidget {
const FilterItem({
super.key,
required this.color,
this.onFilterSelected,
});
final Color color;
final VoidCallback? onFilterSelected;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onFilterSelected,
child: AspectRatio(
aspectRatio: 1.0,
child: Padding(
padding: const EdgeInsets.all(8),
child: ClipOval(
child: Image.network(
'https://docs.flutter.dev/cookbook/img-files'
'/effects/instagram-buttons/millennial-texture.jpg',
color: color.withOpacity(0.5),
colorBlendMode: BlendMode.hardLight,
),
),
),
),
);
}
}
// #enddocregion FilterItem
| website/examples/cookbook/effects/photo_filter_carousel/lib/original_example.dart/0 | {
"file_path": "website/examples/cookbook/effects/photo_filter_carousel/lib/original_example.dart",
"repo_id": "website",
"token_count": 3522
} | 1,370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.