code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart';
import 'package:web/web.dart' as web;
/// The web implementation of the `PointerInterceptor` widget.
///
/// A `Widget` that prevents clicks from being swallowed by [HtmlElementView]s.
class PointerInterceptorWeb extends PointerInterceptorPlatform {
/// Register the plugin
static void registerWith(Registrar? registrar) {
PointerInterceptorPlatform.instance = PointerInterceptorWeb();
}
// Slightly modify the created `element` (for `debug` mode).
void _onElementCreated(Object element) {
(element as web.HTMLElement)
..style.width = '100%'
..style.height = '100%'
..style.backgroundColor = 'rgba(255, 0, 0, .5)';
}
@override
Widget buildWidget({
required Widget child,
bool debug = false,
bool intercepting = true,
Key? key,
}) {
if (!intercepting) {
return child;
}
return Stack(
alignment: Alignment.center,
children: <Widget>[
Positioned.fill(
child: HtmlElementView.fromTagName(
tagName: 'div',
isVisible: false,
onElementCreated: debug ? _onElementCreated : null,
),
),
child,
],
);
}
}
| packages/packages/pointer_interceptor/pointer_interceptor_web/lib/pointer_interceptor_web.dart/0 | {'file_path': 'packages/packages/pointer_interceptor/pointer_interceptor_web/lib/pointer_interceptor_web.dart', 'repo_id': 'packages', 'token_count': 566} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
import 'package:process/process.dart';
import 'package:test/test.dart';
void main() {
group('ProcessWrapper', () {
late TestProcess delegate;
late ProcessWrapper process;
setUp(() {
delegate = TestProcess();
process = ProcessWrapper(delegate);
});
group('done', () {
late bool done;
setUp(() {
done = false;
// ignore: unawaited_futures
process.done.then((int result) {
done = true;
});
});
test('completes only when all done', () async {
expect(done, isFalse);
delegate.exitCodeCompleter.complete(0);
await Future<void>.value();
expect(done, isFalse);
await delegate.stdoutController.close();
await Future<void>.value();
expect(done, isFalse);
await delegate.stderrController.close();
await Future<void>.value();
expect(done, isTrue);
expect(await process.exitCode, 0);
});
test('works in conjunction with subscribers to stdio streams', () async {
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
// ignore: avoid_print
.listen(print);
delegate.exitCodeCompleter.complete(0);
await delegate.stdoutController.close();
await delegate.stderrController.close();
await Future<void>.value();
expect(done, isTrue);
});
});
group('stdio', () {
test('streams properly close', () async {
Future<void> testStream(
Stream<List<int>> stream,
StreamController<List<int>> controller,
String name,
) async {
bool closed = false;
stream.listen(
(_) {},
onDone: () {
closed = true;
},
);
await controller.close();
await Future<void>.value();
expect(closed, isTrue, reason: 'for $name');
}
await testStream(process.stdout, delegate.stdoutController, 'stdout');
await testStream(process.stderr, delegate.stderrController, 'stderr');
});
});
});
}
class TestProcess implements io.Process {
TestProcess([this.pid = 123])
: exitCodeCompleter = Completer<int>(),
stdoutController = StreamController<List<int>>(),
stderrController = StreamController<List<int>>();
@override
final int pid;
final Completer<int> exitCodeCompleter;
final StreamController<List<int>> stdoutController;
final StreamController<List<int>> stderrController;
@override
Future<int> get exitCode => exitCodeCompleter.future;
@override
bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) {
exitCodeCompleter.complete(-1);
return true;
}
@override
Stream<List<int>> get stderr => stderrController.stream;
@override
io.IOSink get stdin => throw UnsupportedError('Not supported');
@override
Stream<List<int>> get stdout => stdoutController.stream;
}
| packages/packages/process/test/src/interface/process_wrapper_test.dart/0 | {'file_path': 'packages/packages/process/test/src/interface/process_wrapper_test.dart', 'repo_id': 'packages', 'token_count': 1328} |
// 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:quick_actions_platform_interface/quick_actions_platform_interface.dart';
import 'messages.g.dart';
export 'package:quick_actions_platform_interface/types/types.dart';
late QuickActionHandler _handler;
/// An implementation of [QuickActionsPlatform] for iOS.
class QuickActionsIos extends QuickActionsPlatform {
/// Creates a new plugin implementation instance.
QuickActionsIos({
@visibleForTesting IOSQuickActionsApi? api,
}) : _hostApi = api ?? IOSQuickActionsApi();
final IOSQuickActionsApi _hostApi;
/// Registers this class as the default instance of [QuickActionsPlatform].
static void registerWith() {
QuickActionsPlatform.instance = QuickActionsIos();
}
@override
Future<void> initialize(QuickActionHandler handler) async {
final _QuickActionHandlerApi quickActionsHandlerApi =
_QuickActionHandlerApi();
IOSQuickActionsFlutterApi.setup(quickActionsHandlerApi);
_handler = handler;
}
@override
Future<void> setShortcutItems(List<ShortcutItem> items) async {
await _hostApi.setShortcutItems(
items.map(_shortcutItemToShortcutItemMessage).toList(),
);
}
@override
Future<void> clearShortcutItems() => _hostApi.clearShortcutItems();
ShortcutItemMessage _shortcutItemToShortcutItemMessage(ShortcutItem item) {
return ShortcutItemMessage(
type: item.type,
localizedTitle: item.localizedTitle,
icon: item.icon,
);
}
}
class _QuickActionHandlerApi extends IOSQuickActionsFlutterApi {
@override
void launchAction(String action) {
_handler(action);
}
}
| packages/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart/0 | {'file_path': 'packages/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart', 'repo_id': 'packages', 'token_count': 582} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:quick_actions_platform_interface/method_channel/method_channel_quick_actions.dart';
import 'package:quick_actions_platform_interface/types/shortcut_item.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$MethodChannelQuickActions', () {
final MethodChannelQuickActions quickActions = MethodChannelQuickActions();
final List<MethodCall> log = <MethodCall>[];
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(quickActions.channel,
(MethodCall methodCall) async {
log.add(methodCall);
return '';
});
log.clear();
});
group('#initialize', () {
test('passes getLaunchAction on launch method', () {
quickActions.initialize((String type) {});
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
],
);
});
test('initialize', () async {
final Completer<bool> quickActionsHandler = Completer<bool>();
await quickActions
.initialize((_) => quickActionsHandler.complete(true));
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
],
);
log.clear();
expect(quickActionsHandler.future, completion(isTrue));
});
});
group('#setShortCutItems', () {
test('passes shortcutItem through channel', () {
quickActions.initialize((String type) {});
quickActions.setShortcutItems(<ShortcutItem>[
const ShortcutItem(
type: 'test', localizedTitle: 'title', icon: 'icon.svg')
]);
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
isMethodCall('setShortcutItems', arguments: <Map<String, String>>[
<String, String>{
'type': 'test',
'localizedTitle': 'title',
'icon': 'icon.svg',
}
]),
],
);
});
test('setShortcutItems with demo data', () async {
const String type = 'type';
const String localizedTitle = 'localizedTitle';
const String icon = 'icon';
await quickActions.setShortcutItems(
const <ShortcutItem>[
ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon)
],
);
expect(
log,
<Matcher>[
isMethodCall(
'setShortcutItems',
arguments: <Map<String, String>>[
<String, String>{
'type': type,
'localizedTitle': localizedTitle,
'icon': icon,
}
],
),
],
);
log.clear();
});
});
group('#clearShortCutItems', () {
test('send clearShortcutItems through channel', () {
quickActions.initialize((String type) {});
quickActions.clearShortcutItems();
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
isMethodCall('clearShortcutItems', arguments: null),
],
);
});
test('clearShortcutItems', () {
quickActions.clearShortcutItems();
expect(
log,
<Matcher>[
isMethodCall('clearShortcutItems', arguments: null),
],
);
log.clear();
});
});
});
group('$ShortcutItem', () {
test('Shortcut item can be constructed', () {
const String type = 'type';
const String localizedTitle = 'title';
const String icon = 'foo';
const ShortcutItem item =
ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon);
expect(item.type, type);
expect(item.localizedTitle, localizedTitle);
expect(item.icon, icon);
});
});
}
| packages/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart/0 | {'file_path': 'packages/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart', 'repo_id': 'packages', 'token_count': 1956} |
// 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:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:shared_preferences_platform_interface/types.dart';
import 'messages.g.dart';
typedef _Setter = Future<void> Function(String key, Object value);
/// iOS and macOS implementation of shared_preferences.
class SharedPreferencesFoundation extends SharedPreferencesStorePlatform {
final UserDefaultsApi _api = UserDefaultsApi();
static const String _defaultPrefix = 'flutter.';
late final Map<String, _Setter> _setters = <String, _Setter>{
'Bool': (String key, Object value) {
return _api.setBool(key, value as bool);
},
'Double': (String key, Object value) {
return _api.setDouble(key, value as double);
},
'Int': (String key, Object value) {
return _api.setValue(key, value as int);
},
'String': (String key, Object value) {
return _api.setValue(key, value as String);
},
'StringList': (String key, Object value) {
return _api.setValue(key, value as List<String?>);
},
};
/// Registers this class as the default instance of
/// [SharedPreferencesStorePlatform].
static void registerWith() {
SharedPreferencesStorePlatform.instance = SharedPreferencesFoundation();
}
@override
Future<bool> clear() async {
return clearWithParameters(
ClearParameters(
filter: PreferencesFilter(prefix: _defaultPrefix),
),
);
}
@override
Future<bool> clearWithPrefix(String prefix) async {
return clearWithParameters(
ClearParameters(filter: PreferencesFilter(prefix: prefix)));
}
@override
Future<bool> clearWithParameters(ClearParameters parameters) async {
final PreferencesFilter filter = parameters.filter;
return _api.clear(
filter.prefix,
filter.allowList?.toList(),
);
}
@override
Future<Map<String, Object>> getAll() async {
return getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: _defaultPrefix),
),
);
}
@override
Future<Map<String, Object>> getAllWithPrefix(String prefix) async {
return getAllWithParameters(
GetAllParameters(filter: PreferencesFilter(prefix: prefix)));
}
@override
Future<Map<String, Object>> getAllWithParameters(
GetAllParameters parameters) async {
final PreferencesFilter filter = parameters.filter;
final Map<String?, Object?> data =
await _api.getAll(filter.prefix, filter.allowList?.toList());
return data.cast<String, Object>();
}
@override
Future<bool> remove(String key) async {
await _api.remove(key);
return true;
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
final _Setter? setter = _setters[valueType];
if (setter == null) {
throw PlatformException(
code: 'InvalidOperation',
message: '"$valueType" is not a supported type.');
}
await setter(key, value);
return true;
}
}
| packages/packages/shared_preferences/shared_preferences_foundation/lib/shared_preferences_foundation.dart/0 | {'file_path': 'packages/packages/shared_preferences/shared_preferences_foundation/lib/shared_preferences_foundation.dart', 'repo_id': 'packages', 'token_count': 1093} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences_linux/shared_preferences_linux.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'SharedPreferences Demo',
home: SharedPreferencesDemo(),
);
}
}
class SharedPreferencesDemo extends StatefulWidget {
const SharedPreferencesDemo({super.key});
@override
SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
}
class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
final SharedPreferencesLinux prefs = SharedPreferencesLinux();
late Future<int> _counter;
Future<void> _incrementCounter() async {
final Map<String, Object> values = await prefs.getAll();
final int counter = (values['counter'] as int? ?? 0) + 1;
setState(() {
_counter = prefs.setValue('Int', 'counter', counter).then((bool success) {
return counter;
});
});
}
@override
void initState() {
super.initState();
_counter = prefs.getAll().then((Map<String, Object> values) {
return values['counter'] as int? ?? 0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SharedPreferences Demo'),
),
body: Center(
child: FutureBuilder<int>(
future: _counter,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return const CircularProgressIndicator();
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text(
'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n'
'This should persist across restarts.',
);
}
}
})),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
| packages/packages/shared_preferences/shared_preferences_linux/example/lib/main.dart/0 | {'file_path': 'packages/packages/shared_preferences/shared_preferences_linux/example/lib/main.dart', 'repo_id': 'packages', 'token_count': 1135} |
name: standard_message_codec_examples
description: Example code for standard message codec usage
version: 0.0.1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
standard_message_codec:
path: ../
dev_dependencies:
build_runner: ^2.1.10
| packages/packages/standard_message_codec/example/pubspec.yaml/0 | {'file_path': 'packages/packages/standard_message_codec/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 102} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
void main() {
test('InAppBrowserConfiguration defaults to showTitle false', () {
expect(const InAppBrowserConfiguration().showTitle, false);
});
test('InAppBrowserConfiguration showTitle can be set to true', () {
expect(const InAppBrowserConfiguration(showTitle: true).showTitle, true);
});
}
| packages/packages/url_launcher/url_launcher_platform_interface/test/in_app_browser_configuration_test.dart/0 | {'file_path': 'packages/packages/url_launcher/url_launcher_platform_interface/test/in_app_browser_configuration_test.dart', 'repo_id': 'packages', 'token_count': 173} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:js_util';
import 'dart:ui_web' as ui_web;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:web/helpers.dart' as html;
/// The unique identifier for the view type to be used for link platform views.
const String linkViewType = '__url_launcher::link';
/// The name of the property used to set the viewId on the DOM element.
const String linkViewIdProperty = '__url_launcher::link::viewId';
/// Signature for a function that takes a unique [id] and creates an HTML element.
typedef HtmlViewFactory = html.Element Function(int viewId);
/// Factory that returns the link DOM element for each unique view id.
HtmlViewFactory get linkViewFactory => LinkViewController._viewFactory;
/// The delegate for building the [Link] widget on the web.
///
/// It uses a platform view to render an anchor element in the DOM.
class WebLinkDelegate extends StatefulWidget {
/// Creates a delegate for the given [link].
const WebLinkDelegate(this.link, {super.key});
/// Information about the link built by the app.
final LinkInfo link;
@override
WebLinkDelegateState createState() => WebLinkDelegateState();
}
/// The link delegate used on the web platform.
///
/// For external URIs, it lets the browser do its thing. For app route names, it
/// pushes the route name to the framework.
class WebLinkDelegateState extends State<WebLinkDelegate> {
late LinkViewController _controller;
@override
void didUpdateWidget(WebLinkDelegate oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.link.uri != oldWidget.link.uri) {
_controller.setUri(widget.link.uri);
}
if (widget.link.target != oldWidget.link.target) {
_controller.setTarget(widget.link.target);
}
}
Future<void> _followLink() {
LinkViewController.registerHitTest(_controller);
return Future<void>.value();
}
@override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.passthrough,
children: <Widget>[
widget.link.builder(
context,
widget.link.isDisabled ? null : _followLink,
),
Positioned.fill(
child: PlatformViewLink(
viewType: linkViewType,
onCreatePlatformView: (PlatformViewCreationParams params) {
_controller = LinkViewController.fromParams(params);
return _controller
..setUri(widget.link.uri)
..setTarget(widget.link.target);
},
surfaceFactory:
(BuildContext context, PlatformViewController controller) {
return PlatformViewSurface(
controller: controller,
gestureRecognizers: const <Factory<
OneSequenceGestureRecognizer>>{},
hitTestBehavior: PlatformViewHitTestBehavior.transparent,
);
},
),
),
],
);
}
}
/// Controls link views.
class LinkViewController extends PlatformViewController {
/// Creates a [LinkViewController] instance with the unique [viewId].
LinkViewController(this.viewId) {
if (_instances.isEmpty) {
// This is the first controller being created, attach the global click
// listener.
_clickSubscription =
const html.EventStreamProvider<html.MouseEvent>('click')
.forTarget(html.window)
.listen(_onGlobalClick);
}
_instances[viewId] = this;
}
/// Creates and initializes a [LinkViewController] instance with the given
/// platform view [params].
factory LinkViewController.fromParams(
PlatformViewCreationParams params,
) {
final int viewId = params.id;
final LinkViewController controller = LinkViewController(viewId);
controller._initialize().then((_) {
/// Because _initialize is async, it can happen that [LinkViewController.dispose]
/// may get called before this `then` callback.
/// Check that the `controller` that was created by this factory is not
/// disposed before calling `onPlatformViewCreated`.
if (_instances[viewId] == controller) {
params.onPlatformViewCreated(viewId);
}
});
return controller;
}
static final Map<int, LinkViewController> _instances =
<int, LinkViewController>{};
static html.Element _viewFactory(int viewId) {
return _instances[viewId]!._element;
}
static int? _hitTestedViewId;
static late StreamSubscription<html.MouseEvent> _clickSubscription;
static void _onGlobalClick(html.MouseEvent event) {
final int? viewId = getViewIdFromTarget(event);
_instances[viewId]?._onDomClick(event);
// After the DOM click event has been received, clean up the hit test state
// so we can start fresh on the next click.
unregisterHitTest();
}
/// Call this method to indicate that a hit test has been registered for the
/// given [controller].
///
/// The [onClick] callback is invoked when the anchor element receives a
/// `click` from the browser.
static void registerHitTest(LinkViewController controller) {
_hitTestedViewId = controller.viewId;
}
/// Removes all information about previously registered hit tests.
static void unregisterHitTest() {
_hitTestedViewId = null;
}
@override
final int viewId;
late html.HTMLElement _element;
Future<void> _initialize() async {
_element = html.document.createElement('a') as html.HTMLElement;
setProperty(_element, linkViewIdProperty, viewId);
_element.style
..opacity = '0'
..display = 'block'
..width = '100%'
..height = '100%'
..cursor = 'unset';
// This is recommended on MDN:
// - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target
_element.setAttribute('rel', 'noreferrer noopener');
final Map<String, dynamic> args = <String, dynamic>{
'id': viewId,
'viewType': linkViewType,
};
await SystemChannels.platform_views.invokeMethod<void>('create', args);
}
void _onDomClick(html.MouseEvent event) {
final bool isHitTested = _hitTestedViewId == viewId;
if (!isHitTested) {
// There was no hit test registered for this click. This means the click
// landed on the anchor element but not on the underlying widget. In this
// case, we prevent the browser from following the click.
event.preventDefault();
return;
}
if (_uri != null && _uri!.hasScheme) {
// External links will be handled by the browser, so we don't have to do
// anything.
return;
}
// A uri that doesn't have a scheme is an internal route name. In this
// case, we push it via Flutter's navigation system instead of letting the
// browser handle it.
event.preventDefault();
final String routeName = _uri.toString();
pushRouteNameToFramework(null, routeName);
}
Uri? _uri;
/// Set the [Uri] value for this link.
///
/// When Uri is null, the `href` attribute of the link is removed.
void setUri(Uri? uri) {
_uri = uri;
if (uri == null) {
_element.removeAttribute('href');
} else {
String href = uri.toString();
// in case an internal uri is given, the url mus be properly encoded
// using the currently used [UrlStrategy]
if (!uri.hasScheme) {
href = ui_web.urlStrategy?.prepareExternalUrl(href) ?? href;
}
_element.setAttribute('href', href);
}
}
/// Set the [LinkTarget] value for this link.
void setTarget(LinkTarget target) {
_element.setAttribute('target', _getHtmlTarget(target));
}
String _getHtmlTarget(LinkTarget target) {
switch (target) {
case LinkTarget.defaultTarget:
case LinkTarget.self:
return '_self';
case LinkTarget.blank:
return '_blank';
}
// The enum comes from a different package, which could get a new value at
// any time, so provide a fallback that ensures this won't break when used
// with a version that contains new values. This is deliberately outside
// the switch rather than a `default` so that the linter will flag the
// switch as needing an update.
return '_self';
}
@override
Future<void> clearFocus() async {
// Currently this does nothing on Flutter Web.
// TODO(het): Implement this. See https://github.com/flutter/flutter/issues/39496
}
@override
Future<void> dispatchPointerEvent(PointerEvent event) async {
// We do not dispatch pointer events to HTML views because they may contain
// cross-origin iframes, which only accept user-generated events.
}
@override
Future<void> dispose() async {
assert(_instances[viewId] == this);
_instances.remove(viewId);
if (_instances.isEmpty) {
await _clickSubscription.cancel();
}
await SystemChannels.platform_views.invokeMethod<void>('dispose', viewId);
}
}
/// Finds the view id of the DOM element targeted by the [event].
int? getViewIdFromTarget(html.Event event) {
final html.Element? linkElement = getLinkElementFromTarget(event);
if (linkElement != null) {
// TODO(stuartmorgan): Remove this ignore (and change to getProperty<int>)
// once the templated version is available on stable. On master (2.8) this
// is already not necessary.
// ignore: return_of_invalid_type
return getProperty(linkElement, linkViewIdProperty);
}
return null;
}
/// Finds the targeted DOM element by the [event].
///
/// It handles the case where the target element is inside a shadow DOM too.
html.Element? getLinkElementFromTarget(html.Event event) {
final html.EventTarget? target = event.target;
if (target != null && target is html.Element) {
if (isLinkElement(target)) {
return target;
}
if (target.shadowRoot != null) {
final html.Node? child = target.shadowRoot!.lastChild;
if (child != null && child is html.Element && isLinkElement(child)) {
return child;
}
}
}
return null;
}
/// Checks if the given [element] is a link that was created by
/// [LinkViewController].
bool isLinkElement(html.Element? element) {
return element != null &&
element.tagName == 'A' &&
hasProperty(element, linkViewIdProperty);
}
| packages/packages/url_launcher/url_launcher_web/lib/src/link.dart/0 | {'file_path': 'packages/packages/url_launcher/url_launcher_web/lib/src/link.dart', 'repo_id': 'packages', 'token_count': 3671} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
// Runs `dart test -p chrome` in the root of the cross_file package.
//
// Called from the custom-tests CI action.
//
// usage: dart run tool/run_tests.dart
// (needs a `chrome` executable in $PATH, or a tweak to dart_test.yaml)
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as p;
Future<void> main(List<String> args) async {
if (!Platform.isLinux) {
// The test was migrated from a Linux-only task, so this preserves behavior.
// If desired, it can be enabled for other platforms in the future.
print('Skipping for non-Linux host');
exit(0);
}
final Directory packageDir =
Directory(p.dirname(Platform.script.path)).parent;
final String testingAppDirPath =
p.join(packageDir.path, 'testing', 'test_app');
// Fetch the test app's dependencies.
int status = await _runProcess(
'flutter',
<String>[
'pub',
'get',
],
workingDirectory: testingAppDirPath,
);
if (status != 0) {
exit(status);
}
// Run the tests.
status = await _runProcess(
'flutter',
<String>[
'test',
'testing',
],
workingDirectory: packageDir.path,
);
exit(status);
}
Future<Process> _streamOutput(Future<Process> processFuture) async {
final Process process = await processFuture;
await Future.wait(<Future<void>>[
stdout.addStream(process.stdout),
stderr.addStream(process.stderr),
]);
return process;
}
Future<int> _runProcess(
String command,
List<String> arguments, {
String? workingDirectory,
}) async {
final Process process = await _streamOutput(Process.start(
command,
arguments,
workingDirectory: workingDirectory,
));
return process.exitCode;
}
| packages/packages/web_benchmarks/tool/run_tests.dart/0 | {'file_path': 'packages/packages/web_benchmarks/tool/run_tests.dart', 'repo_id': 'packages', 'token_count': 653} |
// 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:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'webview_controller.dart';
/// Callbacks for accepting or rejecting navigation changes, and for tracking
/// the progress of navigation requests.
///
/// See [WebViewController.setNavigationDelegate].
///
/// ## Platform-Specific Features
/// This class contains an underlying implementation provided by the current
/// platform. Once a platform implementation is imported, the examples below
/// can be followed to use features provided by a platform's implementation.
///
/// {@macro webview_flutter.NavigationDelegate.fromPlatformCreationParams}
///
/// Below is an example of accessing the platform-specific implementation for
/// iOS and Android:
///
/// ```dart
/// final NavigationDelegate navigationDelegate = NavigationDelegate();
///
/// if (WebViewPlatform.instance is WebKitWebViewPlatform) {
/// final WebKitNavigationDelegate webKitDelegate =
/// navigationDelegate.platform as WebKitNavigationDelegate;
/// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
/// final AndroidNavigationDelegate androidDelegate =
/// navigationDelegate.platform as AndroidNavigationDelegate;
/// }
/// ```
class NavigationDelegate {
/// Constructs a [NavigationDelegate].
///
/// {@template webview_fluttter.NavigationDelegate.constructor}
/// `onUrlChange`: invoked when the underlying web view changes to a new url.
/// {@endtemplate}
NavigationDelegate({
FutureOr<NavigationDecision> Function(NavigationRequest request)?
onNavigationRequest,
void Function(String url)? onPageStarted,
void Function(String url)? onPageFinished,
void Function(int progress)? onProgress,
void Function(WebResourceError error)? onWebResourceError,
void Function(UrlChange change)? onUrlChange,
}) : this.fromPlatformCreationParams(
const PlatformNavigationDelegateCreationParams(),
onNavigationRequest: onNavigationRequest,
onPageStarted: onPageStarted,
onPageFinished: onPageFinished,
onProgress: onProgress,
onWebResourceError: onWebResourceError,
onUrlChange: onUrlChange,
);
/// Constructs a [NavigationDelegate] from creation params for a specific
/// platform.
///
/// {@macro webview_fluttter.NavigationDelegate.constructor}
///
/// {@template webview_flutter.NavigationDelegate.fromPlatformCreationParams}
/// Below is an example of setting platform-specific creation parameters for
/// iOS and Android:
///
/// ```dart
/// PlatformNavigationDelegateCreationParams params =
/// const PlatformNavigationDelegateCreationParams();
///
/// if (WebViewPlatform.instance is WebKitWebViewPlatform) {
/// params = WebKitNavigationDelegateCreationParams
/// .fromPlatformNavigationDelegateCreationParams(
/// params,
/// );
/// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
/// params = AndroidNavigationDelegateCreationParams
/// .fromPlatformNavigationDelegateCreationParams(
/// params,
/// );
/// }
///
/// final NavigationDelegate navigationDelegate =
/// NavigationDelegate.fromPlatformCreationParams(
/// params,
/// );
/// ```
/// {@endtemplate}
NavigationDelegate.fromPlatformCreationParams(
PlatformNavigationDelegateCreationParams params, {
FutureOr<NavigationDecision> Function(NavigationRequest request)?
onNavigationRequest,
void Function(String url)? onPageStarted,
void Function(String url)? onPageFinished,
void Function(int progress)? onProgress,
void Function(WebResourceError error)? onWebResourceError,
void Function(UrlChange change)? onUrlChange,
}) : this.fromPlatform(
PlatformNavigationDelegate(params),
onNavigationRequest: onNavigationRequest,
onPageStarted: onPageStarted,
onPageFinished: onPageFinished,
onProgress: onProgress,
onWebResourceError: onWebResourceError,
onUrlChange: onUrlChange,
);
/// Constructs a [NavigationDelegate] from a specific platform implementation.
///
/// {@macro webview_fluttter.NavigationDelegate.constructor}
NavigationDelegate.fromPlatform(
this.platform, {
this.onNavigationRequest,
this.onPageStarted,
this.onPageFinished,
this.onProgress,
this.onWebResourceError,
void Function(UrlChange change)? onUrlChange,
}) {
if (onNavigationRequest != null) {
platform.setOnNavigationRequest(onNavigationRequest!);
}
if (onPageStarted != null) {
platform.setOnPageStarted(onPageStarted!);
}
if (onPageFinished != null) {
platform.setOnPageFinished(onPageFinished!);
}
if (onProgress != null) {
platform.setOnProgress(onProgress!);
}
if (onWebResourceError != null) {
platform.setOnWebResourceError(onWebResourceError!);
}
if (onUrlChange != null) {
platform.setOnUrlChange(onUrlChange);
}
}
/// Implementation of [PlatformNavigationDelegate] for the current platform.
final PlatformNavigationDelegate platform;
/// Invoked when a decision for a navigation request is pending.
///
/// When a navigation is initiated by the WebView (e.g when a user clicks a
/// link) this delegate is called and has to decide how to proceed with the
/// navigation.
///
/// *Important*: Some platforms may also trigger this callback from calls to
/// [WebViewController.loadRequest].
///
/// See [NavigationDecision].
final NavigationRequestCallback? onNavigationRequest;
/// Invoked when a page has started loading.
final PageEventCallback? onPageStarted;
/// Invoked when a page has finished loading.
final PageEventCallback? onPageFinished;
/// Invoked when a page is loading to report the progress.
final ProgressCallback? onProgress;
/// Invoked when a resource loading error occurred.
final WebResourceErrorCallback? onWebResourceError;
}
| packages/packages/webview_flutter/webview_flutter/lib/src/navigation_delegate.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter/lib/src/navigation_delegate.dart', 'repo_id': 'packages', 'token_count': 1940} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import '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_widget_test.mocks.dart';
@GenerateMocks(<Type>[PlatformWebViewController, PlatformWebViewWidget])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('WebViewWidget', () {
testWidgets('build', (WidgetTester tester) async {
final MockPlatformWebViewWidget mockPlatformWebViewWidget =
MockPlatformWebViewWidget();
when(mockPlatformWebViewWidget.build(any)).thenReturn(Container());
await tester.pumpWidget(WebViewWidget.fromPlatform(
platform: mockPlatformWebViewWidget,
));
expect(find.byType(Container), findsOneWidget);
});
testWidgets(
'constructor parameters are correctly passed to creation params',
(WidgetTester tester) async {
WebViewPlatform.instance = TestWebViewPlatform();
final MockPlatformWebViewController mockPlatformWebViewController =
MockPlatformWebViewController();
final WebViewController webViewController =
WebViewController.fromPlatform(
mockPlatformWebViewController,
);
final WebViewWidget webViewWidget = WebViewWidget(
key: GlobalKey(),
controller: webViewController,
layoutDirection: TextDirection.rtl,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()),
},
);
// The key passed to the default constructor is used by the super class
// and not passed to the platform implementation.
expect(webViewWidget.platform.params.key, isNull);
expect(
webViewWidget.platform.params.controller,
webViewController.platform,
);
expect(webViewWidget.platform.params.layoutDirection, TextDirection.rtl);
expect(
webViewWidget.platform.params.gestureRecognizers.isNotEmpty,
isTrue,
);
});
});
}
class TestWebViewPlatform extends WebViewPlatform {
@override
PlatformWebViewWidget createPlatformWebViewWidget(
PlatformWebViewWidgetCreationParams params,
) {
return TestPlatformWebViewWidget(params);
}
}
class TestPlatformWebViewWidget extends PlatformWebViewWidget {
TestPlatformWebViewWidget(super.params) : super.implementation();
@override
Widget build(BuildContext context) {
throw UnimplementedError();
}
}
| packages/packages/webview_flutter/webview_flutter/test/webview_widget_test.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter/test/webview_widget_test.dart', 'repo_id': 'packages', 'token_count': 1004} |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/webview_flutter/webview_flutter_android/example/.pluginToolsConfig.yaml/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_android/example/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Proxy that provides access to the platform views service.
///
/// This service allows creating and controlling platform-specific views.
@immutable
class PlatformViewsServiceProxy {
/// Constructs a [PlatformViewsServiceProxy].
const PlatformViewsServiceProxy();
/// Proxy method for [PlatformViewsService.initExpensiveAndroidView].
ExpensiveAndroidViewController initExpensiveAndroidView({
required int id,
required String viewType,
required TextDirection layoutDirection,
dynamic creationParams,
MessageCodec<dynamic>? creationParamsCodec,
VoidCallback? onFocus,
}) {
return PlatformViewsService.initExpensiveAndroidView(
id: id,
viewType: viewType,
layoutDirection: layoutDirection,
creationParams: creationParams,
creationParamsCodec: creationParamsCodec,
onFocus: onFocus,
);
}
/// Proxy method for [PlatformViewsService.initSurfaceAndroidView].
SurfaceAndroidViewController initSurfaceAndroidView({
required int id,
required String viewType,
required TextDirection layoutDirection,
dynamic creationParams,
MessageCodec<dynamic>? creationParamsCodec,
VoidCallback? onFocus,
}) {
return PlatformViewsService.initSurfaceAndroidView(
id: id,
viewType: viewType,
layoutDirection: layoutDirection,
creationParams: creationParams,
creationParamsCodec: creationParamsCodec,
onFocus: onFocus,
);
}
}
| packages/packages/webview_flutter/webview_flutter_android/lib/src/platform_views_service_proxy.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_android/lib/src/platform_views_service_proxy.dart', 'repo_id': 'packages', 'token_count': 541} |
// 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 'web_resource_request.dart';
import 'web_resource_response.dart';
/// Error returned in `PlatformNavigationDelegate.setOnHttpError` when an HTTP
/// response error has been received.
///
/// Platform specific implementations can add additional fields by extending
/// this class.
///
/// This example demonstrates how to extend the [HttpResponseError] to
/// provide additional platform specific parameters.
///
/// When extending [HttpResponseError] additional parameters should always
/// accept `null` or have a default value to prevent breaking changes.
///
/// ```dart
/// class IOSHttpResponseError extends HttpResponseError {
/// IOSHttpResponseError._(HttpResponseError error, {required this.domain})
/// : super(
/// statusCode: error.statusCode,
/// );
///
/// factory IOSHttpResponseError.fromHttpResponseError(
/// HttpResponseError error, {
/// required String? domain,
/// }) {
/// return IOSHttpResponseError._(error, domain: domain);
/// }
///
/// final String? domain;
/// }
/// ```
@immutable
class HttpResponseError {
/// Used by the platform implementation to create a new [HttpResponseError].
const HttpResponseError({
this.request,
this.response,
});
/// The associated request.
final WebResourceRequest? request;
/// The associated response.
final WebResourceResponse? response;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart', 'repo_id': 'packages', 'token_count': 449} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
/// Details of the change to a web view's url.
///
/// Platform specific implementations can add additional fields by extending
/// this class.
///
/// This example demonstrates how to extend the [UrlChange] to provide
/// additional platform specific parameters:
///
/// ```dart
/// class AndroidUrlChange extends UrlChange {
/// const AndroidUrlChange({required super.url, required this.isReload});
///
/// final bool isReload;
/// }
/// ```
@immutable
class UrlChange {
/// Creates a new [UrlChange].
const UrlChange({required this.url});
/// The new url of the web view.
final String? url;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/url_change.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/url_change.dart', 'repo_id': 'packages', 'token_count': 225} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'platform_navigation_delegate_test.dart';
import 'webview_platform_test.mocks.dart';
@GenerateMocks(<Type>[PlatformNavigationDelegate])
void main() {
setUp(() {
WebViewPlatform.instance = MockWebViewPlatformWithMixin();
});
test('Cannot be implemented with `implements`', () {
when((WebViewPlatform.instance! as MockWebViewPlatform)
.createPlatformWebViewController(any))
.thenReturn(ImplementsPlatformWebViewController());
expect(() {
PlatformWebViewController(
const PlatformWebViewControllerCreationParams());
// In versions of `package:plugin_platform_interface` prior to fixing
// https://github.com/flutter/flutter/issues/109339, an attempt to
// implement a platform interface using `implements` would sometimes throw
// a `NoSuchMethodError` and other times throw an `AssertionError`. After
// the issue is fixed, an `AssertionError` will always be thrown. For the
// purpose of this test, we don't really care what exception is thrown, so
// just allow any exception.
}, throwsA(anything));
});
test('Can be extended', () {
const PlatformWebViewControllerCreationParams params =
PlatformWebViewControllerCreationParams();
when((WebViewPlatform.instance! as MockWebViewPlatform)
.createPlatformWebViewController(any))
.thenReturn(ExtendsPlatformWebViewController(params));
expect(PlatformWebViewController(params), isNotNull);
});
test('Can be mocked with `implements`', () {
when((WebViewPlatform.instance! as MockWebViewPlatform)
.createPlatformWebViewController(any))
.thenReturn(MockWebViewControllerDelegate());
expect(
PlatformWebViewController(
const PlatformWebViewControllerCreationParams()),
isNotNull);
});
test('Default implementation of loadFile should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.loadFile(''),
throwsUnimplementedError,
);
});
test(
'Default implementation of loadFlutterAsset should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.loadFlutterAsset(''),
throwsUnimplementedError,
);
});
test(
'Default implementation of loadHtmlString should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.loadHtmlString(''),
throwsUnimplementedError,
);
});
test('Default implementation of loadRequest should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.loadRequest(MockLoadRequestParamsDelegate()),
throwsUnimplementedError,
);
});
test('Default implementation of currentUrl should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.currentUrl(),
throwsUnimplementedError,
);
});
test('Default implementation of canGoBack should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.canGoBack(),
throwsUnimplementedError,
);
});
test(
'Default implementation of canGoForward should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.canGoForward(),
throwsUnimplementedError,
);
});
test('Default implementation of goBack should throw unimplemented error', () {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.goBack(),
throwsUnimplementedError,
);
});
test('Default implementation of goForward should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.goForward(),
throwsUnimplementedError,
);
});
test('Default implementation of reload should throw unimplemented error', () {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.reload(),
throwsUnimplementedError,
);
});
test('Default implementation of clearCache should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.clearCache(),
throwsUnimplementedError,
);
});
test(
'Default implementation of clearLocalStorage should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.clearLocalStorage(),
throwsUnimplementedError,
);
});
test(
'Default implementation of the setNavigationCallback should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() =>
controller.setPlatformNavigationDelegate(MockNavigationDelegate()),
throwsUnimplementedError,
);
},
);
test(
'Default implementation of runJavaScript should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.runJavaScript('javaScript'),
throwsUnimplementedError,
);
});
test(
'Default implementation of runJavaScriptReturningResult should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.runJavaScriptReturningResult('javaScript'),
throwsUnimplementedError,
);
});
test(
'Default implementation of addJavaScriptChannel should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.addJavaScriptChannel(
JavaScriptChannelParams(
name: 'test',
onMessageReceived: (_) {},
),
),
throwsUnimplementedError,
);
});
test(
'Default implementation of removeJavaScriptChannel should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.removeJavaScriptChannel('test'),
throwsUnimplementedError,
);
});
test('Default implementation of getTitle should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.getTitle(),
throwsUnimplementedError,
);
});
test('Default implementation of scrollTo should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.scrollTo(0, 0),
throwsUnimplementedError,
);
});
test('Default implementation of scrollBy should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.scrollBy(0, 0),
throwsUnimplementedError,
);
});
test(
'Default implementation of getScrollPosition should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.getScrollPosition(),
throwsUnimplementedError,
);
});
test('Default implementation of enableZoom should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.enableZoom(true),
throwsUnimplementedError,
);
});
test(
'Default implementation of setBackgroundColor should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.setBackgroundColor(Colors.blue),
throwsUnimplementedError,
);
});
test(
'Default implementation of setJavaScriptMode should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.setJavaScriptMode(JavaScriptMode.disabled),
throwsUnimplementedError,
);
});
test(
'Default implementation of setUserAgent should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.setUserAgent(null),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnPermissionRequest should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.setOnPlatformPermissionRequest((_) {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of getUserAgent should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.getUserAgent(),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnConsoleMessage should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() =>
controller.setOnConsoleMessage((JavaScriptConsoleMessage message) {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnJavaScriptAlertDialog should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.setOnJavaScriptAlertDialog((_) async {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnJavaScriptConfirmDialog should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.setOnJavaScriptConfirmDialog((_) async {
return false;
}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnJavaScriptTextInputDialog should throw unimplemented error',
() {
final PlatformWebViewController controller =
ExtendsPlatformWebViewController(
const PlatformWebViewControllerCreationParams());
expect(
() => controller.setOnJavaScriptTextInputDialog((_) async {
return '';
}),
throwsUnimplementedError,
);
});
}
class MockWebViewPlatformWithMixin extends MockWebViewPlatform
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin {}
class ImplementsPlatformWebViewController implements PlatformWebViewController {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class MockWebViewControllerDelegate extends Mock
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin
implements
PlatformWebViewController {}
class ExtendsPlatformWebViewController extends PlatformWebViewController {
ExtendsPlatformWebViewController(super.params) : super.implementation();
}
// ignore: must_be_immutable
class MockLoadRequestParamsDelegate extends Mock
with
//ignore: prefer_mixin
MockPlatformInterfaceMixin
implements
LoadRequestParams {}
| packages/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.dart', 'repo_id': 'packages', 'token_count': 4943} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'package:webview_flutter_web/webview_flutter_web.dart';
void main() {
WebViewPlatform.instance = WebWebViewPlatform();
runApp(const MaterialApp(home: _WebViewExample()));
}
class _WebViewExample extends StatefulWidget {
const _WebViewExample();
@override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<_WebViewExample> {
final PlatformWebViewController _controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)..loadRequest(
LoadRequestParams(
uri: Uri.parse('https://flutter.dev'),
),
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView example'),
actions: <Widget>[
_SampleMenu(_controller),
],
),
body: PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: _controller),
).build(context),
);
}
}
enum _MenuOptions {
doPostRequest,
}
class _SampleMenu extends StatelessWidget {
const _SampleMenu(this.controller);
final PlatformWebViewController controller;
@override
Widget build(BuildContext context) {
return PopupMenuButton<_MenuOptions>(
onSelected: (_MenuOptions value) {
switch (value) {
case _MenuOptions.doPostRequest:
_onDoPostRequest(controller);
}
},
itemBuilder: (BuildContext context) => <PopupMenuItem<_MenuOptions>>[
const PopupMenuItem<_MenuOptions>(
value: _MenuOptions.doPostRequest,
child: Text('Post Request'),
),
],
);
}
Future<void> _onDoPostRequest(PlatformWebViewController controller) async {
final LoadRequestParams params = LoadRequestParams(
uri: Uri.parse('https://httpbin.org/post'),
method: LoadRequestMethod.post,
headers: const <String, String>{
'foo': 'bar',
'Content-Type': 'text/plain'
},
body: Uint8List.fromList('Test Body'.codeUnits),
);
await controller.loadRequest(params);
}
}
| packages/packages/webview_flutter/webview_flutter_web/example/lib/main.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_web/example/lib/main.dart', 'repo_id': 'packages', 'token_count': 916} |
// 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_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart';
import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart';
import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart';
import 'package:webview_flutter_wkwebview/src/foundation/foundation_api_impls.dart';
import '../common/test_web_kit.g.dart';
import 'foundation_test.mocks.dart';
@GenerateMocks(<Type>[
TestNSObjectHostApi,
TestNSUrlCredentialHostApi,
TestNSUrlHostApi,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Foundation', () {
late InstanceManager instanceManager;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
});
group('NSObject', () {
late MockTestNSObjectHostApi mockPlatformHostApi;
late NSObject object;
setUp(() {
mockPlatformHostApi = MockTestNSObjectHostApi();
TestNSObjectHostApi.setup(mockPlatformHostApi);
object = NSObject.detached(instanceManager: instanceManager);
instanceManager.addDartCreatedInstance(object);
});
tearDown(() {
TestNSObjectHostApi.setup(null);
});
test('addObserver', () async {
final NSObject observer = NSObject.detached(
instanceManager: instanceManager,
);
instanceManager.addDartCreatedInstance(observer);
await object.addObserver(
observer,
keyPath: 'aKeyPath',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.initialValue,
NSKeyValueObservingOptions.priorNotification,
},
);
final List<NSKeyValueObservingOptionsEnumData?> optionsData =
verify(mockPlatformHostApi.addObserver(
instanceManager.getIdentifier(object),
instanceManager.getIdentifier(observer),
'aKeyPath',
captureAny,
)).captured.single as List<NSKeyValueObservingOptionsEnumData?>;
expect(optionsData, hasLength(2));
expect(
optionsData[0]!.value,
NSKeyValueObservingOptionsEnum.initialValue,
);
expect(
optionsData[1]!.value,
NSKeyValueObservingOptionsEnum.priorNotification,
);
});
test('removeObserver', () async {
final NSObject observer = NSObject.detached(
instanceManager: instanceManager,
);
instanceManager.addDartCreatedInstance(observer);
await object.removeObserver(observer, keyPath: 'aKeyPath');
verify(mockPlatformHostApi.removeObserver(
instanceManager.getIdentifier(object),
instanceManager.getIdentifier(observer),
'aKeyPath',
));
});
test('NSObjectHostApi.dispose', () async {
int? callbackIdentifier;
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (int identifier) {
callbackIdentifier = identifier;
});
final NSObject object = NSObject.detached(
instanceManager: instanceManager,
);
final int identifier = instanceManager.addDartCreatedInstance(object);
NSObject.dispose(object);
expect(callbackIdentifier, identifier);
});
test('observeValue', () async {
final Completer<List<Object?>> argsCompleter =
Completer<List<Object?>>();
FoundationFlutterApis.instance = FoundationFlutterApis(
instanceManager: instanceManager,
);
object = NSObject.detached(
instanceManager: instanceManager,
observeValue: (
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) {
argsCompleter.complete(<Object?>[keyPath, object, change]);
},
);
instanceManager.addHostCreatedInstance(object, 1);
FoundationFlutterApis.instance.object.observeValue(
1,
'keyPath',
1,
<NSKeyValueChangeKeyEnumData>[
NSKeyValueChangeKeyEnumData(value: NSKeyValueChangeKeyEnum.oldValue)
],
<ObjectOrIdentifier?>[
ObjectOrIdentifier(isIdentifier: false, value: 'value'),
],
);
expect(
argsCompleter.future,
completion(<Object?>[
'keyPath',
object,
<NSKeyValueChangeKey, Object?>{
NSKeyValueChangeKey.oldValue: 'value',
},
]),
);
});
test('observeValue returns object in an `InstanceManager`', () async {
final Completer<List<Object?>> argsCompleter =
Completer<List<Object?>>();
FoundationFlutterApis.instance = FoundationFlutterApis(
instanceManager: instanceManager,
);
object = NSObject.detached(
instanceManager: instanceManager,
observeValue: (
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) {
argsCompleter.complete(<Object?>[keyPath, object, change]);
},
);
instanceManager.addHostCreatedInstance(object, 1);
final NSObject returnedObject = NSObject.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(returnedObject, 2);
FoundationFlutterApis.instance.object.observeValue(
1,
'keyPath',
1,
<NSKeyValueChangeKeyEnumData>[
NSKeyValueChangeKeyEnumData(value: NSKeyValueChangeKeyEnum.oldValue)
],
<ObjectOrIdentifier?>[
ObjectOrIdentifier(isIdentifier: true, value: 2),
],
);
expect(
argsCompleter.future,
completion(<Object?>[
'keyPath',
object,
<NSKeyValueChangeKey, Object?>{
NSKeyValueChangeKey.oldValue: returnedObject,
},
]),
);
});
test('NSObjectFlutterApi.dispose', () {
FoundationFlutterApis.instance = FoundationFlutterApis(
instanceManager: instanceManager,
);
object = NSObject.detached(instanceManager: instanceManager);
instanceManager.addHostCreatedInstance(object, 1);
instanceManager.removeWeakReference(object);
FoundationFlutterApis.instance.object.dispose(1);
expect(instanceManager.containsIdentifier(1), isFalse);
});
});
group('NSUrl', () {
// Ensure the test host api is removed after each test run.
tearDown(() => TestNSUrlHostApi.setup(null));
test('getAbsoluteString', () async {
final MockTestNSUrlHostApi mockApi = MockTestNSUrlHostApi();
TestNSUrlHostApi.setup(mockApi);
final NSUrl url = NSUrl.detached(instanceManager: instanceManager);
instanceManager.addHostCreatedInstance(url, 0);
when(mockApi.getAbsoluteString(0)).thenReturn('myString');
expect(await url.getAbsoluteString(), 'myString');
});
test('Flutter API create', () {
final NSUrlFlutterApi flutterApi = NSUrlFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(0);
expect(instanceManager.getInstanceWithWeakReference(0), isA<NSUrl>());
});
});
group('NSUrlCredential', () {
tearDown(() {
TestNSUrlCredentialHostApi.setup(null);
});
test('HostApi createWithUser', () {
final MockTestNSUrlCredentialHostApi mockApi =
MockTestNSUrlCredentialHostApi();
TestNSUrlCredentialHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const String user = 'testString';
const String password = 'testString2';
const NSUrlCredentialPersistence persistence =
NSUrlCredentialPersistence.permanent;
final NSUrlCredential instance = NSUrlCredential.withUser(
user: user,
password: password,
persistence: persistence,
instanceManager: instanceManager,
);
verify(mockApi.createWithUser(
instanceManager.getIdentifier(instance),
user,
password,
persistence,
));
});
});
group('NSUrlProtectionSpace', () {
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final NSUrlProtectionSpaceFlutterApiImpl api =
NSUrlProtectionSpaceFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
api.create(
instanceIdentifier,
'testString',
'testString',
'testAuthenticationMethod',
);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<NSUrlProtectionSpace>(),
);
});
});
group('NSUrlAuthenticationChallenge', () {
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final NSUrlAuthenticationChallengeFlutterApiImpl api =
NSUrlAuthenticationChallengeFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
const int protectionSpaceIdentifier = 1;
instanceManager.addHostCreatedInstance(
NSUrlProtectionSpace.detached(
host: null,
realm: null,
authenticationMethod: null,
instanceManager: instanceManager,
),
protectionSpaceIdentifier,
);
api.create(instanceIdentifier, protectionSpaceIdentifier);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<NSUrlAuthenticationChallenge>(),
);
});
});
});
test('NSError', () {
expect(
const NSError(
code: 0,
domain: 'domain',
userInfo: <String, Object?>{
NSErrorUserInfoKey.NSLocalizedDescription: 'desc',
},
).toString(),
'desc (domain:0:{NSLocalizedDescription: desc})',
);
expect(
const NSError(
code: 0,
domain: 'domain',
userInfo: <String, Object?>{
NSErrorUserInfoKey.NSLocalizedDescription: '',
},
).toString(),
'Error domain:0:{NSLocalizedDescription: }',
);
expect(
const NSError(
code: 255,
domain: 'bar',
userInfo: <String, Object?>{
NSErrorUserInfoKey.NSLocalizedDescription: 'baz',
},
).toString(),
'baz (bar:255:{NSLocalizedDescription: baz})',
);
expect(
const NSError(
code: 255,
domain: 'bar',
userInfo: <String, Object?>{
NSErrorUserInfoKey.NSLocalizedDescription: '',
},
).toString(),
'Error bar:255:{NSLocalizedDescription: }',
);
});
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/foundation/foundation_test.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/foundation/foundation_test.dart', 'repo_id': 'packages', 'token_count': 5066} |
// 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 'package:git/git.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:yaml/yaml.dart';
/// Finding diffs based on `baseGitDir` and `baseSha`.
class GitVersionFinder {
/// Constructor
GitVersionFinder(this.baseGitDir, {String? baseSha, String? baseBranch})
: assert(baseSha == null || baseBranch == null,
'At most one of baseSha and baseBranch can be provided'),
_baseSha = baseSha,
_baseBranch = baseBranch ?? 'FETCH_HEAD';
/// The top level directory of the git repo.
///
/// That is where the .git/ folder exists.
final GitDir baseGitDir;
/// The base sha used to get diff.
String? _baseSha;
/// The base branche used to find a merge point if baseSha is not provided.
final String _baseBranch;
static bool _isPubspec(String file) {
return file.trim().endsWith('pubspec.yaml');
}
/// Get a list of all the pubspec.yaml file that is changed.
Future<List<String>> getChangedPubSpecs() async {
return (await getChangedFiles()).where(_isPubspec).toList();
}
/// Get a list of all the changed files.
Future<List<String>> getChangedFiles(
{bool includeUncommitted = false}) async {
final String baseSha = await getBaseSha();
final io.ProcessResult changedFilesCommand = await baseGitDir
.runCommand(<String>[
'diff',
'--name-only',
baseSha,
if (!includeUncommitted) 'HEAD'
]);
final String changedFilesStdout = changedFilesCommand.stdout.toString();
if (changedFilesStdout.isEmpty) {
return <String>[];
}
final List<String> changedFiles = changedFilesStdout.split('\n')
..removeWhere((String element) => element.isEmpty);
return changedFiles.toList();
}
/// Get a list of all the changed files.
Future<List<String>> getDiffContents({
String? targetPath,
bool includeUncommitted = false,
}) async {
final String baseSha = await getBaseSha();
final io.ProcessResult diffCommand = await baseGitDir.runCommand(<String>[
'diff',
baseSha,
if (!includeUncommitted) 'HEAD',
if (targetPath != null) ...<String>['--', targetPath],
]);
final String diffStdout = diffCommand.stdout.toString();
if (diffStdout.isEmpty) {
return <String>[];
}
final List<String> changedFiles = diffStdout.split('\n')
..removeWhere((String element) => element.isEmpty);
return changedFiles.toList();
}
/// Get the package version specified in the pubspec file in `pubspecPath` and
/// at the revision of `gitRef` (defaulting to the base if not provided).
Future<Version?> getPackageVersion(String pubspecPath,
{String? gitRef}) async {
final String ref = gitRef ?? (await getBaseSha());
io.ProcessResult gitShow;
try {
gitShow =
await baseGitDir.runCommand(<String>['show', '$ref:$pubspecPath']);
} on io.ProcessException {
return null;
}
final String fileContent = gitShow.stdout as String;
if (fileContent.trim().isEmpty) {
return null;
}
final YamlMap fileYaml = loadYaml(fileContent) as YamlMap;
final String? versionString = fileYaml['version'] as String?;
return versionString == null ? null : Version.parse(versionString);
}
/// Returns the base used to diff against.
Future<String> getBaseSha() async {
String? baseSha = _baseSha;
if (baseSha != null && baseSha.isNotEmpty) {
return baseSha;
}
io.ProcessResult baseShaFromMergeBase = await baseGitDir.runCommand(
<String>['merge-base', '--fork-point', _baseBranch, 'HEAD'],
throwOnError: false);
final String stdout = (baseShaFromMergeBase.stdout as String? ?? '').trim();
final String stderr = (baseShaFromMergeBase.stderr as String? ?? '').trim();
if (stderr.isNotEmpty || stdout.isEmpty) {
baseShaFromMergeBase = await baseGitDir
.runCommand(<String>['merge-base', _baseBranch, 'HEAD']);
}
baseSha = (baseShaFromMergeBase.stdout as String).trim();
_baseSha = baseSha;
return baseSha;
}
}
| packages/script/tool/lib/src/common/git_version_finder.dart/0 | {'file_path': 'packages/script/tool/lib/src/common/git_version_finder.dart', 'repo_id': 'packages', 'token_count': 1569} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:file/file.dart';
import 'common/core.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/plugin_utils.dart';
import 'common/repository_package.dart';
const int _exitNoPlatformFlags = 2;
const int _exitNoAvailableDevice = 3;
// From https://docs.flutter.dev/testing/integration-tests#running-in-a-browser
const int _chromeDriverPort = 4444;
/// A command to run the integration tests for a package's example applications.
class DriveExamplesCommand extends PackageLoopingCommand {
/// Creates an instance of the drive command.
DriveExamplesCommand(
super.packagesDir, {
super.processRunner,
super.platform,
}) {
argParser.addFlag(platformAndroid,
help: 'Runs the Android implementation of the examples',
aliases: const <String>[platformAndroidAlias]);
argParser.addFlag(platformIOS,
help: 'Runs the iOS implementation of the examples');
argParser.addFlag(platformLinux,
help: 'Runs the Linux implementation of the examples');
argParser.addFlag(platformMacOS,
help: 'Runs the macOS implementation of the examples');
argParser.addFlag(platformWeb,
help: 'Runs the web implementation of the examples');
argParser.addFlag(platformWindows,
help: 'Runs the Windows implementation of the examples');
argParser.addOption(
kEnableExperiment,
defaultsTo: '',
help:
'Runs the driver tests in Dart VM with the given experiments enabled.',
);
argParser.addFlag(_chromeDriverFlag,
help: 'Runs chromedriver for the duration of the test.\n\n'
'Requires the correct version of chromedriver to be in your path.');
}
static const String _chromeDriverFlag = 'run-chromedriver';
@override
final String name = 'drive-examples';
@override
final String description = 'Runs Dart integration tests for example apps.\n\n'
"This runs all tests in each example's integration_test directory, "
'via "flutter test" on most platforms, and "flutter drive" on web.\n\n'
'This command requires "flutter" to be in your path.';
Map<String, List<String>> _targetDeviceFlags = const <String, List<String>>{};
@override
Future<void> initializeRun() async {
final List<String> platformSwitches = <String>[
platformAndroid,
platformIOS,
platformLinux,
platformMacOS,
platformWeb,
platformWindows,
];
final int platformCount = platformSwitches
.where((String platform) => getBoolArg(platform))
.length;
// The flutter tool currently doesn't accept multiple device arguments:
// https://github.com/flutter/flutter/issues/35733
// If that is implemented, this check can be relaxed.
if (platformCount != 1) {
printError(
'Exactly one of ${platformSwitches.map((String platform) => '--$platform').join(', ')} '
'must be specified.');
throw ToolExit(_exitNoPlatformFlags);
}
String? androidDevice;
if (getBoolArg(platformAndroid)) {
final List<String> devices = await _getDevicesForPlatform('android');
if (devices.isEmpty) {
printError('No Android devices available');
throw ToolExit(_exitNoAvailableDevice);
}
androidDevice = devices.first;
}
String? iOSDevice;
if (getBoolArg(platformIOS)) {
final List<String> devices = await _getDevicesForPlatform('ios');
if (devices.isEmpty) {
printError('No iOS devices available');
throw ToolExit(_exitNoAvailableDevice);
}
iOSDevice = devices.first;
}
_targetDeviceFlags = <String, List<String>>{
if (getBoolArg(platformAndroid))
platformAndroid: <String>['-d', androidDevice!],
if (getBoolArg(platformIOS)) platformIOS: <String>['-d', iOSDevice!],
if (getBoolArg(platformLinux)) platformLinux: <String>['-d', 'linux'],
if (getBoolArg(platformMacOS)) platformMacOS: <String>['-d', 'macos'],
if (getBoolArg(platformWeb))
platformWeb: <String>[
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
if (platform.environment.containsKey('CHROME_EXECUTABLE'))
'--chrome-binary=${platform.environment['CHROME_EXECUTABLE']}',
],
if (getBoolArg(platformWindows))
platformWindows: <String>['-d', 'windows'],
};
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
final bool isPlugin = isFlutterPlugin(package);
if (package.isPlatformInterface && package.getExamples().isEmpty) {
// Platform interface packages generally aren't intended to have
// examples, and don't need integration tests, so skip rather than fail.
return PackageResult.skip(
'Platform interfaces are not expected to have integration tests.');
}
// For plugin packages, skip if the plugin itself doesn't support any
// requested platform(s).
if (isPlugin) {
final Iterable<String> requestedPlatforms = _targetDeviceFlags.keys;
final Iterable<String> unsupportedPlatforms = requestedPlatforms.where(
(String platform) => !pluginSupportsPlatform(platform, package));
for (final String platform in unsupportedPlatforms) {
print('Skipping unsupported platform $platform...');
}
if (unsupportedPlatforms.length == requestedPlatforms.length) {
return PackageResult.skip(
'${package.displayName} does not support any requested platform.');
}
}
int examplesFound = 0;
int supportedExamplesFound = 0;
bool testsRan = false;
final List<String> errors = <String>[];
for (final RepositoryPackage example in package.getExamples()) {
++examplesFound;
final String exampleName =
getRelativePosixPath(example.directory, from: packagesDir);
// Skip examples that don't support any requested platform(s).
final List<String> deviceFlags = _deviceFlagsForExample(example);
if (deviceFlags.isEmpty) {
print(
'Skipping $exampleName; does not support any requested platforms.');
continue;
}
++supportedExamplesFound;
final List<File> testTargets = await _getIntegrationTests(example);
if (testTargets.isEmpty) {
print('No integration_test/*.dart files found for $exampleName.');
continue;
}
// Check files for known problematic patterns.
testTargets
.where((File file) => !_validateIntegrationTest(file))
.forEach((File file) {
// Report the issue, but continue with the test as the validation
// errors don't prevent running.
errors.add('${file.basename} failed validation');
});
// `flutter test` doesn't yet support web integration tests, so fall back
// to `flutter drive`.
final bool useFlutterDrive = getBoolArg(platformWeb);
final List<File> drivers;
if (useFlutterDrive) {
drivers = await _getDrivers(example);
if (drivers.isEmpty) {
print('No driver found for $exampleName');
continue;
}
} else {
drivers = <File>[];
}
testsRan = true;
if (useFlutterDrive) {
Process? chromedriver;
if (getBoolArg(_chromeDriverFlag)) {
print('Starting chromedriver on port $_chromeDriverPort');
chromedriver = await processRunner
.start('chromedriver', <String>['--port=$_chromeDriverPort']);
}
for (final File driver in drivers) {
final List<File> failingTargets = await _driveTests(
example, driver, testTargets,
deviceFlags: deviceFlags);
for (final File failingTarget in failingTargets) {
errors.add(
getRelativePosixPath(failingTarget, from: package.directory));
}
}
if (chromedriver != null) {
print('Stopping chromedriver');
chromedriver.kill();
}
} else {
if (!await _runTests(example,
deviceFlags: deviceFlags, testFiles: testTargets)) {
errors.add('Integration tests failed.');
}
}
}
if (!testsRan) {
// It is an error for a plugin not to have integration tests, because that
// is the only way to test the method channel communication.
if (isPlugin) {
printError(
'No driver tests were run ($examplesFound example(s) found).');
errors.add('No tests ran (use --exclude if this is intentional).');
} else {
return PackageResult.skip(supportedExamplesFound == 0
? 'No example supports requested platform(s).'
: 'No example is configured for integration tests.');
}
}
return errors.isEmpty
? PackageResult.success()
: PackageResult.fail(errors);
}
/// Returns the device flags for the intersection of the requested platforms
/// and the platforms supported by [example].
List<String> _deviceFlagsForExample(RepositoryPackage example) {
final List<String> deviceFlags = <String>[];
for (final MapEntry<String, List<String>> entry
in _targetDeviceFlags.entries) {
final String platform = entry.key;
if (example.appSupportsPlatform(getPlatformByName(platform))) {
deviceFlags.addAll(entry.value);
} else {
final String exampleName =
getRelativePosixPath(example.directory, from: packagesDir);
print('Skipping unsupported platform $platform for $exampleName');
}
}
return deviceFlags;
}
Future<List<String>> _getDevicesForPlatform(String platform) async {
final List<String> deviceIds = <String>[];
final ProcessResult result = await processRunner.run(
flutterCommand, <String>['devices', '--machine'],
stdoutEncoding: utf8);
if (result.exitCode != 0) {
return deviceIds;
}
String output = result.stdout as String;
// --machine doesn't currently prevent the tool from printing banners;
// see https://github.com/flutter/flutter/issues/86055. This workaround
// can be removed once that is fixed.
output = output.substring(output.indexOf('['));
final List<Map<String, dynamic>> devices =
(jsonDecode(output) as List<dynamic>).cast<Map<String, dynamic>>();
for (final Map<String, dynamic> deviceInfo in devices) {
final String targetPlatform =
(deviceInfo['targetPlatform'] as String?) ?? '';
if (targetPlatform.startsWith(platform)) {
final String? deviceId = deviceInfo['id'] as String?;
if (deviceId != null) {
deviceIds.add(deviceId);
}
}
}
return deviceIds;
}
Future<List<File>> _getDrivers(RepositoryPackage example) async {
final List<File> drivers = <File>[];
final Directory driverDir = example.directory.childDirectory('test_driver');
if (driverDir.existsSync()) {
await for (final FileSystemEntity driver in driverDir.list()) {
if (driver is File && driver.basename.endsWith('_test.dart')) {
drivers.add(driver);
}
}
}
return drivers;
}
Future<List<File>> _getIntegrationTests(RepositoryPackage example) async {
final List<File> tests = <File>[];
final Directory integrationTestDir =
example.directory.childDirectory('integration_test');
if (integrationTestDir.existsSync()) {
await for (final FileSystemEntity file
in integrationTestDir.list(recursive: true)) {
if (file is File && file.basename.endsWith('_test.dart')) {
tests.add(file);
}
}
}
return tests;
}
/// Checks [testFile] for known bad patterns in integration tests, logging
/// any issues.
///
/// Returns true if the file passes validation without issues.
bool _validateIntegrationTest(File testFile) {
final List<String> lines = testFile.readAsLinesSync();
final RegExp badTestPattern = RegExp(r'\s*test\(');
if (lines.any((String line) => line.startsWith(badTestPattern))) {
final String filename = testFile.basename;
printError(
'$filename uses "test", which will not report failures correctly. '
'Use testWidgets instead.');
return false;
}
return true;
}
/// For each file in [targets], uses
/// `flutter drive --driver [driver] --target <target>`
/// to drive [example], returning a list of any failing test targets.
///
/// [deviceFlags] should contain the flags to run the test on a specific
/// target device (plus any supporting device-specific flags). E.g.:
/// - `['-d', 'macos']` for driving for macOS.
/// - `['-d', 'web-server', '--web-port=<port>', '--browser-name=<browser>]`
/// for web
Future<List<File>> _driveTests(
RepositoryPackage example,
File driver,
List<File> targets, {
required List<String> deviceFlags,
}) async {
final List<File> failures = <File>[];
final String enableExperiment = getStringArg(kEnableExperiment);
for (final File target in targets) {
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>[
'drive',
...deviceFlags,
if (enableExperiment.isNotEmpty)
'--enable-experiment=$enableExperiment',
'--driver',
getRelativePosixPath(driver, from: example.directory),
'--target',
getRelativePosixPath(target, from: example.directory),
],
workingDir: example.directory);
if (exitCode != 0) {
failures.add(target);
}
}
return failures;
}
/// Uses `flutter test integration_test` to run [example], returning the
/// success of the test run.
///
/// [deviceFlags] should contain the flags to run the test on a specific
/// target device (plus any supporting device-specific flags). E.g.:
/// - `['-d', 'macos']` for driving for macOS.
/// - `['-d', 'web-server', '--web-port=<port>', '--browser-name=<browser>]`
/// for web
Future<bool> _runTests(
RepositoryPackage example, {
required List<String> deviceFlags,
required List<File> testFiles,
}) async {
final String enableExperiment = getStringArg(kEnableExperiment);
// Workaround for https://github.com/flutter/flutter/issues/135673
// Once that is fixed on stable, this logic can be removed and the command
// can always just be run with "integration_test".
final bool needsMultipleInvocations =
testFiles.length > 1 && getBoolArg(platformMacOS);
final Iterable<String> individualRunTargets = needsMultipleInvocations
? testFiles
.map((File f) => getRelativePosixPath(f, from: example.directory))
: <String>['integration_test'];
bool passed = true;
for (final String target in individualRunTargets) {
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>[
'test',
...deviceFlags,
if (enableExperiment.isNotEmpty)
'--enable-experiment=$enableExperiment',
target,
],
workingDir: example.directory);
passed = passed && (exitCode == 0);
}
return passed;
}
}
| packages/script/tool/lib/src/drive_examples_command.dart/0 | {'file_path': 'packages/script/tool/lib/src/drive_examples_command.dart', 'repo_id': 'packages', 'token_count': 5816} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:flutter_plugin_tools/src/common/output_utils.dart';
import 'package:test/test.dart';
void main() {
group('with color support', () {
setUp(() {
useColorForOutput = true;
});
tearDown(() {
useColorForOutput = stdout.supportsAnsiEscapes;
});
test('colorize works', () async {
const String message = 'a message';
expect(
colorizeString(message, Styles.MAGENTA), '\x1B[35m$message\x1B[0m');
});
test('printSuccess is green', () async {
const String message = 'a message';
expect(await _capturePrint(() => printSuccess(message)),
'\x1B[32m$message\x1B[0m');
});
test('printWarning is yellow', () async {
const String message = 'a message';
expect(await _capturePrint(() => printWarning(message)),
'\x1B[33m$message\x1B[0m');
});
test('printError is red', () async {
const String message = 'a message';
expect(await _capturePrint(() => printError(message)),
'\x1B[31m$message\x1B[0m');
});
});
group('without color support', () {
setUp(() {
useColorForOutput = false;
});
tearDown(() {
useColorForOutput = stdout.supportsAnsiEscapes;
});
test('colorize no-ops', () async {
const String message = 'a message';
expect(colorizeString(message, Styles.MAGENTA), message);
});
test('printSuccess just prints', () async {
const String message = 'a message';
expect(await _capturePrint(() => printSuccess(message)), message);
});
test('printWarning just prints', () async {
const String message = 'a message';
expect(await _capturePrint(() => printWarning(message)), message);
});
test('printError just prints', () async {
const String message = 'a message';
expect(await _capturePrint(() => printError(message)), message);
});
});
}
/// Run the command [runner] with the given [args] and return
/// what was printed.
/// A custom [errorHandler] can be used to handle the runner error as desired without throwing.
Future<String> _capturePrint(void Function() printFunction) async {
final StringBuffer output = StringBuffer();
final ZoneSpecification spec = ZoneSpecification(
print: (_, __, ___, String message) {
output.write(message);
},
);
await Zone.current
.fork(specification: spec)
.run<Future<void>>(() async => printFunction());
return output.toString();
}
| packages/script/tool/test/common/output_utils_test.dart/0 | {'file_path': 'packages/script/tool/test/common/output_utils_test.dart', 'repo_id': 'packages', 'token_count': 979} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/common/plugin_utils.dart';
import 'package:flutter_plugin_tools/src/fetch_deps_command.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
group('FetchDepsCommand', () {
FileSystem fileSystem;
late Directory packagesDir;
late CommandRunner<void> runner;
late MockPlatform mockPlatform;
late RecordingProcessRunner processRunner;
setUp(() {
fileSystem = MemoryFileSystem();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
mockPlatform = MockPlatform();
processRunner = RecordingProcessRunner();
final FetchDepsCommand command = FetchDepsCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner =
CommandRunner<void>('fetch_deps_test', 'Test for $FetchDepsCommand');
runner.addCommand(command);
});
group('dart', () {
test('runs pub get', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin1', packagesDir, platformSupport: <String, PlatformDetails>{
platformIOS: const PlatformDetails(PlatformSupport.inline)
});
final List<String> output =
await runCapturingPrint(runner, <String>['fetch-deps']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'flutter',
const <String>['pub', 'get'],
plugin.directory.path,
),
]),
);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin1'),
contains('No issues found!'),
]));
});
test('fails if pub get fails', () async {
createFakePlugin('plugin1', packagesDir,
platformSupport: <String, PlatformDetails>{
platformIOS: const PlatformDetails(PlatformSupport.inline)
});
processRunner
.mockProcessesForExecutable[getFlutterCommand(mockPlatform)] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1)),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Failed to "pub get"'),
],
));
});
test('skips unsupported packages when any platforms are passed',
() async {
final RepositoryPackage packageWithBoth = createFakePackage(
'supports_both', packagesDir, extraFiles: <String>[
'example/linux/placeholder',
'example/windows/placeholder'
]);
final RepositoryPackage packageWithOne = createFakePackage(
'supports_one', packagesDir,
extraFiles: <String>['example/linux/placeholder']);
createFakePackage('supports_neither', packagesDir);
await runCapturingPrint(runner, <String>[
'fetch-deps',
'--linux',
'--windows',
'--supporting-target-platforms-only'
]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'dart',
const <String>['pub', 'get'],
packageWithBoth.path,
),
ProcessCall(
'dart',
const <String>['pub', 'get'],
packageWithOne.path,
),
]),
);
});
});
group('android', () {
test('runs pub get before gradlew dependencies', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin1', packagesDir, extraFiles: <String>[
'example/android/gradlew',
], platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline)
});
final Directory androidDir = plugin
.getExamples()
.first
.platformDirectory(FlutterPlatform.android);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--android']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'flutter',
const <String>['pub', 'get'],
plugin.directory.path,
),
ProcessCall(
androidDir.childFile('gradlew').path,
const <String>['plugin1:dependencies'],
androidDir.path,
),
]),
);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin1'),
contains('No issues found!'),
]));
});
test('runs gradlew dependencies', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin1', packagesDir, extraFiles: <String>[
'example/android/gradlew',
], platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline)
});
final Directory androidDir = plugin
.getExamples()
.first
.platformDirectory(FlutterPlatform.android);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--android']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
androidDir.childFile('gradlew').path,
const <String>['plugin1:dependencies'],
androidDir.path,
),
]),
);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin1'),
contains('No issues found!'),
]));
});
test('runs on all examples', () async {
final List<String> examples = <String>['example1', 'example2'];
final RepositoryPackage plugin = createFakePlugin(
'plugin1', packagesDir,
examples: examples,
extraFiles: <String>[
'example/example1/android/gradlew',
'example/example2/android/gradlew',
],
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline)
});
final Iterable<Directory> exampleAndroidDirs = plugin.getExamples().map(
(RepositoryPackage example) =>
example.platformDirectory(FlutterPlatform.android));
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--android']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
for (final Directory directory in exampleAndroidDirs)
ProcessCall(
directory.childFile('gradlew').path,
const <String>['plugin1:dependencies'],
directory.path,
),
]),
);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin1'),
contains('No issues found!'),
]));
});
test('runs --config-only build if gradlew is missing', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin1', packagesDir, platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline)
});
final Directory androidDir = plugin
.getExamples()
.first
.platformDirectory(FlutterPlatform.android);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--android']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>['build', 'apk', '--config-only'],
plugin.getExamples().first.directory.path,
),
ProcessCall(
androidDir.childFile('gradlew').path,
const <String>['plugin1:dependencies'],
androidDir.path,
),
]),
);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin1'),
contains('No issues found!'),
]));
});
test('fails if gradlew generation fails', () async {
createFakePlugin('plugin1', packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline)
});
processRunner
.mockProcessesForExecutable[getFlutterCommand(mockPlatform)] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1)),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--android'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Unable to configure Gradle project'),
],
));
});
test('fails if dependency download finds issues', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin1', packagesDir, extraFiles: <String>[
'example/android/gradlew',
], platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline)
});
final String gradlewPath = plugin
.getExamples()
.first
.platformDirectory(FlutterPlatform.android)
.childFile('gradlew')
.path;
processRunner.mockProcessesForExecutable[gradlewPath] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1)),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--android'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('The following packages had errors:'),
],
));
});
test('skips non-Android plugins', () async {
createFakePlugin('plugin1', packagesDir);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--android']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Package does not have native Android dependencies.')
],
));
});
test('skips non-inline plugins', () async {
createFakePlugin('plugin1', packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.federated)
});
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--android']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Package does not have native Android dependencies.')
],
));
});
});
group('ios', () {
test('runs on all examples', () async {
final List<String> examples = <String>['example1', 'example2'];
final RepositoryPackage plugin = createFakePlugin(
'plugin1', packagesDir,
examples: examples,
platformSupport: <String, PlatformDetails>{
platformIOS: const PlatformDetails(PlatformSupport.inline)
});
final Iterable<Directory> exampleDirs = plugin.getExamples().map(
(RepositoryPackage example) => example.directory);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--ios']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall(
'flutter',
<String>['precache', '--ios'],
null,
),
for (final Directory directory in exampleDirs)
ProcessCall(
'flutter',
const <String>['build', 'ios', '--config-only'],
directory.path,
),
]),
);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin1'),
contains('No issues found!'),
]));
});
test('fails if flutter build --config-only fails', () async {
createFakePlugin('plugin1', packagesDir,
platformSupport: <String, PlatformDetails>{
platformIOS: const PlatformDetails(PlatformSupport.inline)
});
processRunner
.mockProcessesForExecutable[getFlutterCommand(mockPlatform)] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(), <String>['precache']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>['build', 'ios', '--config-only']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--ios'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('The following packages had errors:'),
],
));
});
test('skips non-iOS plugins', () async {
createFakePlugin('plugin1', packagesDir);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--ios']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Package does not have native iOS dependencies.')
],
));
});
test('skips non-inline plugins', () async {
createFakePlugin('plugin1', packagesDir,
platformSupport: <String, PlatformDetails>{
platformIOS: const PlatformDetails(PlatformSupport.federated)
});
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--ios']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Package does not have native iOS dependencies.')
],
));
});
});
group('macos', () {
test('runs on all examples', () async {
final List<String> examples = <String>['example1', 'example2'];
final RepositoryPackage plugin = createFakePlugin(
'plugin1', packagesDir,
examples: examples,
platformSupport: <String, PlatformDetails>{
platformMacOS: const PlatformDetails(PlatformSupport.inline)
});
final Iterable<Directory> exampleDirs = plugin.getExamples().map(
(RepositoryPackage example) => example.directory);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--macos']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall(
'flutter',
<String>['precache', '--macos'],
null,
),
for (final Directory directory in exampleDirs)
ProcessCall(
'flutter',
const <String>['build', 'macos', '--config-only'],
directory.path,
),
]),
);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin1'),
contains('No issues found!'),
]));
});
test('fails if flutter build --config-only fails', () async {
createFakePlugin('plugin1', packagesDir,
platformSupport: <String, PlatformDetails>{
platformMacOS: const PlatformDetails(PlatformSupport.inline)
});
processRunner
.mockProcessesForExecutable[getFlutterCommand(mockPlatform)] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(), <String>['precache']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>['build', 'macos', '--config-only']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--macos'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('The following packages had errors:'),
],
));
});
test('skips non-macOS plugins', () async {
createFakePlugin('plugin1', packagesDir);
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--macos']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Package does not have native macOS dependencies.')
],
));
});
test('skips non-inline plugins', () async {
createFakePlugin('plugin1', packagesDir,
platformSupport: <String, PlatformDetails>{
platformMacOS: const PlatformDetails(PlatformSupport.federated)
});
final List<String> output = await runCapturingPrint(
runner, <String>['fetch-deps', '--no-dart', '--macos']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Package does not have native macOS dependencies.')
],
));
});
});
});
}
| packages/script/tool/test/fetch_deps_command_test.dart/0 | {'file_path': 'packages/script/tool/test/fetch_deps_command_test.dart', 'repo_id': 'packages', 'token_count': 9089} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/remove_dev_dependencies_command.dart';
import 'package:test/test.dart';
import 'util.dart';
void main() {
late FileSystem fileSystem;
late Directory packagesDir;
late CommandRunner<void> runner;
setUp(() {
fileSystem = MemoryFileSystem();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
final RemoveDevDependenciesCommand command = RemoveDevDependenciesCommand(
packagesDir,
);
runner = CommandRunner<void>('trim_dev_dependencies_command',
'Test for trim_dev_dependencies_command');
runner.addCommand(command);
});
void addToPubspec(RepositoryPackage package, String addition) {
final String originalContent = package.pubspecFile.readAsStringSync();
package.pubspecFile.writeAsStringSync('''
$originalContent
$addition
''');
}
test('skips if nothing is removed', () async {
createFakePackage('a_package', packagesDir, version: '1.0.0');
final List<String> output =
await runCapturingPrint(runner, <String>['remove-dev-dependencies']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('SKIPPING: Nothing to remove.'),
]),
);
});
test('removes dev_dependencies', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
addToPubspec(package, '''
dev_dependencies:
some_dependency: ^2.1.8
another_dependency: ^1.0.0
''');
final List<String> output =
await runCapturingPrint(runner, <String>['remove-dev-dependencies']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Removed dev_dependencies'),
]),
);
expect(package.pubspecFile.readAsStringSync(),
isNot(contains('some_dependency:')));
expect(package.pubspecFile.readAsStringSync(),
isNot(contains('another_dependency:')));
});
test('removes from examples', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
final RepositoryPackage example = package.getExamples().first;
addToPubspec(example, '''
dev_dependencies:
some_dependency: ^2.1.8
another_dependency: ^1.0.0
''');
final List<String> output =
await runCapturingPrint(runner, <String>['remove-dev-dependencies']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Removed dev_dependencies'),
]),
);
expect(package.pubspecFile.readAsStringSync(),
isNot(contains('some_dependency:')));
expect(package.pubspecFile.readAsStringSync(),
isNot(contains('another_dependency:')));
});
}
| packages/script/tool/test/remove_dev_dependencies_command_test.dart/0 | {'file_path': 'packages/script/tool/test/remove_dev_dependencies_command_test.dart', 'repo_id': 'packages', 'token_count': 1062} |
// Copyright (c) 2017, 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.
library pana.license;
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:meta/meta.dart';
import 'package:pana/src/license_detection/license_detector.dart';
import 'package:path/path.dart' as p;
import 'maintenance.dart';
import 'model.dart';
Future<LicenseFile?> detectLicenseInDir(String baseDir) async {
for (final candidate in licenseFileNames) {
final file = File(p.join(baseDir, candidate));
if (!file.existsSync()) continue;
return detectLicenseInFile(file, relativePath: candidate);
}
return null;
}
@visibleForTesting
Future<LicenseFile> detectLicenseInFile(File file,
{required String relativePath}) async {
final content = utf8.decode(await file.readAsBytes(), allowMalformed: true);
var license =
await detectLicenseInContent(content, relativePath: relativePath);
return license ?? LicenseFile(relativePath, LicenseNames.unknown);
}
/// Returns an instance of [LicenseFile] if [originalContent] has contains a license(s)
/// present in the [SPDX-corpus][1].
///
/// [1]: https://spdx.org/licenses/
Future<LicenseFile?> detectLicenseInContent(
String originalContent, {
required String relativePath,
}) async {
var content = originalContent;
final licenseResult = await detectLicense(content, 0.95);
if (licenseResult.matches.isNotEmpty &&
licenseResult.unclaimedTokenPercentage <= 0.5 &&
licenseResult.longestUnclaimedTokenCount < 50) {
return LicenseFile(
relativePath,
licenseResult.matches.first.identifier,
);
}
return null;
}
| pana/lib/src/license.dart/0 | {'file_path': 'pana/lib/src/license.dart', 'repo_id': 'pana', 'token_count': 560} |
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:pub_semver/pub_semver.dart';
import 'code_problem.dart';
import 'download_utils.dart';
import 'internal_model.dart';
import 'logging.dart';
import 'messages.dart' as messages;
import 'package_analyzer.dart' show InspectOptions;
import 'pkg_resolution.dart';
import 'pubspec.dart';
import 'pubspec_io.dart';
import 'sdk_env.dart';
import 'utils.dart' show listFocusDirs;
/// Calculates and stores the intermediate analysis and processing results that
/// are required for the final report.
class PackageContext {
final ToolEnvironment toolEnvironment;
final String packageDir;
final InspectOptions options;
final UrlChecker urlChecker;
final errors = <String>[];
final urlProblems = <String, String>{};
Version? _currentSdkVersion;
Pubspec? _pubspec;
bool? _usesFlutter;
PkgResolution? _pkgResolution;
List<CodeProblem>? _codeProblems;
PackageContext({
required this.toolEnvironment,
required this.packageDir,
required this.options,
UrlChecker? urlChecker,
}) : urlChecker = urlChecker ?? UrlChecker();
Version get currentSdkVersion => _currentSdkVersion ??=
Version.parse(toolEnvironment.runtimeInfo.sdkVersion);
Pubspec get pubspec {
if (_pubspec != null) return _pubspec!;
try {
_pubspec = pubspecFromDir(packageDir);
} catch (e, st) {
log.info('Unable to read pubspec.yaml', e, st);
rethrow;
}
return _pubspec!;
}
bool get usesFlutter => _usesFlutter ??= pubspec.usesFlutter;
Future<PkgResolution?> resolveDependencies() async {
if (_pkgResolution != null) return _pkgResolution;
final upgrade = await toolEnvironment.runUpgrade(packageDir, usesFlutter);
if (upgrade.exitCode == 0) {
try {
_pkgResolution = createPkgResolution(pubspec, upgrade.asJoinedOutput,
path: packageDir);
} catch (e, stack) {
log.severe('Problem with `dart pub upgrade`', e, stack);
//(TODO)kevmoo - should add a helper that handles logging exceptions
// and writing to issues in one go.
// Note: calling `flutter pub pub` ensures we get the raw `pub` output.
final cmd = usesFlutter ? 'flutter pub upgrade' : 'dart pub upgrade';
errors.add('Running `$cmd` failed with the following output:\n\n'
'```\n$e\n```\n');
}
} else {
String message;
if (upgrade.exitCode > 0) {
message = PubEntry.parse(upgrade.stderr as String)
.where((e) => e.header == 'ERR')
.join('\n');
} else {
message = LineSplitter.split(upgrade.stderr as String).first;
}
// 1: Version constraint issue with direct or transitive dependencies.
//
// 2: Code in a git repository could change or disappear.
final isUserProblem = message.contains('version solving failed') || // 1
pubspec.hasGitDependency || // 2
message.contains('Git error.'); // 2
if (!isUserProblem) {
log.severe('`dart pub upgrade` failed.\n$message'.trim());
}
// Note: calling `flutter pub pub` ensures we get the raw `pub` output.
final cmd = usesFlutter ? 'flutter pub upgrade' : 'dart pub upgrade';
errors.add(message.isEmpty
? 'Running `$cmd` failed.'
: 'Running `$cmd` failed with the following output:\n\n'
'```\n$message\n```\n');
}
return _pkgResolution;
}
Future<List<CodeProblem>> staticAnalysis() async {
if (_codeProblems != null) return _codeProblems!;
log.info('Analyzing package...');
try {
final dirs = await listFocusDirs(packageDir);
final problems = <CodeProblem>[];
for (final dir in dirs) {
final output = await toolEnvironment
.runAnalyzer(packageDir, dir, usesFlutter, inspectOptions: options);
final list = LineSplitter.split(output)
.map((s) => parseCodeProblem(s, projectDir: packageDir))
.whereNotNull()
.toSet()
.toList();
list.sort();
problems.addAll(list);
}
_codeProblems = problems;
return _codeProblems!;
} on ToolException catch (e) {
errors.add(messages.runningDartanalyzerFailed(usesFlutter, e.message));
rethrow;
}
}
bool get pubspecAllowsCurrentSdk =>
pubspec.dartSdkConstraint != null &&
pubspec.dartSdkConstraint!.allows(currentSdkVersion);
}
| pana/lib/src/package_context.dart/0 | {'file_path': 'pana/lib/src/package_context.dart', 'repo_id': 'pana', 'token_count': 1791} |
// Copyright (c) 2021, 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.
/// Represents a dart runtime and the `dart:` libraries available on that
/// platform.
class Runtime {
final String name;
final Set<String> enabledLibs;
final String? _tag;
Runtime(this.name, this.enabledLibs, {String? tag}) : _tag = tag;
Map<String, String> get declaredVariables =>
{for (final lib in enabledLibs) 'dart.library.$lib': 'true'};
@override
String toString() => 'Runtime($name)';
String get tag => _tag ?? 'runtime:$name';
static final _onAllPlatforms = {
'async',
'collection',
'convert',
'core',
'developer',
'math',
'typed_data',
// TODO(sigurdm): Remove if/when package:dart_internal goes away.
'_internal',
};
static final _onAllNative = {'ffi', 'io', 'isolate'};
static final _onAllWeb = {
'html',
'indexed_db',
'js',
'js_util',
'svg',
'web_audio',
'web_gl',
'web_sql',
};
static final _onNativeAot = {
..._onAllPlatforms,
..._onAllNative,
'cli',
'developer',
};
static final _onNativeJit = {
..._onNativeAot,
'mirrors',
'nativewrappers',
};
static final nativeJit =
Runtime('vm-native', _onNativeJit, tag: 'runtime:native-jit');
static final recognizedRuntimes = [
nativeAot,
nativeJit,
web,
];
static final nativeAot = Runtime('native-aot', {
..._onAllPlatforms,
..._onAllNative,
'cli',
'nativewrappers',
});
static final web = Runtime(
'js',
{
..._onAllPlatforms,
..._onAllWeb,
'html_common',
},
tag: 'runtime:web');
static final flutterNative = Runtime('flutter-native', {
..._onAllPlatforms,
..._onAllNative,
'ui',
});
static final flutterWeb = Runtime('flutter-web', {
..._onAllPlatforms,
..._onAllWeb,
'ui',
});
/// For platform detection we allow dart:ui.
static final broadWeb = Runtime('web', {
..._onAllPlatforms,
..._onAllWeb,
'ui',
});
/// For platform detection we allow dart:ui.
static final broadNative = Runtime('native', {
..._onAllPlatforms,
..._onAllNative,
'ui',
});
/// For sdk detection we allow everything except dart:ui.
static final broadDart = Runtime('dart', {..._onNativeJit, ..._onAllWeb});
/// For sdk detection we allow more or less everything.
static final broadFlutter = Runtime('flutter', {
..._onNativeAot,
..._onAllWeb,
'ui',
});
}
/// A platform where Dart and Flutter can be deployed.
class Platform {
final String name;
final Runtime runtime;
final String tag;
Platform(this.name, this.runtime, {required this.tag});
static final List<Platform> recognizedPlatforms = [
android,
ios,
Platform('Windows', Runtime.broadNative, tag: 'platform:windows'),
Platform('Linux', Runtime.broadNative, tag: 'platform:linux'),
Platform('macOS', Runtime.broadNative, tag: 'platform:macos'),
Platform('Web', Runtime.broadWeb, tag: 'platform:web'),
];
static final android = Platform(
'Android',
Runtime.broadNative,
tag: 'platform:android',
);
static final ios = Platform('iOS', Runtime.broadNative, tag: 'platform:ios');
@override
String toString() => 'FlutterPlatform($name)';
}
class Sdk {
final String name;
final String formattedName;
final List<String> allowedSdks;
final Runtime allowedRuntime;
Sdk(this.name, this.formattedName, this.allowedSdks, this.allowedRuntime);
String get tag => 'sdk:$name';
static Sdk dart = Sdk('dart', 'Dart', ['dart'], Runtime.broadDart);
static Sdk flutter =
Sdk('flutter', 'Flutter', ['dart', 'flutter'], Runtime.broadFlutter);
static List<Sdk> knownSdks = [dart, flutter];
}
| pana/lib/src/tag/_specs.dart/0 | {'file_path': 'pana/lib/src/tag/_specs.dart', 'repo_id': 'pana', 'token_count': 1438} |
// Copyright (c) 2021, 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.
import 'dart:convert';
import 'dart:io';
import 'package:pana/src/license_detection/license_detector.dart';
import 'package:test/test.dart';
void main() {
final file = File('test/license_test_assets/crc32_random.json');
var z = jsonDecode(file.readAsStringSync()) as Map<String, dynamic>;
/// The random vectors were generate using this python code and then
/// verified with [GO crc32 package][]
/// ```python
/// import zlib
/// import json
/// import string
/// import random
/// f = open('crc.json', 'w')
/// jsonJ = {}
/// for i in range(1000):
/// z = i % 20
/// if z < 1:
/// z = 1
/// res = ''.join(random.choices(string.printable, k=z))
/// crc = zlib.crc32(bytes(res, 'utf8'))
/// jsonJ[res] = crc
/// json.dump(jsonJ, f)
/// ```
/// [GO crc32 package] : https://golang.org/pkg/hash/crc32/
group('crc32 - random vectors', () {
z.forEach((key, value) {
test(key, () {
expect(crc32(utf8.encode(key)), value);
});
});
});
final allAscii = File('test/license_test_assets/crc32_ascii_values.json');
z = jsonDecode(allAscii.readAsStringSync()) as Map<String, dynamic>;
group('crc32 - all ascii value ', () {
z.forEach((key, value) {
test('Ascii value $key', () {
expect(crc32([int.parse(key)]), value);
});
});
});
}
| pana/test/crc32_test.dart/0 | {'file_path': 'pana/test/crc32_test.dart', 'repo_id': 'pana', 'token_count': 619} |
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'package:test_descriptor/test_descriptor.dart' as d;
/// Convenience for creating a descriptor of a package.
d.DirectoryDescriptor packageWithPathDeps(String name,
{String? sdkConstraint,
List<String> dependencies = const [],
List<d.Descriptor> lib = const [],
Map pubspecExtras = const {},
List<d.Descriptor> extraFiles = const []}) {
final pubspec = json.encode(
{
'name': name,
if (sdkConstraint != null) 'environment': {'sdk': sdkConstraint},
'dependencies': {
for (final dep in dependencies) dep: {'path': '../$dep'}
},
...pubspecExtras,
},
);
// TODO(sigurdm): write a package_config.json or use `dart pub get`.da
final packages = [
'$name:lib/',
for (final dep in dependencies) '$dep:../$dep/lib/'
].join('\n') +
'\n';
return d.dir(name, [
d.file('.packages', packages),
d.file('pubspec.yaml', pubspec),
d.dir('lib', lib),
...extraFiles,
]);
}
/// Convenience for creating a descriptor of a package.
d.DirectoryDescriptor package(String name,
{String? sdkConstraint,
Map<String, Object> dependencies = const {},
List<d.Descriptor> lib = const [],
Map pubspecExtras = const {},
List<d.Descriptor> extraFiles = const []}) {
final pubspec = json.encode(
{
'name': name,
if (sdkConstraint != null) 'environment': {'sdk': sdkConstraint},
'dependencies': dependencies,
...pubspecExtras,
},
);
return d.dir(name, [
d.file('pubspec.yaml', pubspec),
d.dir('lib', lib),
...extraFiles,
]);
}
| pana/test/package_descriptor.dart/0 | {'file_path': 'pana/test/package_descriptor.dart', 'repo_id': 'pana', 'token_count': 724} |
import 'package:flutter/material.dart';
class ExampleButtonNode extends StatelessWidget {
const ExampleButtonNode({
required this.title,
required this.onPressed,
});
final String title;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(
vertical: 20.0,
),
child: Column(
children: <Widget>[
Text(
title,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
fontSize: 21.0,
fontWeight: FontWeight.w600,
),
),
Container(
margin: const EdgeInsets.only(
top: 10.0,
),
child: ElevatedButton(
onPressed: onPressed,
child: const Text("Open example"),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.amber),
),
),
)
],
),
);
}
}
| photo_view/example/lib/screens/common/example_button.dart/0 | {'file_path': 'photo_view/example/lib/screens/common/example_button.dart', 'repo_id': 'photo_view', 'token_count': 549} |
import 'package:photobooth_ui/photobooth_ui.dart';
const googleIOExternalLink = 'https://events.google.com/io/';
const flutterDevExternalLink = 'https://flutter.dev';
const firebaseExternalLink = 'https://firebase.google.com';
const photoboothEmail = 'mailto:flutter-photo-booth@google.com';
const openSourceLink = 'https://github.com/flutter/photobooth';
Future<void> launchGoogleIOLink() => openLink(googleIOExternalLink);
Future<void> launchFlutterDevLink() => openLink(flutterDevExternalLink);
Future<void> launchFirebaseLink() => openLink(firebaseExternalLink);
Future<void> launchPhotoboothEmail() => openLink(photoboothEmail);
Future<void> launchOpenSourceLink() => openLink(openSourceLink);
| photobooth/lib/external_links/external_links.dart/0 | {'file_path': 'photobooth/lib/external_links/external_links.dart', 'repo_id': 'photobooth', 'token_count': 215} |
import 'dart:async';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const _videoConstraints = VideoConstraints(
facingMode: FacingMode(
type: CameraType.user,
constrain: Constrain.ideal,
),
width: VideoSize(ideal: 1920, maximum: 1920),
height: VideoSize(ideal: 1080, maximum: 1080),
);
class PhotoboothPage extends StatelessWidget {
const PhotoboothPage({super.key});
static Route<void> route() {
return AppPageRoute(builder: (_) => const PhotoboothPage());
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => PhotoboothBloc(),
child: Navigator(
onGenerateRoute: (_) => AppPageRoute(
builder: (_) => const PhotoboothView(),
),
),
);
}
}
class PhotoboothView extends StatefulWidget {
const PhotoboothView({super.key});
@override
State<PhotoboothView> createState() => _PhotoboothViewState();
}
class _PhotoboothViewState extends State<PhotoboothView> {
final _controller = CameraController(
options: const CameraOptions(
audio: AudioConstraints(),
video: _videoConstraints,
),
);
bool get _isCameraAvailable =>
_controller.value.status == CameraStatus.available;
Future<void> _play() async {
if (!_isCameraAvailable) return;
return _controller.play();
}
Future<void> _stop() async {
if (!_isCameraAvailable) return;
return _controller.stop();
}
@override
void initState() {
super.initState();
_initializeCameraController();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _initializeCameraController() async {
await _controller.initialize();
await _play();
}
Future<void> _onSnapPressed({required double aspectRatio}) async {
final navigator = Navigator.of(context);
final photoboothBloc = context.read<PhotoboothBloc>();
final picture = await _controller.takePicture();
photoboothBloc.add(PhotoCaptured(aspectRatio: aspectRatio, image: picture));
final stickersPage = StickersPage.route();
await _stop();
unawaited(navigator.pushReplacement(stickersPage));
}
@override
Widget build(BuildContext context) {
final orientation = MediaQuery.of(context).orientation;
final aspectRatio = orientation == Orientation.portrait
? PhotoboothAspectRatio.portrait
: PhotoboothAspectRatio.landscape;
return Scaffold(
body: _PhotoboothBackground(
aspectRatio: aspectRatio,
child: Camera(
controller: _controller,
placeholder: (_) => const SizedBox(),
preview: (context, preview) => PhotoboothPreview(
preview: preview,
onSnapPressed: () => _onSnapPressed(aspectRatio: aspectRatio),
),
error: (context, error) => PhotoboothError(error: error),
),
),
);
}
}
class _PhotoboothBackground extends StatelessWidget {
const _PhotoboothBackground({
required this.aspectRatio,
required this.child,
});
final double aspectRatio;
final Widget child;
@override
Widget build(BuildContext context) {
return Stack(
children: [
const PhotoboothBackground(),
Center(
child: AspectRatio(
aspectRatio: aspectRatio,
child: ColoredBox(
color: PhotoboothColors.black,
child: child,
),
),
),
],
);
}
}
| photobooth/lib/photobooth/view/photobooth_page.dart/0 | {'file_path': 'photobooth/lib/photobooth/view/photobooth_page.dart', 'repo_id': 'photobooth', 'token_count': 1424} |
import 'dart:async';
import 'dart:typed_data';
import 'package:bloc/bloc.dart';
import 'package:camera/camera.dart';
import 'package:cross_file/cross_file.dart';
import 'package:equatable/equatable.dart';
import 'package:image_compositor/image_compositor.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:photos_repository/photos_repository.dart';
part 'share_event.dart';
part 'share_state.dart';
class ShareBloc extends Bloc<ShareEvent, ShareState> {
ShareBloc({
required PhotosRepository photosRepository,
required this.imageId,
required this.image,
required this.assets,
required this.aspectRatio,
required this.shareText,
bool isSharingEnabled = const bool.fromEnvironment('SHARING_ENABLED'),
}) : _photosRepository = photosRepository,
_isSharingEnabled = isSharingEnabled,
super(const ShareState()) {
on<ShareViewLoaded>(_onShareViewLoaded);
on<ShareTapped>(_onShareTapped);
on<_ShareCompositeSucceeded>(_onShareCompositeSucceeded);
on<_ShareCompositeFailed>(
(event, emit) => emit(
state.copyWith(
compositeStatus: ShareStatus.failure,
),
),
);
}
final PhotosRepository _photosRepository;
final String imageId;
final CameraImage image;
final List<PhotoAsset> assets;
final double aspectRatio;
final bool _isSharingEnabled;
final String shareText;
void _onShareViewLoaded(
ShareViewLoaded event,
Emitter<ShareState> emit,
) {
emit(state.copyWith(compositeStatus: ShareStatus.loading));
unawaited(
_composite().then(
(value) => add(_ShareCompositeSucceeded(bytes: value)),
onError: (_) => add(const _ShareCompositeFailed()),
),
);
}
Future<void> _onShareTapped(
ShareTapped event,
Emitter<ShareState> emit,
) async {
if (!_isSharingEnabled) return;
final shareUrl =
event is ShareOnTwitterTapped ? ShareUrl.twitter : ShareUrl.facebook;
emit(
state.copyWith(
uploadStatus: ShareStatus.initial,
isDownloadRequested: false,
isUploadRequested: true,
shareUrl: shareUrl,
),
);
if (state.compositeStatus.isLoading) return;
if (state.uploadStatus.isLoading) return;
if (state.uploadStatus.isSuccess) return;
if (state.compositeStatus.isFailure) {
emit(
state.copyWith(
compositeStatus: ShareStatus.loading,
uploadStatus: ShareStatus.initial,
isDownloadRequested: false,
isUploadRequested: true,
shareUrl: shareUrl,
),
);
unawaited(
_composite().then(
(value) => add(_ShareCompositeSucceeded(bytes: value)),
onError: (_) => add(const _ShareCompositeFailed()),
),
);
} else if (state.compositeStatus.isSuccess) {
emit(
state.copyWith(
uploadStatus: ShareStatus.loading,
isDownloadRequested: false,
isUploadRequested: true,
shareUrl: shareUrl,
),
);
try {
final shareUrls = await _photosRepository.sharePhoto(
fileName: _getPhotoFileName(imageId),
data: state.bytes!,
shareText: shareText,
);
emit(
state.copyWith(
uploadStatus: ShareStatus.success,
isDownloadRequested: false,
isUploadRequested: true,
file: state.file,
bytes: state.bytes,
explicitShareUrl: shareUrls.explicitShareUrl,
facebookShareUrl: shareUrls.facebookShareUrl,
twitterShareUrl: shareUrls.twitterShareUrl,
shareUrl: shareUrl,
),
);
} catch (_) {
emit(
state.copyWith(
uploadStatus: ShareStatus.failure,
isDownloadRequested: false,
shareUrl: shareUrl,
),
);
}
}
}
Future<void> _onShareCompositeSucceeded(
_ShareCompositeSucceeded event,
Emitter<ShareState> emit,
) async {
final file = XFile.fromData(
event.bytes,
mimeType: 'image/png',
name: _getPhotoFileName(imageId),
);
final bytes = event.bytes;
emit(
state.copyWith(
compositeStatus: ShareStatus.success,
bytes: bytes,
file: file,
),
);
if (state.isUploadRequested) {
emit(
state.copyWith(
uploadStatus: ShareStatus.loading,
bytes: bytes,
file: file,
isDownloadRequested: false,
isUploadRequested: true,
),
);
try {
final shareUrls = await _photosRepository.sharePhoto(
fileName: _getPhotoFileName(imageId),
data: event.bytes,
shareText: shareText,
);
emit(
state.copyWith(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.success,
isDownloadRequested: false,
isUploadRequested: true,
bytes: bytes,
file: file,
explicitShareUrl: shareUrls.explicitShareUrl,
facebookShareUrl: shareUrls.facebookShareUrl,
twitterShareUrl: shareUrls.twitterShareUrl,
),
);
} catch (_) {
emit(
state.copyWith(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.failure,
bytes: bytes,
file: file,
isDownloadRequested: false,
),
);
}
}
}
Future<Uint8List> _composite() async {
final composite = await _photosRepository.composite(
aspectRatio: aspectRatio,
data: image.data,
width: image.width,
height: image.height,
layers: [
...assets.map(
(l) => CompositeLayer(
angle: l.angle,
assetPath: 'assets/${l.asset.path}',
constraints: Vector2D(l.constraint.width, l.constraint.height),
position: Vector2D(l.position.dx, l.position.dy),
size: Vector2D(l.size.width, l.size.height),
),
)
],
);
return Uint8List.fromList(composite);
}
String _getPhotoFileName(String photoName) => '$photoName.png';
}
| photobooth/lib/share/bloc/share_bloc.dart/0 | {'file_path': 'photobooth/lib/share/bloc/share_bloc.dart', 'repo_id': 'photobooth', 'token_count': 2845} |
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:io_photobooth/external_links/external_links.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class ShareSuccessCaption extends StatelessWidget {
const ShareSuccessCaption({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return SelectableText.rich(
TextSpan(
style: theme.textTheme.bodySmall?.copyWith(
color: PhotoboothColors.white,
),
children: <TextSpan>[
TextSpan(text: l10n.sharePageSuccessCaption1),
TextSpan(
text: l10n.sharePageSuccessCaption2,
recognizer: TapGestureRecognizer()..onTap = launchPhotoboothEmail,
style: const TextStyle(
decoration: TextDecoration.underline,
),
),
TextSpan(text: l10n.sharePageSuccessCaption3),
],
),
textAlign: TextAlign.center,
);
}
}
| photobooth/lib/share/widgets/share_caption.dart/0 | {'file_path': 'photobooth/lib/share/widgets/share_caption.dart', 'repo_id': 'photobooth', 'token_count': 479} |
export 'clear_stickers_button_layer.dart';
export 'clear_stickers_cancel_button.dart';
export 'clear_stickers_confirm_button.dart';
export 'clear_stickers_dialog.dart';
| photobooth/lib/stickers/widgets/clear_stickers/clear_stickers.dart/0 | {'file_path': 'photobooth/lib/stickers/widgets/clear_stickers/clear_stickers.dart', 'repo_id': 'photobooth', 'token_count': 61} |
name: analytics
description: A Flutter package which adds analytics support
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
very_good_analysis: ^4.0.0+1
| photobooth/packages/analytics/pubspec.yaml/0 | {'file_path': 'photobooth/packages/analytics/pubspec.yaml', 'repo_id': 'photobooth', 'token_count': 108} |
import 'package:camera_platform_interface/src/platform_interface/camera_platform.dart';
import 'package:flutter/foundation.dart';
class CameraOptions {
const CameraOptions({
AudioConstraints? audio,
VideoConstraints? video,
}) : audio = audio ?? const AudioConstraints(),
video = video ?? const VideoConstraints();
final AudioConstraints audio;
final VideoConstraints video;
Future<Map<String, dynamic>> toJson() async {
final videoConstraints = await video.toJson();
return {'audio': audio.toJson(), 'video': videoConstraints};
}
}
enum CameraType { rear, user }
enum Constrain { exact, ideal }
class FacingMode {
const FacingMode({this.constrain, this.type});
final Constrain? constrain;
final CameraType? type;
Object? toJson() {
if (constrain == null) {
return type != null ? describeEnum(type!) : null;
}
return {
describeEnum(constrain!): describeEnum(type!),
};
}
}
class AudioConstraints {
const AudioConstraints({this.enabled = false});
final bool enabled;
Object toJson() => enabled;
}
class VideoConstraints {
const VideoConstraints({
this.enabled = true,
this.facingMode,
this.width,
this.height,
this.deviceId,
});
static const String defaultDeviceId = 'default';
final bool enabled;
final FacingMode? facingMode;
final VideoSize? width;
final VideoSize? height;
final String? deviceId;
Future<Object> toJson() async {
if (!enabled) return false;
final json = <String, dynamic>{};
if (width != null) json['width'] = width!.toJson();
if (height != null) json['height'] = height!.toJson();
if (facingMode != null) json['facingMode'] = facingMode!.toJson();
if (deviceId == defaultDeviceId) {
json['deviceId'] = await CameraPlatform.instance.getDefaultDeviceId();
} else if (deviceId != null) {
json['deviceId'] = deviceId;
}
return json;
}
}
class VideoSize {
const VideoSize({this.minimum, this.ideal, this.maximum});
final int? minimum;
final int? ideal;
final int? maximum;
Object toJson() {
final json = <String, dynamic>{};
if (ideal != null) json['ideal'] = ideal;
if (minimum != null) json['min'] = minimum;
if (maximum != null) json['max'] = maximum;
return json;
}
}
| photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_options.dart/0 | {'file_path': 'photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_options.dart', 'repo_id': 'photobooth', 'token_count': 804} |
import 'dart:async';
import 'dart:convert';
import 'package:image_compositor/image_compositor.dart';
import 'package:image_compositor/src/image_loader.dart';
import 'package:image_compositor/src/offscreen_canvas.dart';
/// {@macro image_compositor}
class ImageCompositor {
/// {@macro image_compositor}
ImageCompositor();
/// Composites the [data] and [layers]
/// and returns a byte array with the provided [aspectRatio].
Future<List<int>> composite({
required String data,
required int width,
required int height,
required List<dynamic> layers,
required double aspectRatio,
}) {
return _OffscreenCompositor(data, width, height, layers, aspectRatio)
.composite();
}
}
class _OffscreenCompositor {
const _OffscreenCompositor(
this.data,
this.width,
this.height,
this.rawLayers,
this.targetAspectRatio,
);
final String data;
final int width;
final int height;
final List<dynamic> rawLayers;
final double targetAspectRatio;
/// Left, Top, Right border size.
static const _frameBorderSize = 15;
Future<List<int>> composite() async {
final layers =
rawLayers.map((l) => CompositeLayer.fromJson(l as Map)).toList();
final imageFutures = <Future<HtmlImage>>[];
/// Load assets in parallel.
final imageFuture = HtmlImageLoader(data).loadImage();
for (var layerIndex = 0; layerIndex < layers.length; layerIndex++) {
final imageFuture =
HtmlImageLoader(layers[layerIndex].assetPath).loadImage();
imageFutures.add(imageFuture);
}
/// Load framed image.
await Future.wait(imageFutures);
final image = await imageFuture;
/// Prepare image elements.
final frameAssetPath = targetAspectRatio < 1
? 'assets/assets/images/photo_frame_mobile_download.png'
: 'assets/assets/images/photo_frame_download.png';
final frameImage = await HtmlImageLoader(frameAssetPath).loadImage();
/// Compute target coordinates and target image size from assets.
final targetWidth = frameImage.width;
final targetHeight = frameImage.height;
/// We will have to create a clipping rectangle within frame and compute
/// videoRect that will correct the aspectratio and crop the image
/// correctly.
final inputVideoAspectRatio = width / height;
var croppedWidth = width.toDouble();
var croppedHeight = height.toDouble();
// Amount to shift drawing so that image gets cropped.
var imageCropOffsetX = 0;
var imageCropOffsetY = 0;
if (inputVideoAspectRatio > targetAspectRatio) {
// Crop left and right of video
croppedWidth = height * targetAspectRatio;
imageCropOffsetX = (croppedWidth - width) ~/ 2;
} else {
// Crop top and bottom of video
croppedHeight = width / targetAspectRatio;
imageCropOffsetY = (croppedHeight - height) ~/ 2;
}
const insideFrameX = _frameBorderSize;
const insideFrameY = _frameBorderSize;
final insideFrameWidth = frameImage.width - (2 * _frameBorderSize);
final insideFrameHeight = insideFrameWidth ~/ targetAspectRatio;
/// Render images to offscreen canvas.
final canvas = OffScreenCanvas(targetWidth, targetHeight)
/// Draw frame to cover full cropped area.
..drawImage(frameImage.imageElement, 0, 0, targetWidth, targetHeight)
/// Clip to frame interior.
..clipRect(
insideFrameX,
insideFrameY,
insideFrameWidth,
insideFrameHeight,
);
/// Scale the image so the cropped portion will cover the inside of
/// the frame.
final imageScaleFactor = (inputVideoAspectRatio > targetAspectRatio)
? insideFrameHeight / image.height
: insideFrameWidth / image.width;
final videoImageX =
insideFrameX + (imageCropOffsetX * imageScaleFactor).toInt();
final videoImageY =
insideFrameY + (imageCropOffsetY * imageScaleFactor).toInt();
final videoImageWidth = (image.width * imageScaleFactor).toInt();
final videoImageHeight = (image.height * imageScaleFactor).toInt();
canvas.drawImage(
image.imageElement,
videoImageX,
videoImageY,
videoImageWidth,
videoImageHeight,
);
for (var layerIndex = 0; layerIndex < layers.length; layerIndex++) {
final layer = layers[layerIndex];
final asset = await imageFutures[layerIndex];
/// Normalize coordinates to 0..1 based on original video image size.
/// then scale to target.
final assetDxPercent = layer.position.x / layer.constraints.x;
final assetDyPercent = layer.position.y / layer.constraints.y;
final assetWidthPercent = layer.size.x / layer.constraints.x;
final assetDx = assetDxPercent * insideFrameWidth;
final assetDy = assetDyPercent * insideFrameHeight;
final assetWidth = assetWidthPercent * insideFrameWidth;
/// Keep aspect ratio of asset since it is centered in layer.
final assetHeight = assetWidth * asset.height / asset.width;
canvas
..save()
..translate(insideFrameX + assetDx, insideFrameY + assetDy)
..translate(assetWidth / 2, assetHeight / 2)
..rotate(layer.angle)
..translate(-assetWidth / 2, -assetHeight / 2)
..drawImage(
asset.imageElement,
0,
0,
assetWidth.toInt(),
assetHeight.toInt(),
)
..restore();
}
/// To data url will convert canvas contents to 64bit encoded PNG.
final dataUrl = await canvas.toDataUrl();
return base64.decode(dataUrl.split(',')[1]);
}
}
| photobooth/packages/image_compositor/lib/src/web.dart/0 | {'file_path': 'photobooth/packages/image_compositor/lib/src/web.dart', 'repo_id': 'photobooth', 'token_count': 2015} |
export 'links_helper.dart';
export 'modal_helper.dart';
| photobooth/packages/photobooth_ui/lib/src/helpers/helpers.dart/0 | {'file_path': 'photobooth/packages/photobooth_ui/lib/src/helpers/helpers.dart', 'repo_id': 'photobooth', 'token_count': 23} |
const transparentImage = <int>[
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A,
0x00,
0x00,
0x00,
0x0D,
0x49,
0x48,
0x44,
0x52,
0x00,
0x00,
0x00,
0x01,
0x00,
0x00,
0x00,
0x01,
0x08,
0x06,
0x00,
0x00,
0x00,
0x1F,
0x15,
0xC4,
0x89,
0x00,
0x00,
0x00,
0x0A,
0x49,
0x44,
0x41,
0x54,
0x78,
0x9C,
0x63,
0x00,
0x01,
0x00,
0x00,
0x05,
0x00,
0x01,
0x0D,
0x0A,
0x2D,
0xB4,
0x00,
0x00,
0x00,
0x00,
0x49,
0x45,
0x4E,
0x44,
0xAE,
];
| photobooth/packages/photobooth_ui/test/helpers/constants.dart/0 | {'file_path': 'photobooth/packages/photobooth_ui/test/helpers/constants.dart', 'repo_id': 'photobooth', 'token_count': 409} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('AppPageView', () {
const footerKey = Key('footer');
const bodyKey = Key('body');
const backgroundKey = Key('background');
const firstOverlayKey = Key('firstOverlay');
const secondOverlayKey = Key('secondOverlayKey');
testWidgets('renders body', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
),
),
);
expect(find.byKey(bodyKey), findsOneWidget);
});
testWidgets('renders footer', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
),
),
);
expect(find.byKey(footerKey), findsOneWidget);
});
testWidgets('renders background', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
background: Container(key: backgroundKey),
),
),
);
expect(find.byKey(backgroundKey), findsOneWidget);
});
testWidgets('renders overlays', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
background: Container(key: backgroundKey),
overlays: [
Container(key: firstOverlayKey),
Container(key: secondOverlayKey),
],
),
),
);
expect(find.byKey(firstOverlayKey), findsOneWidget);
expect(find.byKey(secondOverlayKey), findsOneWidget);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/app_page_view_test.dart/0 | {'file_path': 'photobooth/packages/photobooth_ui/test/src/widgets/app_page_view_test.dart', 'repo_id': 'photobooth', 'token_count': 1106} |
import 'package:authentication_repository/authentication_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/app/app.dart';
import 'package:io_photobooth/landing/landing.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:photos_repository/photos_repository.dart';
import 'helpers/helpers.dart';
class MockAuthenticationRepository extends Mock
implements AuthenticationRepository {}
class MockPhotosRepository extends Mock implements PhotosRepository {}
void main() {
group('App', () {
testWidgets('uses default theme on large devices', (tester) async {
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 1000));
await tester.pumpWidget(
App(
authenticationRepository: MockAuthenticationRepository(),
photosRepository: MockPhotosRepository(),
),
);
final materialApp = tester.widget<MaterialApp>(find.byType(MaterialApp));
expect(
materialApp.theme!.textTheme.displayLarge!.fontSize,
equals(PhotoboothTheme.standard.textTheme.displayLarge!.fontSize),
);
});
testWidgets('uses small theme on small devices', (tester) async {
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 500));
await tester.pumpWidget(
App(
authenticationRepository: MockAuthenticationRepository(),
photosRepository: MockPhotosRepository(),
),
);
final materialApp = tester.widget<MaterialApp>(find.byType(MaterialApp));
expect(
materialApp.theme!.textTheme.displayLarge!.fontSize,
equals(PhotoboothTheme.small.textTheme.displayLarge!.fontSize),
);
});
testWidgets('renders LandingPage', (tester) async {
await tester.pumpWidget(
App(
authenticationRepository: MockAuthenticationRepository(),
photosRepository: MockPhotosRepository(),
),
);
expect(find.byType(LandingPage), findsOneWidget);
});
});
}
| photobooth/test/app_test.dart/0 | {'file_path': 'photobooth/test/app_test.dart', 'repo_id': 'photobooth', 'token_count': 779} |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/assets.g.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class FakePhotoboothEvent extends Fake implements PhotoboothEvent {}
class FakePhotoboothState extends Fake implements PhotoboothState {}
class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState>
implements PhotoboothBloc {}
void main() {
const width = 1;
const height = 1;
const data = '';
const image = CameraImage(width: width, height: height, data: data);
late PhotoboothBloc photoboothBloc;
group('StickersLayer', () {
setUpAll(() {
registerFallbackValue(FakePhotoboothEvent());
registerFallbackValue(FakePhotoboothState());
});
setUp(() {
photoboothBloc = MockPhotoboothBloc();
});
testWidgets('displays selected sticker assets', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: const [PhotoAsset(id: '0', asset: Assets.android)],
stickers: [PhotoAsset(id: '0', asset: Assets.props.first)],
image: image,
),
);
await tester.pumpApp(
const StickersLayer(),
photoboothBloc: photoboothBloc,
);
expect(
find.byKey(const Key('stickersLayer_01_google_v1_0_positioned')),
findsOneWidget,
);
});
testWidgets('displays multiple selected sticker assets', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: const [PhotoAsset(id: '0', asset: Assets.android)],
stickers: [
PhotoAsset(id: '0', asset: Assets.props.first),
PhotoAsset(id: '1', asset: Assets.props.first),
PhotoAsset(id: '2', asset: Assets.props.last),
],
image: image,
),
);
await tester.pumpApp(
const StickersLayer(),
photoboothBloc: photoboothBloc,
);
expect(
find.byKey(const Key('stickersLayer_01_google_v1_0_positioned')),
findsOneWidget,
);
expect(
find.byKey(const Key('stickersLayer_01_google_v1_1_positioned')),
findsOneWidget,
);
expect(
find.byKey(const Key('stickersLayer_25_shapes_v1_2_positioned')),
findsOneWidget,
);
});
});
}
| photobooth/test/photobooth/widgets/stickers_layer_test.dart/0 | {'file_path': 'photobooth/test/photobooth/widgets/stickers_layer_test.dart', 'repo_id': 'photobooth', 'token_count': 1101} |
// ignore_for_file: prefer_const_constructors
import 'dart:typed_data';
import 'package:cross_file/cross_file.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class MockPhotoAsset extends Mock implements PhotoAsset {}
void main() {
const shareUrl = 'http://share-url.com';
final bytes = Uint8List.fromList([]);
late ShareBloc shareBloc;
setUpAll(() {
registerFallbackValue(FakeShareEvent());
registerFallbackValue(FakeShareState());
});
setUp(() {
shareBloc = MockShareBloc();
when(() => shareBloc.state).thenReturn(ShareState());
});
group('TwitterButton', () {
testWidgets('pops when tapped', (tester) async {
await tester.pumpApp(TwitterButton(), shareBloc: shareBloc);
await tester.tap(find.byType(TwitterButton));
await tester.pumpAndSettle();
expect(find.byType(TwitterButton), findsNothing);
});
testWidgets('adds ShareOnTwitterTapped event when tapped', (tester) async {
await tester.pumpApp(TwitterButton(), shareBloc: shareBloc);
await tester.tap(find.byType(TwitterButton));
await tester.pumpAndSettle();
verify(() => shareBloc.add(ShareOnTwitterTapped())).called(1);
});
testWidgets(
'does not add ShareOnTwitterTapped event '
'when tapped but state is upload success', (tester) async {
when(() => shareBloc.state).thenReturn(
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.success,
file: XFile.fromData(bytes),
bytes: bytes,
twitterShareUrl: shareUrl,
facebookShareUrl: shareUrl,
),
);
await tester.pumpApp(TwitterButton(), shareBloc: shareBloc);
await tester.tap(find.byType(TwitterButton));
await tester.pumpAndSettle();
verifyNever(() => shareBloc.add(any()));
});
});
}
| photobooth/test/share/widgets/twitter_button_test.dart/0 | {'file_path': 'photobooth/test/share/widgets/twitter_button_test.dart', 'repo_id': 'photobooth', 'token_count': 794} |
name: leaderboard_repository
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
push:
paths:
- "packages/leaderboard_repository/**"
- ".github/workflows/leaderboard_repository.yaml"
pull_request:
paths:
- "packages/leaderboard_repository/**"
- ".github/workflows/leaderboard_repository.yaml"
jobs:
build:
uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1
with:
working_directory: packages/leaderboard_repository
| pinball/.github/workflows/leaderboard_repository.yaml/0 | {'file_path': 'pinball/.github/workflows/leaderboard_repository.yaml', 'repo_id': 'pinball', 'token_count': 213} |
import 'package:flame/components.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template bonus_ball_spawning_behavior}
/// After a duration, spawns a bonus ball from the [DinoWalls] and boosts it
/// into the middle of the board.
/// {@endtemplate}
class BonusBallSpawningBehavior extends TimerComponent with HasGameRef {
/// {@macro bonus_ball_spawning_behavior}
BonusBallSpawningBehavior()
: super(
period: 5,
removeOnFinish: true,
);
@override
void onTick() {
final characterTheme = readBloc<CharacterThemeCubit, CharacterThemeState>()
.state
.characterTheme;
gameRef.descendants().whereType<ZCanvasComponent>().single.add(
Ball(assetPath: characterTheme.ball.keyName)
..add(BallImpulsingBehavior(impulse: Vector2(-40, 0)))
..initialPosition = Vector2(29.2, -24.5)
..zIndex = ZIndexes.ballOnBoard,
);
}
}
| pinball/lib/game/behaviors/bonus_ball_spawning_behavior.dart/0 | {'file_path': 'pinball/lib/game/behaviors/bonus_ball_spawning_behavior.dart', 'repo_id': 'pinball', 'token_count': 414} |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Increases the multiplier when a [Ball] is shot 5 times into the
/// [SpaceshipRamp].
class RampMultiplierBehavior extends Component
with FlameBlocListenable<SpaceshipRampCubit, SpaceshipRampState> {
@override
bool listenWhen(
SpaceshipRampState previousState,
SpaceshipRampState newState,
) {
final hitsIncreased = previousState.hits < newState.hits;
final achievedFiveShots = newState.hits % 5 == 0;
final notMaxMultiplier =
!readBloc<GameBloc, GameState>().state.isMaxMultiplier;
return hitsIncreased & achievedFiveShots && notMaxMultiplier;
}
@override
void onNewState(SpaceshipRampState state) {
readBloc<GameBloc, GameState>().add(const MultiplierIncreased());
}
}
| pinball/lib/game/components/android_acres/behaviors/ramp_multiplier_behavior.dart/0 | {'file_path': 'pinball/lib/game/components/android_acres/behaviors/ramp_multiplier_behavior.dart', 'repo_id': 'pinball', 'token_count': 337} |
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/input.dart';
import 'package:flutter/material.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_ui/pinball_ui.dart';
import 'package:share_repository/share_repository.dart';
/// Signature for the callback called when the user tries to share their score
/// on the [ShareDisplay].
typedef OnSocialShareTap = void Function(SharePlatform);
final _descriptionTextPaint = TextPaint(
style: const TextStyle(
fontSize: 1.6,
color: PinballColors.white,
fontFamily: PinballFonts.pixeloidSans,
),
);
/// {@template share_display}
/// Display that allows users to share their score to social networks.
/// {@endtemplate}
class ShareDisplay extends Component with HasGameRef {
/// {@macro share_display}
ShareDisplay({
OnSocialShareTap? onShare,
}) : super(
children: [
_ShareInstructionsComponent(
onShare: onShare,
),
],
);
}
class _ShareInstructionsComponent extends PositionComponent with HasGameRef {
_ShareInstructionsComponent({
OnSocialShareTap? onShare,
}) : super(
anchor: Anchor.center,
position: Vector2(0, -25),
children: [
_DescriptionComponent(),
_SocialNetworksComponent(
onShare: onShare,
),
],
);
}
class _DescriptionComponent extends PositionComponent with HasGameRef {
_DescriptionComponent()
: super(
anchor: Anchor.center,
position: Vector2.zero(),
children: [
_LetEveryoneTextComponent(),
_SharingYourScoreTextComponent(),
_SocialMediaTextComponent(),
],
);
}
class _LetEveryoneTextComponent extends TextComponent with HasGameRef {
_LetEveryoneTextComponent()
: super(
anchor: Anchor.center,
position: Vector2.zero(),
textRenderer: _descriptionTextPaint,
);
@override
Future<void> onLoad() async {
await super.onLoad();
text = readProvider<AppLocalizations>().letEveryone;
}
}
class _SharingYourScoreTextComponent extends TextComponent with HasGameRef {
_SharingYourScoreTextComponent()
: super(
anchor: Anchor.center,
position: Vector2(0, 2.5),
textRenderer: _descriptionTextPaint,
);
@override
Future<void> onLoad() async {
await super.onLoad();
text = readProvider<AppLocalizations>().bySharingYourScore;
}
}
class _SocialMediaTextComponent extends TextComponent with HasGameRef {
_SocialMediaTextComponent()
: super(
anchor: Anchor.center,
position: Vector2(0, 5),
textRenderer: _descriptionTextPaint,
);
@override
Future<void> onLoad() async {
await super.onLoad();
text = readProvider<AppLocalizations>().socialMediaAccount;
}
}
class _SocialNetworksComponent extends PositionComponent with HasGameRef {
_SocialNetworksComponent({
OnSocialShareTap? onShare,
}) : super(
anchor: Anchor.center,
position: Vector2(0, 12),
children: [
FacebookButtonComponent(onTap: onShare),
TwitterButtonComponent(onTap: onShare),
],
);
}
/// {@template facebook_button_component}
/// Button for sharing on Facebook.
/// {@endtemplate}
class FacebookButtonComponent extends SpriteComponent
with HasGameRef, Tappable {
/// {@macro facebook_button_component}
FacebookButtonComponent({
OnSocialShareTap? onTap,
}) : _onTap = onTap,
super(
anchor: Anchor.center,
position: Vector2(-5, 0),
);
final OnSocialShareTap? _onTap;
@override
bool onTapUp(TapUpInfo info) {
_onTap?.call(SharePlatform.facebook);
return true;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(Assets.images.backbox.button.facebook.keyName),
);
this.sprite = sprite;
size = sprite.originalSize / 25;
}
}
/// {@template twitter_button_component}
/// Button for sharing on Twitter.
/// {@endtemplate}
class TwitterButtonComponent extends SpriteComponent with HasGameRef, Tappable {
/// {@macro twitter_button_component}
TwitterButtonComponent({
OnSocialShareTap? onTap,
}) : _onTap = onTap,
super(
anchor: Anchor.center,
position: Vector2(5, 0),
);
final OnSocialShareTap? _onTap;
@override
bool onTapUp(TapUpInfo info) {
_onTap?.call(SharePlatform.twitter);
return true;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(Assets.images.backbox.button.twitter.keyName),
);
this.sprite = sprite;
size = sprite.originalSize / 25;
}
}
| pinball/lib/game/components/backbox/displays/share_display.dart/0 | {'file_path': 'pinball/lib/game/components/backbox/displays/share_display.dart', 'repo_id': 'pinball', 'token_count': 1946} |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets;
/// {@template launcher}
/// Channel on the right side of the board containing the [LaunchRamp],
/// [Plunger], and [RocketSpriteComponent].
/// {@endtemplate}
class Launcher extends Component {
/// {@macro launcher}
Launcher()
: super(
children: [
LaunchRamp(),
Flapper(),
Plunger()..initialPosition = Vector2(41, 43.7),
RocketSpriteComponent()..position = Vector2(42.8, 62.3),
],
);
}
| pinball/lib/game/components/launcher.dart/0 | {'file_path': 'pinball/lib/game/components/launcher.dart', 'repo_id': 'pinball', 'token_count': 236} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/gen/gen.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// {@template game_hud}
/// Overlay on the [PinballGame].
///
/// Displays the current [GameState.displayScore], [GameState.rounds] and
/// animates when the player gets a [GameBonus].
/// {@endtemplate}
class GameHud extends StatefulWidget {
/// {@macro game_hud}
const GameHud({Key? key}) : super(key: key);
@override
State<GameHud> createState() => _GameHudState();
}
class _GameHudState extends State<GameHud> {
bool showAnimation = false;
/// Ratio from sprite frame (width 500, height 144) w / h = ratio
static const _ratio = 3.47;
@override
Widget build(BuildContext context) {
final isGameOver =
context.select((GameBloc bloc) => bloc.state.status.isGameOver);
final height = _calculateHeight(context);
return _ScoreViewDecoration(
child: SizedBox(
height: height,
width: height * _ratio,
child: BlocListener<GameBloc, GameState>(
listenWhen: (previous, current) =>
previous.bonusHistory.length != current.bonusHistory.length,
listener: (_, __) => setState(() => showAnimation = true),
child: AnimatedSwitcher(
duration: kThemeAnimationDuration,
child: showAnimation && !isGameOver
? _AnimationView(
onComplete: () {
if (mounted) {
setState(() => showAnimation = false);
}
},
)
: const ScoreView(),
),
),
),
);
}
double _calculateHeight(BuildContext context) {
final height = MediaQuery.of(context).size.height * 0.09;
if (height > 90) {
return 90;
} else if (height < 60) {
return 60;
} else {
return height;
}
}
}
class _ScoreViewDecoration extends StatelessWidget {
const _ScoreViewDecoration({
Key? key,
required this.child,
}) : super(key: key);
final Widget child;
@override
Widget build(BuildContext context) {
const radius = BorderRadius.all(Radius.circular(12));
const borderWidth = 5.0;
return DecoratedBox(
decoration: BoxDecoration(
borderRadius: radius,
border: Border.all(
color: PinballColors.white,
width: borderWidth,
),
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
Assets.images.score.miniScoreBackground.path,
),
),
),
child: Padding(
padding: const EdgeInsets.all(borderWidth - 1),
child: ClipRRect(
borderRadius: radius,
child: child,
),
),
);
}
}
class _AnimationView extends StatelessWidget {
const _AnimationView({
Key? key,
required this.onComplete,
}) : super(key: key);
final VoidCallback onComplete;
@override
Widget build(BuildContext context) {
final lastBonus = context.select(
(GameBloc bloc) => bloc.state.bonusHistory.last,
);
switch (lastBonus) {
case GameBonus.dashNest:
return BonusAnimation.dashNest(onCompleted: onComplete);
case GameBonus.sparkyTurboCharge:
return BonusAnimation.sparkyTurboCharge(onCompleted: onComplete);
case GameBonus.dinoChomp:
return BonusAnimation.dinoChomp(onCompleted: onComplete);
case GameBonus.googleWord:
return BonusAnimation.googleWord(onCompleted: onComplete);
case GameBonus.androidSpaceship:
return BonusAnimation.androidSpaceship(onCompleted: onComplete);
}
}
}
| pinball/lib/game/view/widgets/game_hud.dart/0 | {'file_path': 'pinball/lib/game/view/widgets/game_hud.dart', 'repo_id': 'pinball', 'token_count': 1584} |
import 'package:authentication_repository/authentication_repository.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/app/app.dart';
import 'package:pinball/bootstrap.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:platform_helper/platform_helper.dart';
import 'package:share_repository/share_repository.dart';
void main() {
bootstrap((firestore, firebaseAuth) async {
final leaderboardRepository = LeaderboardRepository(firestore);
const shareRepository =
ShareRepository(appUrl: ShareRepository.pinballGameUrl);
final authenticationRepository = AuthenticationRepository(firebaseAuth);
final pinballAudioPlayer = PinballAudioPlayer();
final platformHelper = PlatformHelper();
await Firebase.initializeApp();
await authenticationRepository.authenticateAnonymously();
return App(
authenticationRepository: authenticationRepository,
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
pinballAudioPlayer: pinballAudioPlayer,
platformHelper: platformHelper,
);
});
}
| pinball/lib/main.dart/0 | {'file_path': 'pinball/lib/main.dart', 'repo_id': 'pinball', 'token_count': 376} |
include: package:very_good_analysis/analysis_options.2.4.0.yaml | pinball/packages/authentication_repository/analysis_options.yaml/0 | {'file_path': 'pinball/packages/authentication_repository/analysis_options.yaml', 'repo_id': 'pinball', 'token_count': 22} |
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
/// {@template leaderboard_repository}
/// Repository to access leaderboard data in Firebase Cloud Firestore.
/// {@endtemplate}
class LeaderboardRepository {
/// {@macro leaderboard_repository}
const LeaderboardRepository(
FirebaseFirestore firebaseFirestore,
) : _firebaseFirestore = firebaseFirestore;
final FirebaseFirestore _firebaseFirestore;
static const _leaderboardLimit = 10;
static const _leaderboardCollectionName = 'leaderboard';
static const _scoreFieldName = 'score';
/// Acquires top 10 [LeaderboardEntryData]s.
Future<List<LeaderboardEntryData>> fetchTop10Leaderboard() async {
try {
final querySnapshot = await _firebaseFirestore
.collection(_leaderboardCollectionName)
.orderBy(_scoreFieldName, descending: true)
.limit(_leaderboardLimit)
.get();
final documents = querySnapshot.docs;
return documents.toLeaderboard();
} on LeaderboardDeserializationException {
rethrow;
} on Exception catch (error, stackTrace) {
throw FetchTop10LeaderboardException(error, stackTrace);
}
}
/// Adds player's score entry to the leaderboard if it is within the top-10
Future<void> addLeaderboardEntry(
LeaderboardEntryData entry,
) async {
final leaderboard = await _fetchLeaderboardSortedByScore();
if (leaderboard.length < 10) {
await _saveScore(entry);
} else {
final tenthPositionScore = leaderboard[9].score;
if (entry.score > tenthPositionScore) {
await _saveScore(entry);
}
}
}
Future<List<LeaderboardEntryData>> _fetchLeaderboardSortedByScore() async {
try {
final querySnapshot = await _firebaseFirestore
.collection(_leaderboardCollectionName)
.orderBy(_scoreFieldName, descending: true)
.get();
final documents = querySnapshot.docs;
return documents.toLeaderboard();
} on Exception catch (error, stackTrace) {
throw FetchLeaderboardException(error, stackTrace);
}
}
Future<void> _saveScore(LeaderboardEntryData entry) {
try {
return _firebaseFirestore
.collection(_leaderboardCollectionName)
.add(entry.toJson());
} on Exception catch (error, stackTrace) {
throw AddLeaderboardEntryException(error, stackTrace);
}
}
}
extension on List<QueryDocumentSnapshot> {
List<LeaderboardEntryData> toLeaderboard() {
final leaderboardEntries = <LeaderboardEntryData>[];
for (final document in this) {
final data = document.data() as Map<String, dynamic>?;
if (data != null) {
try {
leaderboardEntries.add(LeaderboardEntryData.fromJson(data));
} catch (error, stackTrace) {
throw LeaderboardDeserializationException(error, stackTrace);
}
}
}
return leaderboardEntries;
}
}
| pinball/packages/leaderboard_repository/lib/src/leaderboard_repository.dart/0 | {'file_path': 'pinball/packages/leaderboard_repository/lib/src/leaderboard_repository.dart', 'repo_id': 'pinball', 'token_count': 1063} |
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_bumper/behaviors/behaviors.dart';
import 'package:pinball_components/src/components/bumping_behavior.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'cubit/android_bumper_cubit.dart';
/// {@template android_bumper}
/// Bumper for area under the [AndroidSpaceship].
/// {@endtemplate}
class AndroidBumper extends BodyComponent with InitialPosition, ZIndex {
/// {@macro android_bumper}
AndroidBumper._({
required double majorRadius,
required double minorRadius,
required String litAssetPath,
required String dimmedAssetPath,
required Vector2 spritePosition,
Iterable<Component>? children,
required this.bloc,
}) : _majorRadius = majorRadius,
_minorRadius = minorRadius,
super(
renderBody: false,
children: [
AndroidBumperBallContactBehavior(),
AndroidBumperBlinkingBehavior(),
_AndroidBumperSpriteGroupComponent(
dimmedAssetPath: dimmedAssetPath,
litAssetPath: litAssetPath,
position: spritePosition,
state: bloc.state,
),
...?children,
],
) {
zIndex = ZIndexes.androidBumper;
}
/// {@macro android_bumper}
AndroidBumper.a({
Iterable<Component>? children,
}) : this._(
majorRadius: 3.52,
minorRadius: 2.97,
litAssetPath: Assets.images.android.bumper.a.lit.keyName,
dimmedAssetPath: Assets.images.android.bumper.a.dimmed.keyName,
spritePosition: Vector2(0, -0.1),
bloc: AndroidBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// {@macro android_bumper}
AndroidBumper.b({
Iterable<Component>? children,
}) : this._(
majorRadius: 3.19,
minorRadius: 2.79,
litAssetPath: Assets.images.android.bumper.b.lit.keyName,
dimmedAssetPath: Assets.images.android.bumper.b.dimmed.keyName,
spritePosition: Vector2(0, -0.1),
bloc: AndroidBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// {@macro android_bumper}
AndroidBumper.cow({
Iterable<Component>? children,
}) : this._(
majorRadius: 3.45,
minorRadius: 3.11,
litAssetPath: Assets.images.android.bumper.cow.lit.keyName,
dimmedAssetPath: Assets.images.android.bumper.cow.dimmed.keyName,
spritePosition: Vector2(0, -0.35),
bloc: AndroidBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// Creates an [AndroidBumper] without any children.
///
/// This can be used for testing [AndroidBumper]'s behaviors in isolation.
@visibleForTesting
AndroidBumper.test({
required this.bloc,
}) : _majorRadius = 3.52,
_minorRadius = 2.97;
final double _majorRadius;
final double _minorRadius;
final AndroidBumperCubit bloc;
@override
void onRemove() {
bloc.close();
super.onRemove();
}
@override
Body createBody() {
final shape = EllipseShape(
center: Vector2.zero(),
majorRadius: _majorRadius,
minorRadius: _minorRadius,
)..rotate(1.29);
final bodyDef = BodyDef(
position: initialPosition,
);
return world.createBody(bodyDef)..createFixtureFromShape(shape);
}
}
class _AndroidBumperSpriteGroupComponent
extends SpriteGroupComponent<AndroidBumperState>
with HasGameRef, ParentIsA<AndroidBumper> {
_AndroidBumperSpriteGroupComponent({
required String litAssetPath,
required String dimmedAssetPath,
required Vector2 position,
required AndroidBumperState state,
}) : _litAssetPath = litAssetPath,
_dimmedAssetPath = dimmedAssetPath,
super(
anchor: Anchor.center,
position: position,
current: state,
);
final String _litAssetPath;
final String _dimmedAssetPath;
@override
Future<void> onLoad() async {
await super.onLoad();
parent.bloc.stream.listen((state) => current = state);
final sprites = {
AndroidBumperState.lit: Sprite(
gameRef.images.fromCache(_litAssetPath),
),
AndroidBumperState.dimmed:
Sprite(gameRef.images.fromCache(_dimmedAssetPath)),
};
this.sprites = sprites;
size = sprites[current]!.originalSize / 10;
}
}
| pinball/packages/pinball_components/lib/src/components/android_bumper/android_bumper.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/android_bumper/android_bumper.dart', 'repo_id': 'pinball', 'token_count': 2010} |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Scales the ball's body and sprite according to its position on the board.
class BallScalingBehavior extends Component with ParentIsA<Ball> {
@override
void update(double dt) {
super.update(dt);
final boardHeight = BoardDimensions.bounds.height;
const maxShrinkValue = BoardDimensions.perspectiveShrinkFactor;
final standardizedYPosition = parent.body.position.y + (boardHeight / 2);
final scaleFactor = maxShrinkValue +
((standardizedYPosition / boardHeight) * (1 - maxShrinkValue));
parent.body.fixtures.first.shape.radius = (Ball.size.x / 2) * scaleFactor;
final ballSprite = parent.descendants().whereType<SpriteComponent>();
if (ballSprite.isNotEmpty) {
ballSprite.single.scale.setValues(
scaleFactor,
scaleFactor,
);
}
}
}
| pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_scaling_behavior.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_scaling_behavior.dart', 'repo_id': 'pinball', 'token_count': 339} |
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template chrome_dino_swivel_behavior}
/// Swivels the [ChromeDino] up and down periodically to match its animation
/// sequence.
/// {@endtemplate}
class ChromeDinoSwivelingBehavior extends TimerComponent
with ParentIsA<ChromeDino> {
/// {@macro chrome_dino_swivel_behavior}
ChromeDinoSwivelingBehavior()
: super(
period: 98 / 48,
repeat: true,
);
late final RevoluteJoint _joint;
@override
Future<void> onLoad() async {
final anchor = _ChromeDinoAnchor()
..initialPosition = parent.initialPosition + Vector2(9, -4);
await add(anchor);
final jointDef = _ChromeDinoAnchorRevoluteJointDef(
chromeDino: parent,
anchor: anchor,
);
_joint = RevoluteJoint(jointDef);
parent.world.createJoint(_joint);
}
@override
void update(double dt) {
super.update(dt);
final angle = _joint.jointAngle();
if (angle < _joint.upperLimit &&
angle > _joint.lowerLimit &&
parent.bloc.state.isMouthOpen) {
parent.bloc.onCloseMouth();
} else if ((angle >= _joint.upperLimit || angle <= _joint.lowerLimit) &&
!parent.bloc.state.isMouthOpen) {
parent.bloc.onOpenMouth();
}
}
@override
void onTick() {
super.onTick();
_joint.setMotorSpeed(-_joint.motorSpeed);
}
}
class _ChromeDinoAnchor extends JointAnchor
with ParentIsA<ChromeDinoSwivelingBehavior> {
@override
void onMount() {
super.onMount();
parent.parent.children
.whereType<SpriteAnimationComponent>()
.forEach((sprite) {
sprite.animation!.currentIndex = 45;
sprite.changeParent(this);
});
}
}
class _ChromeDinoAnchorRevoluteJointDef extends RevoluteJointDef {
_ChromeDinoAnchorRevoluteJointDef({
required ChromeDino chromeDino,
required _ChromeDinoAnchor anchor,
}) {
initialize(
chromeDino.body,
anchor.body,
chromeDino.body.position + anchor.body.position,
);
enableLimit = true;
lowerAngle = -ChromeDino.halfSweepingAngle;
upperAngle = ChromeDino.halfSweepingAngle;
enableMotor = true;
maxMotorTorque = chromeDino.body.mass * 255;
motorSpeed = 2;
}
}
| pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_swiveling_behavior.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_swiveling_behavior.dart', 'repo_id': 'pinball', 'token_count': 968} |
export 'flipper_jointing_behavior.dart';
export 'flipper_key_controlling_behavior.dart';
export 'flipper_moving_behavior.dart';
export 'flipper_noise_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/flipper/behaviors/behaviors.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/flipper/behaviors/behaviors.dart', 'repo_id': 'pinball', 'token_count': 58} |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
export 'behaviors/behaviors.dart';
export 'cubit/google_word_cubit.dart';
/// {@template google_word}
/// Loads all [GoogleLetter]s to compose a [GoogleWord].
/// {@endtemplate}
class GoogleWord extends PositionComponent {
/// {@macro google_word}
GoogleWord({
required Vector2 position,
}) : super(
position: position,
children: [
GoogleLetter(0)..position = Vector2(-13.1, 1.72),
GoogleLetter(1)..position = Vector2(-8.33, -0.75),
GoogleLetter(2)..position = Vector2(-2.88, -1.85),
GoogleLetter(3)..position = Vector2(2.88, -1.85),
GoogleLetter(4)..position = Vector2(8.33, -0.75),
GoogleLetter(5)..position = Vector2(13.1, 1.72),
],
);
}
| pinball/packages/pinball_components/lib/src/components/google_word/google_word.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/google_word/google_word.dart', 'repo_id': 'pinball', 'token_count': 378} |
part of 'multiball_cubit.dart';
enum MultiballLightState {
lit,
dimmed,
}
// Indicates if the blinking animation is running.
enum MultiballAnimationState {
idle,
blinking,
}
class MultiballState extends Equatable {
const MultiballState({
required this.lightState,
required this.animationState,
});
const MultiballState.initial()
: this(
lightState: MultiballLightState.dimmed,
animationState: MultiballAnimationState.idle,
);
final MultiballLightState lightState;
final MultiballAnimationState animationState;
MultiballState copyWith({
MultiballLightState? lightState,
MultiballAnimationState? animationState,
}) {
return MultiballState(
lightState: lightState ?? this.lightState,
animationState: animationState ?? this.animationState,
);
}
@override
List<Object> get props => [lightState, animationState];
}
| pinball/packages/pinball_components/lib/src/components/multiball/cubit/multiball_state.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/multiball/cubit/multiball_state.dart', 'repo_id': 'pinball', 'token_count': 317} |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Scales a [ScoreComponent] according to its position on the board.
class ScoreComponentScalingBehavior extends Component
with ParentIsA<SpriteComponent> {
@override
void update(double dt) {
super.update(dt);
final boardHeight = BoardDimensions.bounds.height;
const maxShrinkValue = 0.83;
final augmentedPosition = parent.position.y * 3;
final standardizedYPosition = augmentedPosition + (boardHeight / 2);
final scaleFactor = maxShrinkValue +
((standardizedYPosition / boardHeight) * (1 - maxShrinkValue));
parent.scale.setValues(
scaleFactor,
scaleFactor,
);
}
}
| pinball/packages/pinball_components/lib/src/components/score_component/behaviors/score_component_scaling_behavior.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/score_component/behaviors/score_component_scaling_behavior.dart', 'repo_id': 'pinball', 'token_count': 264} |
// ignore_for_file: comment_references
part of 'spaceship_ramp_cubit.dart';
class SpaceshipRampState extends Equatable {
const SpaceshipRampState({
required this.hits,
required this.lightState,
}) : assert(hits >= 0, "Hits can't be negative");
const SpaceshipRampState.initial()
: this(
hits: 0,
lightState: ArrowLightState.inactive,
);
final int hits;
final ArrowLightState lightState;
bool get arrowFullyLit => lightState == ArrowLightState.active5;
SpaceshipRampState copyWith({
int? hits,
ArrowLightState? lightState,
}) {
return SpaceshipRampState(
hits: hits ?? this.hits,
lightState: lightState ?? this.lightState,
);
}
@override
List<Object?> get props => [hits, lightState];
}
/// Indicates the state of the arrow on the [SpaceshipRamp].
enum ArrowLightState {
/// Arrow with no lights lit up.
inactive,
/// Arrow with 1 light lit up.
active1,
/// Arrow with 2 lights lit up.
active2,
/// Arrow with 3 lights lit up.
active3,
/// Arrow with 4 lights lit up.
active4,
/// Arrow with all 5 lights lit up.
active5,
}
| pinball/packages/pinball_components/lib/src/components/spaceship_ramp/cubit/spaceship_ramp_state.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/components/spaceship_ramp/cubit/spaceship_ramp_state.dart', 'repo_id': 'pinball', 'token_count': 414} |
import 'package:intl/intl.dart';
final _numberFormat = NumberFormat('#,###');
/// Adds score related extensions to int
extension ScoreX on int {
/// Formats this number as a score value
String formatScore() {
return _numberFormat.format(this);
}
}
| pinball/packages/pinball_components/lib/src/extensions/score.dart/0 | {'file_path': 'pinball/packages/pinball_components/lib/src/extensions/score.dart', 'repo_id': 'pinball', 'token_count': 81} |
import 'dart:async';
import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class AndroidBumperCowGame extends BallGame {
AndroidBumperCowGame()
: super(
imagesFileNames: [
Assets.images.android.bumper.cow.lit.keyName,
Assets.images.android.bumper.cow.dimmed.keyName,
],
);
static const description = '''
Shows how a AndroidBumper.cow is rendered.
- Activate the "trace" parameter to overlay the body.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
camera.followVector2(Vector2.zero());
await add(
AndroidBumper.cow()..priority = 1,
);
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_cow_game.dart/0 | {'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_cow_game.dart', 'repo_id': 'pinball', 'token_count': 312} |
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/boundaries/boundaries_game.dart';
void addBoundariesStories(Dashbook dashbook) {
dashbook.storiesOf('Boundaries').addGame(
title: 'Traced',
description: BoundariesGame.description,
gameBuilder: (_) => BoundariesGame(),
);
}
| pinball/packages/pinball_components/sandbox/lib/stories/boundaries/stories.dart/0 | {'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/boundaries/stories.dart', 'repo_id': 'pinball', 'token_count': 136} |
import 'dart:async';
import 'package:flame/input.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class LaunchRampGame extends BallGame {
LaunchRampGame()
: super(
ballPriority: ZIndexes.ballOnLaunchRamp,
ballLayer: Layer.launcher,
imagesFileNames: [
Assets.images.launchRamp.ramp.keyName,
Assets.images.launchRamp.backgroundRailing.keyName,
Assets.images.launchRamp.foregroundRailing.keyName,
],
);
static const description = '''
Shows how the LaunchRamp is rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
camera
..followVector2(Vector2.zero())
..zoom = 7.5;
await add(LaunchRamp());
await ready();
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart/0 | {'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart', 'repo_id': 'pinball', 'token_count': 418} |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group(
'AndroidBumperCubit',
() {
blocTest<AndroidBumperCubit, AndroidBumperState>(
'onBallContacted emits dimmed',
build: AndroidBumperCubit.new,
act: (bloc) => bloc.onBallContacted(),
expect: () => [AndroidBumperState.dimmed],
);
blocTest<AndroidBumperCubit, AndroidBumperState>(
'onBlinked emits lit',
build: AndroidBumperCubit.new,
act: (bloc) => bloc.onBlinked(),
expect: () => [AndroidBumperState.lit],
);
},
);
}
| pinball/packages/pinball_components/test/src/components/android_bumper/cubit/android_bumper_cubit_test.dart/0 | {'file_path': 'pinball/packages/pinball_components/test/src/components/android_bumper/cubit/android_bumper_cubit_test.dart', 'repo_id': 'pinball', 'token_count': 301} |
import 'package:flame/extensions.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group('BoardDimensions', () {
test('has size', () {
expect(BoardDimensions.size, equals(Vector2(101.6, 143.8)));
});
test('has bounds', () {
expect(BoardDimensions.bounds, isNotNull);
});
test('has perspectiveAngle', () {
expect(BoardDimensions.perspectiveAngle, isNotNull);
});
test('has perspectiveShrinkFactor', () {
expect(BoardDimensions.perspectiveShrinkFactor, equals(0.63));
});
});
}
| pinball/packages/pinball_components/test/src/components/board_dimensions_test.dart/0 | {'file_path': 'pinball/packages/pinball_components/test/src/components/board_dimensions_test.dart', 'repo_id': 'pinball', 'token_count': 237} |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/dash_bumper/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
class _MockDashBumpersCubit extends Mock implements DashBumpersCubit {}
class _MockBall extends Mock implements Ball {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group(
'DashBumperBallContactBehavior',
() {
test('can be instantiated', () {
expect(
DashBumperBallContactBehavior(),
isA<DashBumperBallContactBehavior>(),
);
});
flameTester.test(
'beginContact emits onBallContacted with the bumper ID '
'when contacts with a ball',
(game) async {
final behavior = DashBumperBallContactBehavior();
final bloc = _MockDashBumpersCubit();
const id = DashBumperId.main;
whenListen(
bloc,
const Stream<DashBumperSpriteState>.empty(),
initialState: DashBumperSpriteState.active,
);
final bumper = DashBumper.test(id: id);
await bumper.add(behavior);
await game.ensureAdd(
FlameBlocProvider<DashBumpersCubit, DashBumpersState>.value(
value: bloc,
children: [bumper],
),
);
behavior.beginContact(_MockBall(), _MockContact());
verify(() => bloc.onBallContacted(id)).called(1);
},
);
},
);
}
| pinball/packages/pinball_components/test/src/components/dash_nest_bumper/behaviors/dash_bumper_ball_contact_behavior_test.dart/0 | {'file_path': 'pinball/packages/pinball_components/test/src/components/dash_nest_bumper/behaviors/dash_bumper_ball_contact_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 814} |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/google_rollover/behaviors/behaviors.dart';
import '../../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.googleRollover.left.decal.keyName,
Assets.images.googleRollover.left.pin.keyName,
Assets.images.googleRollover.right.decal.keyName,
Assets.images.googleRollover.right.pin.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('GoogleRollover', () {
test('can be instantiated', () {
expect(
GoogleRollover(side: BoardSide.left),
isA<GoogleRollover>(),
);
});
flameTester.test('left loads correctly', (game) async {
final googleRollover = GoogleRollover(side: BoardSide.left);
await game.ensureAdd(googleRollover);
expect(game.contains(googleRollover), isTrue);
});
flameTester.test('right loads correctly', (game) async {
final googleRollover = GoogleRollover(side: BoardSide.right);
await game.ensureAdd(googleRollover);
expect(game.contains(googleRollover), isTrue);
});
group('adds', () {
flameTester.test('new children', (game) async {
final component = Component();
final googleRollover = GoogleRollover(
side: BoardSide.left,
children: [component],
);
await game.ensureAdd(googleRollover);
expect(googleRollover.children, contains(component));
});
flameTester.test('a GoogleRolloverBallContactBehavior', (game) async {
final googleRollover = GoogleRollover(side: BoardSide.left);
await game.ensureAdd(googleRollover);
expect(
googleRollover.children
.whereType<GoogleRolloverBallContactBehavior>()
.single,
isNotNull,
);
});
});
flameTester.test(
'pin stops animating after animation completes',
(game) async {
final googleRollover = GoogleRollover(side: BoardSide.left);
await game.ensureAdd(googleRollover);
final pinSpriteAnimationComponent =
googleRollover.firstChild<SpriteAnimationComponent>()!;
pinSpriteAnimationComponent.playing = true;
game.update(
pinSpriteAnimationComponent.animation!.totalDuration() + 0.1,
);
expect(pinSpriteAnimationComponent.playing, isFalse);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/google_rollover/google_rollover_test.dart/0 | {'file_path': 'pinball/packages/pinball_components/test/src/components/google_rollover/google_rollover_test.dart', 'repo_id': 'pinball', 'token_count': 1044} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/src/pinball_components.dart';
void main() {
group('MultiballState', () {
test('supports value equality', () {
expect(
MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
),
equals(
MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
),
),
);
});
group('constructor', () {
test('can be instantiated', () {
expect(
MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
),
isNotNull,
);
});
});
group('copyWith', () {
test(
'copies correctly '
'when no argument specified',
() {
final multiballState = MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
);
expect(
multiballState.copyWith(),
equals(multiballState),
);
},
);
test(
'copies correctly '
'when all arguments specified',
() {
final multiballState = MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
);
final otherMultiballState = MultiballState(
animationState: MultiballAnimationState.blinking,
lightState: MultiballLightState.lit,
);
expect(multiballState, isNot(equals(otherMultiballState)));
expect(
multiballState.copyWith(
animationState: MultiballAnimationState.blinking,
lightState: MultiballLightState.lit,
),
equals(otherMultiballState),
);
},
);
});
});
}
| pinball/packages/pinball_components/test/src/components/multiball/cubit/multiball_state_test.dart/0 | {'file_path': 'pinball/packages/pinball_components/test/src/components/multiball/cubit/multiball_state_test.dart', 'repo_id': 'pinball', 'token_count': 1011} |
// ignore_for_file: cascade_invocations
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.signpost.inactive.keyName,
Assets.images.signpost.active1.keyName,
Assets.images.signpost.active2.keyName,
Assets.images.signpost.active3.keyName,
]);
}
Future<void> pump(
Signpost child, {
SignpostCubit? signpostBloc,
DashBumpersCubit? dashBumpersBloc,
}) async {
await onLoad();
await ensureAdd(
FlameMultiBlocProvider(
providers: [
FlameBlocProvider<SignpostCubit, SignpostState>.value(
value: signpostBloc ?? SignpostCubit(),
),
FlameBlocProvider<DashBumpersCubit, DashBumpersState>.value(
value: dashBumpersBloc ?? DashBumpersCubit(),
),
],
children: [child],
),
);
}
}
class _MockSignpostCubit extends Mock implements SignpostCubit {}
class _MockDashBumpersCubit extends Mock implements DashBumpersCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('Signpost', () {
const goldenPath = '../golden/signpost/';
test('can be instantiated', () {
expect(Signpost(), isA<Signpost>());
});
flameTester.test(
'can be added',
(game) async {
final signpost = Signpost();
await game.pump(signpost);
expect(game.descendants().contains(signpost), isTrue);
},
);
group('renders correctly', () {
flameTester.testGameWidget(
'inactive sprite',
setUp: (game, tester) async {
final signpost = Signpost();
await game.pump(signpost);
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.inactive),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}inactive.png'),
);
},
);
flameTester.testGameWidget(
'active1 sprite',
setUp: (game, tester) async {
final signpost = Signpost();
final bloc = SignpostCubit();
await game.pump(signpost, signpostBloc: bloc);
bloc.onProgressed();
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.active1),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}active1.png'),
);
},
);
flameTester.testGameWidget(
'active2 sprite',
setUp: (game, tester) async {
final signpost = Signpost();
final bloc = SignpostCubit();
await game.pump(signpost, signpostBloc: bloc);
bloc
..onProgressed()
..onProgressed();
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.active2),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}active2.png'),
);
},
);
flameTester.testGameWidget(
'active3 sprite',
setUp: (game, tester) async {
final signpost = Signpost();
final bloc = SignpostCubit();
await game.pump(signpost, signpostBloc: bloc);
bloc
..onProgressed()
..onProgressed()
..onProgressed();
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.active3),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}active3.png'),
);
},
);
});
flameTester.testGameWidget(
'listenWhen is true when all dash bumpers are activated',
setUp: (game, tester) async {
final activatedBumpersState = DashBumpersState(
bumperSpriteStates: {
for (var id in DashBumperId.values) id: DashBumperSpriteState.active
},
);
final signpost = Signpost();
final dashBumpersBloc = _MockDashBumpersCubit();
whenListen(
dashBumpersBloc,
const Stream<DashBumpersState>.empty(),
initialState: DashBumpersState.initial(),
);
await game.pump(signpost, dashBumpersBloc: dashBumpersBloc);
final signpostListener = game
.descendants()
.whereType<FlameBlocListener<DashBumpersCubit, DashBumpersState>>()
.single;
final listenWhen = signpostListener.listenWhen(
DashBumpersState.initial(),
activatedBumpersState,
);
expect(listenWhen, isTrue);
},
);
flameTester.test(
'onNewState calls onProgressed and onReset',
(game) async {
final signpost = Signpost();
final signpostBloc = _MockSignpostCubit();
whenListen(
signpostBloc,
const Stream<SignpostState>.empty(),
initialState: SignpostState.inactive,
);
final dashBumpersBloc = _MockDashBumpersCubit();
whenListen(
dashBumpersBloc,
const Stream<DashBumpersState>.empty(),
initialState: DashBumpersState.initial(),
);
await game.pump(
signpost,
signpostBloc: signpostBloc,
dashBumpersBloc: dashBumpersBloc,
);
game
.descendants()
.whereType<FlameBlocListener<DashBumpersCubit, DashBumpersState>>()
.single
.onNewState(DashBumpersState.initial());
verify(signpostBloc.onProgressed).called(1);
verify(dashBumpersBloc.onReset).called(1);
},
);
flameTester.test('adds new children', (game) async {
final component = Component();
final signpost = Signpost(
children: [component],
);
await game.pump(signpost);
expect(signpost.children, contains(component));
});
});
}
| pinball/packages/pinball_components/test/src/components/signpost/signpost_test.dart/0 | {'file_path': 'pinball/packages/pinball_components/test/src/components/signpost/signpost_test.dart', 'repo_id': 'pinball', 'token_count': 3321} |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/bumping_behavior.dart';
import 'package:pinball_components/src/components/sparky_bumper/behaviors/behaviors.dart';
import '../../../helpers/helpers.dart';
class _MockSparkyBumperCubit extends Mock implements SparkyBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.sparky.bumper.a.lit.keyName,
Assets.images.sparky.bumper.a.dimmed.keyName,
Assets.images.sparky.bumper.b.lit.keyName,
Assets.images.sparky.bumper.b.dimmed.keyName,
Assets.images.sparky.bumper.c.lit.keyName,
Assets.images.sparky.bumper.c.dimmed.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('SparkyBumper', () {
flameTester.test('"a" loads correctly', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(game.contains(sparkyBumper), isTrue);
});
flameTester.test('"b" loads correctly', (game) async {
final sparkyBumper = SparkyBumper.b();
await game.ensureAdd(sparkyBumper);
expect(game.contains(sparkyBumper), isTrue);
});
flameTester.test('"c" loads correctly', (game) async {
final sparkyBumper = SparkyBumper.c();
await game.ensureAdd(sparkyBumper);
expect(game.contains(sparkyBumper), isTrue);
});
flameTester.test('closes bloc when removed', (game) async {
final bloc = _MockSparkyBumperCubit();
whenListen(
bloc,
const Stream<SparkyBumperState>.empty(),
initialState: SparkyBumperState.lit,
);
when(bloc.close).thenAnswer((_) async {});
final sparkyBumper = SparkyBumper.test(bloc: bloc);
await game.ensureAdd(sparkyBumper);
game.remove(sparkyBumper);
await game.ready();
verify(bloc.close).called(1);
});
group('adds', () {
flameTester.test('a SparkyBumperBallContactBehavior', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children
.whereType<SparkyBumperBallContactBehavior>()
.single,
isNotNull,
);
});
flameTester.test('a SparkyBumperBlinkingBehavior', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children
.whereType<SparkyBumperBlinkingBehavior>()
.single,
isNotNull,
);
});
});
group("'a' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final sparkyBumper = SparkyBumper.a(
children: [component],
);
await game.ensureAdd(sparkyBumper);
expect(sparkyBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
group("'b' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final sparkyBumper = SparkyBumper.b(
children: [component],
);
await game.ensureAdd(sparkyBumper);
expect(sparkyBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final sparkyBumper = SparkyBumper.b();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
group("'c' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final sparkyBumper = SparkyBumper.c(
children: [component],
);
await game.ensureAdd(sparkyBumper);
expect(sparkyBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final sparkyBumper = SparkyBumper.c();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
});
});
}
| pinball/packages/pinball_components/test/src/components/sparky_bumper/sparky_bumper_test.dart/0 | {'file_path': 'pinball/packages/pinball_components/test/src/components/sparky_bumper/sparky_bumper_test.dart', 'repo_id': 'pinball', 'token_count': 2119} |
import 'dart:ui';
import 'package:collection/collection.dart' as collection;
import 'package:flame/components.dart';
import 'package:pinball_flame/src/canvas/canvas_wrapper.dart';
/// {@template z_canvas_component}
/// Draws [ZIndex] components after the all non-[ZIndex] components have been
/// drawn.
/// {@endtemplate}
class ZCanvasComponent extends Component {
/// {@macro z_canvas_component}
ZCanvasComponent({
Iterable<Component>? children,
}) : _zCanvas = _ZCanvas(),
super(children: children);
final _ZCanvas _zCanvas;
@override
void renderTree(Canvas canvas) {
_zCanvas.canvas = canvas;
super.renderTree(_zCanvas);
_zCanvas.render();
}
}
/// Apply to any [Component] that will be rendered according to a
/// [ZIndex.zIndex].
///
/// [ZIndex] components must be descendants of a [ZCanvasComponent].
///
/// {@macro z_canvas.render}
mixin ZIndex on Component {
/// The z-index of this component.
///
/// The higher the value, the later the component will be drawn. Hence,
/// rendering in front of [Component]s with lower [zIndex] values.
int zIndex = 0;
@override
void renderTree(
Canvas canvas,
) {
if (canvas is _ZCanvas) {
canvas.buffer(this);
} else {
super.renderTree(canvas);
}
}
}
/// The [_ZCanvas] allows to postpone the rendering of [ZIndex] components.
///
/// You should not use this class directly.
class _ZCanvas extends CanvasWrapper {
final List<ZIndex> _zBuffer = [];
/// Postpones the rendering of [ZIndex] component and its children.
void buffer(ZIndex component) {
final lowerBound = collection.lowerBound<ZIndex>(
_zBuffer,
component,
compare: (a, b) => a.zIndex.compareTo(b.zIndex),
);
_zBuffer.insert(lowerBound, component);
}
/// Renders all [ZIndex] components and their children.
///
/// {@template z_canvas.render}
/// The rendering order is defined by the parent [ZIndex]. The children of
/// the same parent are rendered in the order they were added.
///
/// If two [Component]s ever overlap each other, and have the same
/// [ZIndex.zIndex], there is no guarantee that the first one will be rendered
/// before the second one.
/// {@endtemplate}
void render() => _zBuffer
..forEach(_render)
..clear();
void _render(Component component) => component.renderTree(canvas);
}
| pinball/packages/pinball_flame/lib/src/canvas/z_canvas_component.dart/0 | {'file_path': 'pinball/packages/pinball_flame/lib/src/canvas/z_canvas_component.dart', 'repo_id': 'pinball', 'token_count': 794} |
// ignore_for_file: cascade_invocations
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_flame/src/canvas/canvas_component.dart';
class _TestSpriteComponent extends SpriteComponent {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('CanvasComponent', () {
final flameTester = FlameTester(FlameGame.new);
test('can be instantiated', () {
expect(
CanvasComponent(),
isA<CanvasComponent>(),
);
});
flameTester.test('loads correctly', (game) async {
final component = CanvasComponent();
await game.ensureAdd(component);
expect(game.contains(component), isTrue);
});
flameTester.test(
'adds children',
(game) async {
final component = Component();
final canvas = CanvasComponent(
onSpritePainted: (paint) => paint.filterQuality = FilterQuality.high,
children: [component],
);
await game.ensureAdd(canvas);
expect(
canvas.children.contains(component),
isTrue,
);
},
);
flameTester.testGameWidget(
'calls onSpritePainted when painting a sprite',
setUp: (game, tester) async {
final spriteComponent = _TestSpriteComponent();
final completer = Completer<Image>();
decodeImageFromList(
Uint8List.fromList(_image),
completer.complete,
);
spriteComponent.sprite = Sprite(await completer.future);
var calls = 0;
final canvas = CanvasComponent(
onSpritePainted: (paint) => calls++,
children: [spriteComponent],
);
await game.ensureAdd(canvas);
await tester.pump();
expect(calls, equals(1));
},
);
});
}
const List<int> _image = <int>[
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A,
0x00,
0x00,
0x00,
0x0D,
0x49,
0x48,
0x44,
0x52,
0x00,
0x00,
0x00,
0x01,
0x00,
0x00,
0x00,
0x01,
0x08,
0x06,
0x00,
0x00,
0x00,
0x1F,
0x15,
0xC4,
0x89,
0x00,
0x00,
0x00,
0x0A,
0x49,
0x44,
0x41,
0x54,
0x78,
0x9C,
0x63,
0x00,
0x01,
0x00,
0x00,
0x05,
0x00,
0x01,
0x0D,
0x0A,
0x2D,
0xB4,
0x00,
0x00,
0x00,
0x00,
0x49,
0x45,
0x4E,
0x44,
0xAE,
];
| pinball/packages/pinball_flame/test/src/canvas/canvas_component_test.dart/0 | {'file_path': 'pinball/packages/pinball_flame/test/src/canvas/canvas_component_test.dart', 'repo_id': 'pinball', 'token_count': 1236} |
name: pinball_theme
description: Package containing themes for pinball game.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
dependencies:
equatable: ^2.0.3
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
very_good_analysis: ^2.4.0
flutter:
generate: true
assets:
- assets/images/
- assets/images/android/
- assets/images/dash/
- assets/images/dino/
- assets/images/sparky/
flutter_gen:
assets:
package_parameter_enabled: true
output: lib/src/generated/
line_length: 80
integrations:
flutter_svg: true
| pinball/packages/pinball_theme/pubspec.yaml/0 | {'file_path': 'pinball/packages/pinball_theme/pubspec.yaml', 'repo_id': 'pinball', 'token_count': 252} |
import 'package:flutter/material.dart';
import 'package:pinball_ui/gen/gen.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// Enum with all possible directions of a [PinballDpadButton].
enum PinballDpadDirection {
/// Up
up,
/// Down
down,
/// Left
left,
/// Right
right,
}
extension _PinballDpadDirectionX on PinballDpadDirection {
String toAsset() {
switch (this) {
case PinballDpadDirection.up:
return Assets.images.button.dpadUp.keyName;
case PinballDpadDirection.down:
return Assets.images.button.dpadDown.keyName;
case PinballDpadDirection.left:
return Assets.images.button.dpadLeft.keyName;
case PinballDpadDirection.right:
return Assets.images.button.dpadRight.keyName;
}
}
}
/// {@template pinball_dpad_button}
/// Widget that renders a Dpad button with a given direction.
/// {@endtemplate}
class PinballDpadButton extends StatelessWidget {
/// {@macro pinball_dpad_button}
const PinballDpadButton({
Key? key,
required this.direction,
required this.onTap,
}) : super(key: key);
/// Which [PinballDpadDirection] this button is.
final PinballDpadDirection direction;
/// The function executed when the button is pressed.
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: PinballColors.transparent,
child: InkWell(
onTap: onTap,
highlightColor: PinballColors.transparent,
splashColor: PinballColors.transparent,
child: Image.asset(
direction.toAsset(),
width: 60,
height: 60,
),
),
);
}
}
| pinball/packages/pinball_ui/lib/src/widgets/pinball_dpad_button.dart/0 | {'file_path': 'pinball/packages/pinball_ui/lib/src/widgets/pinball_dpad_button.dart', 'repo_id': 'pinball', 'token_count': 637} |
name: pinball
description: Google I/O 2022 Pinball game built with Flutter and Firebase
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
flutter: 2.10.5
dependencies:
authentication_repository:
path: packages/authentication_repository
bloc: ^8.0.2
cloud_firestore: ^3.1.10
equatable: ^2.0.3
firebase_auth: ^3.3.16
firebase_core: ^1.15.0
flame: ^1.1.1
flame_bloc: ^1.4.0
flame_forge2d:
git:
url: https://github.com/flame-engine/flame
path: packages/flame_forge2d/
ref: a50d4a1e7d9eaf66726ed1bb9894c9d495547d8f
flutter:
sdk: flutter
flutter_bloc: ^8.0.1
flutter_localizations:
sdk: flutter
geometry:
path: packages/geometry
intl: ^0.17.0
leaderboard_repository:
path: packages/leaderboard_repository
pinball_audio:
path: packages/pinball_audio
pinball_components:
path: packages/pinball_components
pinball_flame:
path: packages/pinball_flame
pinball_theme:
path: packages/pinball_theme
pinball_ui:
path: packages/pinball_ui
platform_helper:
path: packages/platform_helper
share_repository:
path: packages/share_repository
url_launcher: ^6.1.0
dev_dependencies:
bloc_test: ^9.0.2
flame_test: ^1.3.0
flutter_test:
sdk: flutter
mocktail: ^0.3.0
very_good_analysis: ^2.4.0
flutter:
uses-material-design: true
generate: true
assets:
- assets/images/components/
- assets/images/bonus_animation/
- assets/images/score/
- assets/images/loading_game/
flutter_gen:
line_length: 80
| pinball/pubspec.yaml/0 | {'file_path': 'pinball/pubspec.yaml', 'repo_id': 'pinball', 'token_count': 671} |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart';
void main() {
group('GameBloc', () {
test('initial state has 3 rounds and empty score', () {
final gameBloc = GameBloc();
expect(gameBloc.state.roundScore, equals(0));
expect(gameBloc.state.rounds, equals(3));
});
blocTest<GameBloc, GameState>(
'GameStarted starts the game',
build: GameBloc.new,
act: (bloc) => bloc.add(const GameStarted()),
expect: () => [
isA<GameState>()
..having(
(state) => state.status,
'status',
GameStatus.playing,
),
],
);
blocTest<GameBloc, GameState>(
'GameOver finishes the game',
build: GameBloc.new,
act: (bloc) => bloc.add(const GameOver()),
expect: () => [
isA<GameState>()
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
group('RoundLost', () {
blocTest<GameBloc, GameState>(
'decreases number of rounds '
'when there are already available rounds',
build: GameBloc.new,
act: (bloc) {
bloc.add(const RoundLost());
},
expect: () => [
isA<GameState>()..having((state) => state.rounds, 'rounds', 2),
],
);
blocTest<GameBloc, GameState>(
'sets game over when there are no more rounds',
build: GameBloc.new,
act: (bloc) {
bloc
..add(const RoundLost())
..add(const RoundLost())
..add(const RoundLost());
},
expect: () => [
isA<GameState>()..having((state) => state.rounds, 'rounds', 2),
isA<GameState>()..having((state) => state.rounds, 'rounds', 1),
isA<GameState>()
..having((state) => state.rounds, 'rounds', 0)
..having((state) => state.status, 'status', GameStatus.gameOver),
],
);
blocTest<GameBloc, GameState>(
'apply multiplier to roundScore and add it to totalScore '
'when round is lost',
build: GameBloc.new,
seed: () => const GameState(
totalScore: 10,
roundScore: 5,
multiplier: 3,
rounds: 2,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) {
bloc.add(const RoundLost());
},
expect: () => [
isA<GameState>()
..having((state) => state.totalScore, 'totalScore', 25)
..having((state) => state.roundScore, 'roundScore', 0)
],
);
blocTest<GameBloc, GameState>(
"multiplier doesn't increase score above the max score",
build: GameBloc.new,
seed: () => const GameState(
totalScore: 9999999998,
roundScore: 1,
multiplier: 2,
rounds: 1,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) => bloc.add(const RoundLost()),
expect: () => [
isA<GameState>()
..having(
(state) => state.totalScore,
'totalScore',
9999999999,
)
],
);
blocTest<GameBloc, GameState>(
'resets multiplier when round is lost',
build: GameBloc.new,
seed: () => const GameState(
totalScore: 10,
roundScore: 5,
multiplier: 3,
rounds: 2,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) {
bloc.add(const RoundLost());
},
expect: () => [
isA<GameState>()..having((state) => state.multiplier, 'multiplier', 1)
],
);
});
group('Scored', () {
blocTest<GameBloc, GameState>(
'increases score when playing',
build: GameBloc.new,
act: (bloc) => bloc
..add(const GameStarted())
..add(const Scored(points: 2))
..add(const Scored(points: 3)),
expect: () => [
isA<GameState>()
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 2)
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 5)
..having((state) => state.status, 'status', GameStatus.playing),
],
);
blocTest<GameBloc, GameState>(
"doesn't increase score when game is over",
build: GameBloc.new,
act: (bloc) {
for (var i = 0; i < bloc.state.rounds; i++) {
bloc.add(const RoundLost());
}
bloc.add(const Scored(points: 2));
},
expect: () => [
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 0)
..having((state) => state.rounds, 'rounds', 2)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 0)
..having((state) => state.rounds, 'rounds', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 0)
..having((state) => state.rounds, 'rounds', 0)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
blocTest<GameBloc, GameState>(
"doesn't increase score above the max score",
build: GameBloc.new,
seed: () => const GameState(
totalScore: 9999999998,
roundScore: 0,
multiplier: 1,
rounds: 1,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) => bloc.add(const Scored(points: 2)),
expect: () => [
isA<GameState>()..having((state) => state.roundScore, 'roundScore', 1)
],
);
});
group('MultiplierIncreased', () {
blocTest<GameBloc, GameState>(
'increases multiplier '
'when multiplier is below 6 and game is not over',
build: GameBloc.new,
act: (bloc) => bloc
..add(const GameStarted())
..add(const MultiplierIncreased())
..add(const MultiplierIncreased()),
expect: () => [
isA<GameState>()
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 2)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 3)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
blocTest<GameBloc, GameState>(
"doesn't increase multiplier "
'when multiplier is 6 and game is not over',
build: GameBloc.new,
seed: () => const GameState(
totalScore: 10,
roundScore: 0,
multiplier: 6,
rounds: 3,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) => bloc..add(const MultiplierIncreased()),
expect: () => const <GameState>[],
);
blocTest<GameBloc, GameState>(
"doesn't increase multiplier "
'when game is over',
build: GameBloc.new,
act: (bloc) {
bloc.add(const GameStarted());
for (var i = 0; i < bloc.state.rounds; i++) {
bloc.add(const RoundLost());
}
bloc.add(const MultiplierIncreased());
},
expect: () => [
isA<GameState>()
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
});
group(
'BonusActivated',
() {
blocTest<GameBloc, GameState>(
'adds bonus to history',
build: GameBloc.new,
act: (bloc) => bloc
..add(const BonusActivated(GameBonus.googleWord))
..add(const BonusActivated(GameBonus.dashNest)),
expect: () => [
isA<GameState>()
..having(
(state) => state.bonusHistory,
'bonusHistory',
[GameBonus.googleWord],
),
isA<GameState>()
..having(
(state) => state.bonusHistory,
'bonusHistory',
[GameBonus.googleWord, GameBonus.dashNest],
),
],
);
},
);
});
}
| pinball/test/game/bloc/game_bloc_test.dart/0 | {'file_path': 'pinball/test/game/bloc/game_bloc_test.dart', 'repo_id': 'pinball', 'token_count': 5063} |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/components/backbox/displays/initials_submission_failure_display.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
await super.onLoad();
images.prefix = '';
await images.loadAll(
[
Assets.images.errorBackground.keyName,
],
);
}
Future<void> pump(InitialsSubmissionFailureDisplay component) {
return ensureAdd(
FlameProvider.value(
_MockAppLocalizations(),
children: [component],
),
);
}
}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get initialsErrorTitle => 'Title';
@override
String get initialsErrorMessage => 'Message';
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('InitialsSubmissionFailureDisplay', () {
final flameTester = FlameTester(_TestGame.new);
flameTester.test('renders correctly', (game) async {
await game.pump(
InitialsSubmissionFailureDisplay(
onDismissed: () {},
),
);
expect(
game
.descendants()
.where(
(component) =>
component is TextComponent && component.text == 'Title',
)
.length,
equals(1),
);
expect(
game
.descendants()
.where(
(component) =>
component is TextComponent && component.text == 'Message',
)
.length,
equals(1),
);
});
});
}
| pinball/test/game/components/backbox/displays/initials_submission_failure_display_test.dart/0 | {'file_path': 'pinball/test/game/components/backbox/displays/initials_submission_failure_display_test.dart', 'repo_id': 'pinball', 'token_count': 844} |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/google_gallery/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.googleWord.letter1.lit.keyName,
Assets.images.googleWord.letter1.dimmed.keyName,
Assets.images.googleWord.letter2.lit.keyName,
Assets.images.googleWord.letter2.dimmed.keyName,
Assets.images.googleWord.letter3.lit.keyName,
Assets.images.googleWord.letter3.dimmed.keyName,
Assets.images.googleWord.letter4.lit.keyName,
Assets.images.googleWord.letter4.dimmed.keyName,
Assets.images.googleWord.letter5.lit.keyName,
Assets.images.googleWord.letter5.dimmed.keyName,
Assets.images.googleWord.letter6.lit.keyName,
Assets.images.googleWord.letter6.dimmed.keyName,
Assets.images.googleRollover.left.decal.keyName,
Assets.images.googleRollover.left.pin.keyName,
Assets.images.googleRollover.right.decal.keyName,
Assets.images.googleRollover.right.pin.keyName,
]);
}
Future<void> pump(GoogleGallery child) async {
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: _MockGameBloc(),
children: [child],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('GoogleGallery', () {
flameTester.test('loads correctly', (game) async {
final component = GoogleGallery();
await game.pump(component);
expect(game.descendants(), contains(component));
});
group('loads', () {
flameTester.test(
'two GoogleRollovers',
(game) async {
await game.pump(GoogleGallery());
expect(
game.descendants().whereType<GoogleRollover>().length,
equals(2),
);
},
);
flameTester.test(
'a GoogleWord',
(game) async {
await game.pump(GoogleGallery());
expect(
game.descendants().whereType<GoogleWord>().length,
equals(1),
);
},
);
});
group('adds', () {
flameTester.test(
'ScoringContactBehavior to GoogleRollovers',
(game) async {
await game.pump(GoogleGallery());
game.descendants().whereType<GoogleRollover>().forEach(
(rollover) => expect(
rollover.firstChild<ScoringContactBehavior>(),
isNotNull,
),
);
},
);
flameTester.test(
'RolloverNoiseBehavior to GoogleRollovers',
(game) async {
await game.pump(GoogleGallery());
game.descendants().whereType<GoogleRollover>().forEach(
(rollover) => expect(
rollover.firstChild<RolloverNoiseBehavior>(),
isNotNull,
),
);
},
);
flameTester.test('a GoogleWordBonusBehavior', (game) async {
final component = GoogleGallery();
await game.pump(component);
expect(
component.descendants().whereType<GoogleWordBonusBehavior>().single,
isNotNull,
);
});
});
});
}
| pinball/test/game/components/google_gallery/google_gallery_test.dart/0 | {'file_path': 'pinball/test/game/components/google_gallery/google_gallery_test.dart', 'repo_id': 'pinball', 'token_count': 1666} |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_ui/pinball_ui.dart';
import '../../../helpers/helpers.dart';
class _MockGameBloc extends Mock implements GameBloc {}
void main() {
group('RoundCountDisplay renders', () {
late GameBloc gameBloc;
const initialState = GameState(
totalScore: 0,
roundScore: 0,
multiplier: 1,
rounds: 3,
bonusHistory: [],
status: GameStatus.playing,
);
setUp(() {
gameBloc = _MockGameBloc();
whenListen(
gameBloc,
Stream.value(initialState),
initialState: initialState,
);
});
testWidgets('three active round indicator', (tester) async {
await tester.pumpApp(
const RoundCountDisplay(),
gameBloc: gameBloc,
);
await tester.pump();
expect(find.byType(RoundIndicator), findsNWidgets(3));
});
testWidgets('two active round indicator', (tester) async {
final state = initialState.copyWith(
rounds: 2,
);
whenListen(
gameBloc,
Stream.value(state),
initialState: state,
);
await tester.pumpApp(
const RoundCountDisplay(),
gameBloc: gameBloc,
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && widget.isActive,
),
findsNWidgets(2),
);
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && !widget.isActive,
),
findsOneWidget,
);
});
testWidgets('one active round indicator', (tester) async {
final state = initialState.copyWith(
rounds: 1,
);
whenListen(
gameBloc,
Stream.value(state),
initialState: state,
);
await tester.pumpApp(
const RoundCountDisplay(),
gameBloc: gameBloc,
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && widget.isActive,
),
findsOneWidget,
);
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && !widget.isActive,
),
findsNWidgets(2),
);
});
});
testWidgets('active round indicator is displaying with proper color',
(tester) async {
await tester.pumpApp(
const RoundIndicator(isActive: true),
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) => widget is Container && widget.color == PinballColors.yellow,
),
findsOneWidget,
);
});
testWidgets('inactive round indicator is displaying with proper color',
(tester) async {
await tester.pumpApp(
const RoundIndicator(isActive: false),
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) =>
widget is Container &&
widget.color == PinballColors.yellow.withAlpha(128),
),
findsOneWidget,
);
});
}
| pinball/test/game/view/widgets/round_count_display_test.dart/0 | {'file_path': 'pinball/test/game/view/widgets/round_count_display_test.dart', 'repo_id': 'pinball', 'token_count': 1426} |
include: package:flutter_lints/flutter.yaml
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
errors:
missing_required_param: error
missing_return: error
unused_import: error
unused_local_variable: error
dead_code: error
linter:
rules:
# All rules from pedantic, already enabled rules are left out
# https://github.com/google/pedantic/blob/master/lib/analysis_options.1.11.0.yaml
- always_declare_return_types
- prefer_single_quotes
- sort_child_properties_last
- unawaited_futures
- unsafe_html
# Additional rules from https://github.com/flutter/flutter/blob/master/analysis_options.yaml
# Not all rules are included
- always_put_control_body_on_new_line
- avoid_slow_async_io
- cast_nullable_to_non_nullable
- directives_ordering
- missing_whitespace_between_adjacent_strings
- sort_pub_dependencies
- prefer_final_in_for_each
- prefer_final_locals
- prefer_foreach
- prefer_if_elements_to_conditional_expressions
- sort_constructors_first
- sort_unnamed_constructors_first
- test_types_in_equals
- tighten_type_of_initializing_formals
- unnecessary_await_in_return
- unnecessary_null_aware_assignments
- unnecessary_null_checks
- unnecessary_nullable_for_final_variable_declarations
- unnecessary_statements
- use_late_for_private_fields_and_variables
- use_named_constants
- use_raw_strings | playground/analysis_options.yaml/0 | {'file_path': 'playground/analysis_options.yaml', 'repo_id': 'playground', 'token_count': 549} |
// https://stackoverflow.com/a/55088673/8236404
double Function(double input) interpolate({
double inputMin = 0,
double inputMax = 1,
double outputMin = 0,
double outputMax = 1,
}) {
assert(inputMin != inputMax || outputMin != outputMax);
final diff = (outputMax - outputMin) / (inputMax - inputMin);
return (input) => ((input - inputMin) * diff) + outputMin;
}
| playground/lib/interpolate.dart/0 | {'file_path': 'playground/lib/interpolate.dart', 'repo_id': 'playground', 'token_count': 122} |
// 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:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_platform_interface/src/method_channel/method_channel_camera.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$CameraPlatform', () {
test('$MethodChannelCamera is the default instance', () {
expect(CameraPlatform.instance, isA<MethodChannelCamera>());
});
test('Cannot be implemented with `implements`', () {
expect(() {
CameraPlatform.instance = ImplementsCameraPlatform();
}, throwsNoSuchMethodError);
});
test('Can be extended', () {
CameraPlatform.instance = ExtendsCameraPlatform();
});
test(
'Default implementation of availableCameras() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.availableCameras(),
throwsUnimplementedError,
);
});
test(
'Default implementation of onCameraInitialized() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraInitialized(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onResolutionChanged() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraResolutionChanged(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onCameraClosing() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraClosing(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onCameraError() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraError(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onDeviceOrientationChanged() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onDeviceOrientationChanged(),
throwsUnimplementedError,
);
});
test(
'Default implementation of lockCaptureOrientation() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.lockCaptureOrientation(
1, DeviceOrientation.portraitUp),
throwsUnimplementedError,
);
});
test(
'Default implementation of unlockCaptureOrientation() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.unlockCaptureOrientation(1),
throwsUnimplementedError,
);
});
test('Default implementation of dispose() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.dispose(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of createCamera() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.createCamera(
const CameraDescription(
name: 'back',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
),
throwsUnimplementedError,
);
});
test(
'Default implementation of initializeCamera() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.initializeCamera(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of pauseVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.pauseVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of prepareForVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.prepareForVideoRecording(),
throwsUnimplementedError,
);
});
test(
'Default implementation of resumeVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.resumeVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of setFlashMode() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setFlashMode(1, FlashMode.auto),
throwsUnimplementedError,
);
});
test(
'Default implementation of setExposureMode() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setExposureMode(1, ExposureMode.auto),
throwsUnimplementedError,
);
});
test(
'Default implementation of setExposurePoint() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setExposurePoint(1, null),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMinExposureOffset() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMinExposureOffset(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMaxExposureOffset() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMaxExposureOffset(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getExposureOffsetStepSize() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getExposureOffsetStepSize(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of setExposureOffset() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setExposureOffset(1, 2.0),
throwsUnimplementedError,
);
});
test(
'Default implementation of setFocusMode() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setFocusMode(1, FocusMode.auto),
throwsUnimplementedError,
);
});
test(
'Default implementation of setFocusPoint() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setFocusPoint(1, null),
throwsUnimplementedError,
);
});
test(
'Default implementation of startVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.startVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of stopVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.stopVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of takePicture() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.takePicture(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMaxZoomLevel() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMaxZoomLevel(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMinZoomLevel() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMinZoomLevel(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of setZoomLevel() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setZoomLevel(1, 1.0),
throwsUnimplementedError,
);
});
test(
'Default implementation of pausePreview() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.pausePreview(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of resumePreview() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.resumePreview(1),
throwsUnimplementedError,
);
});
});
}
class ImplementsCameraPlatform implements CameraPlatform {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class ExtendsCameraPlatform extends CameraPlatform {}
| plugins/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart/0 | {'file_path': 'plugins/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart', 'repo_id': 'plugins', 'token_count': 4635} |
// 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.
/// A set of allowed XTypes
class XTypeGroup {
/// Creates a new group with the given label and file extensions.
///
/// A group with none of the type options provided indicates that any type is
/// allowed.
XTypeGroup({
this.label,
List<String>? extensions,
this.mimeTypes,
this.macUTIs,
this.webWildCards,
}) : extensions = _removeLeadingDots(extensions);
/// The 'name' or reference to this group of types
final String? label;
/// The extensions for this group
final List<String>? extensions;
/// The MIME types for this group
final List<String>? mimeTypes;
/// The UTIs for this group
final List<String>? macUTIs;
/// The web wild cards for this group (ex: image/*, video/*)
final List<String>? webWildCards;
/// Converts this object into a JSON formatted object
Map<String, dynamic> toJSON() {
return <String, dynamic>{
'label': label,
'extensions': extensions,
'mimeTypes': mimeTypes,
'macUTIs': macUTIs,
'webWildCards': webWildCards,
};
}
static List<String>? _removeLeadingDots(List<String>? exts) => exts
?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext)
.toList();
}
| plugins/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group/x_type_group.dart/0 | {'file_path': 'plugins/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group/x_type_group.dart', 'repo_id': 'plugins', 'token_count': 467} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:math';
import 'dart:ui';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'page.dart';
class PlaceMarkerPage extends GoogleMapExampleAppPage {
PlaceMarkerPage() : super(const Icon(Icons.place), 'Place marker');
@override
Widget build(BuildContext context) {
return const PlaceMarkerBody();
}
}
class PlaceMarkerBody extends StatefulWidget {
const PlaceMarkerBody();
@override
State<StatefulWidget> createState() => PlaceMarkerBodyState();
}
typedef MarkerUpdateAction = Marker Function(Marker marker);
class PlaceMarkerBodyState extends State<PlaceMarkerBody> {
PlaceMarkerBodyState();
static final LatLng center = const LatLng(-33.86711, 151.1947171);
GoogleMapController? controller;
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
MarkerId? selectedMarker;
int _markerIdCounter = 1;
LatLng? markerPosition;
void _onMapCreated(GoogleMapController controller) {
this.controller = controller;
}
@override
void dispose() {
super.dispose();
}
void _onMarkerTapped(MarkerId markerId) {
final Marker? tappedMarker = markers[markerId];
if (tappedMarker != null) {
setState(() {
final MarkerId? previousMarkerId = selectedMarker;
if (previousMarkerId != null && markers.containsKey(previousMarkerId)) {
final Marker resetOld = markers[previousMarkerId]!
.copyWith(iconParam: BitmapDescriptor.defaultMarker);
markers[previousMarkerId] = resetOld;
}
selectedMarker = markerId;
final Marker newMarker = tappedMarker.copyWith(
iconParam: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueGreen,
),
);
markers[markerId] = newMarker;
markerPosition = null;
});
}
}
void _onMarkerDrag(MarkerId markerId, LatLng newPosition) async {
setState(() {
this.markerPosition = newPosition;
});
}
void _onMarkerDragEnd(MarkerId markerId, LatLng newPosition) async {
final Marker? tappedMarker = markers[markerId];
if (tappedMarker != null) {
setState(() {
this.markerPosition = null;
});
await showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () => Navigator.of(context).pop(),
)
],
content: Padding(
padding: const EdgeInsets.symmetric(vertical: 66),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('Old position: ${tappedMarker.position}'),
Text('New position: $newPosition'),
],
)));
});
}
}
void _add() {
final int markerCount = markers.length;
if (markerCount == 12) {
return;
}
final String markerIdVal = 'marker_id_$_markerIdCounter';
_markerIdCounter++;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position: LatLng(
center.latitude + sin(_markerIdCounter * pi / 6.0) / 20.0,
center.longitude + cos(_markerIdCounter * pi / 6.0) / 20.0,
),
infoWindow: InfoWindow(title: markerIdVal, snippet: '*'),
onTap: () => _onMarkerTapped(markerId),
onDragEnd: (LatLng position) => _onMarkerDragEnd(markerId, position),
onDrag: (LatLng position) => _onMarkerDrag(markerId, position),
);
setState(() {
markers[markerId] = marker;
});
}
void _remove(MarkerId markerId) {
setState(() {
if (markers.containsKey(markerId)) {
markers.remove(markerId);
}
});
}
void _changePosition(MarkerId markerId) {
final Marker marker = markers[markerId]!;
final LatLng current = marker.position;
final Offset offset = Offset(
center.latitude - current.latitude,
center.longitude - current.longitude,
);
setState(() {
markers[markerId] = marker.copyWith(
positionParam: LatLng(
center.latitude + offset.dy,
center.longitude + offset.dx,
),
);
});
}
void _changeAnchor(MarkerId markerId) {
final Marker marker = markers[markerId]!;
final Offset currentAnchor = marker.anchor;
final Offset newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx);
setState(() {
markers[markerId] = marker.copyWith(
anchorParam: newAnchor,
);
});
}
Future<void> _changeInfoAnchor(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final Offset currentAnchor = marker.infoWindow.anchor;
final Offset newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx);
setState(() {
markers[markerId] = marker.copyWith(
infoWindowParam: marker.infoWindow.copyWith(
anchorParam: newAnchor,
),
);
});
}
Future<void> _toggleDraggable(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
draggableParam: !marker.draggable,
);
});
}
Future<void> _toggleFlat(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
flatParam: !marker.flat,
);
});
}
Future<void> _changeInfo(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final String newSnippet = marker.infoWindow.snippet! + '*';
setState(() {
markers[markerId] = marker.copyWith(
infoWindowParam: marker.infoWindow.copyWith(
snippetParam: newSnippet,
),
);
});
}
Future<void> _changeAlpha(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final double current = marker.alpha;
setState(() {
markers[markerId] = marker.copyWith(
alphaParam: current < 0.1 ? 1.0 : current * 0.75,
);
});
}
Future<void> _changeRotation(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final double current = marker.rotation;
setState(() {
markers[markerId] = marker.copyWith(
rotationParam: current == 330.0 ? 0.0 : current + 30.0,
);
});
}
Future<void> _toggleVisible(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
visibleParam: !marker.visible,
);
});
}
Future<void> _changeZIndex(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final double current = marker.zIndex;
setState(() {
markers[markerId] = marker.copyWith(
zIndexParam: current == 12.0 ? 0.0 : current + 1.0,
);
});
}
void _setMarkerIcon(MarkerId markerId, BitmapDescriptor assetIcon) {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
iconParam: assetIcon,
);
});
}
Future<BitmapDescriptor> _getAssetIcon(BuildContext context) async {
final Completer<BitmapDescriptor> bitmapIcon =
Completer<BitmapDescriptor>();
final ImageConfiguration config = createLocalImageConfiguration(context);
const AssetImage('assets/red_square.png')
.resolve(config)
.addListener(ImageStreamListener((ImageInfo image, bool sync) async {
final ByteData? bytes =
await image.image.toByteData(format: ImageByteFormat.png);
if (bytes == null) {
bitmapIcon.completeError(Exception('Unable to encode icon'));
return;
}
final BitmapDescriptor bitmap =
BitmapDescriptor.fromBytes(bytes.buffer.asUint8List());
bitmapIcon.complete(bitmap);
}));
return await bitmapIcon.future;
}
@override
Widget build(BuildContext context) {
final MarkerId? selectedId = selectedMarker;
return Stack(children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: LatLng(-33.852, 151.211),
zoom: 11.0,
),
markers: Set<Marker>.of(markers.values),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
TextButton(
child: const Text('Add'),
onPressed: _add,
),
TextButton(
child: const Text('Remove'),
onPressed:
selectedId == null ? null : () => _remove(selectedId),
),
],
),
Wrap(
alignment: WrapAlignment.spaceEvenly,
children: <Widget>[
TextButton(
child: const Text('change info'),
onPressed:
selectedId == null ? null : () => _changeInfo(selectedId),
),
TextButton(
child: const Text('change info anchor'),
onPressed: selectedId == null
? null
: () => _changeInfoAnchor(selectedId),
),
TextButton(
child: const Text('change alpha'),
onPressed:
selectedId == null ? null : () => _changeAlpha(selectedId),
),
TextButton(
child: const Text('change anchor'),
onPressed:
selectedId == null ? null : () => _changeAnchor(selectedId),
),
TextButton(
child: const Text('toggle draggable'),
onPressed: selectedId == null
? null
: () => _toggleDraggable(selectedId),
),
TextButton(
child: const Text('toggle flat'),
onPressed:
selectedId == null ? null : () => _toggleFlat(selectedId),
),
TextButton(
child: const Text('change position'),
onPressed: selectedId == null
? null
: () => _changePosition(selectedId),
),
TextButton(
child: const Text('change rotation'),
onPressed: selectedId == null
? null
: () => _changeRotation(selectedId),
),
TextButton(
child: const Text('toggle visible'),
onPressed: selectedId == null
? null
: () => _toggleVisible(selectedId),
),
TextButton(
child: const Text('change zIndex'),
onPressed:
selectedId == null ? null : () => _changeZIndex(selectedId),
),
TextButton(
child: const Text('set marker icon'),
onPressed: selectedId == null
? null
: () {
_getAssetIcon(context).then(
(BitmapDescriptor icon) {
_setMarkerIcon(selectedId, icon);
},
);
},
),
],
),
],
),
Visibility(
visible: markerPosition != null,
child: Container(
color: Colors.white70,
height: 30,
padding: EdgeInsets.only(left: 12, right: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
mainAxisSize: MainAxisSize.max,
children: [
markerPosition == null
? Container()
: Expanded(child: Text("lat: ${markerPosition!.latitude}")),
markerPosition == null
? Container()
: Expanded(child: Text("lng: ${markerPosition!.longitude}")),
],
),
),
),
]);
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart/0 | {'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart', 'repo_id': 'plugins', 'token_count': 6120} |
// 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'fake_maps_controllers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakePlatformViewsController fakePlatformViewsController =
FakePlatformViewsController();
setUpAll(() {
SystemChannels.platform_views.setMockMethodCallHandler(
fakePlatformViewsController.fakePlatformViewsMethodHandler);
});
setUp(() {
fakePlatformViewsController.reset();
});
testWidgets('Initial camera position', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.cameraPosition,
const CameraPosition(target: LatLng(10.0, 15.0)));
});
testWidgets('Initial camera position change is a no-op',
(WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 16.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.cameraPosition,
const CameraPosition(target: LatLng(10.0, 15.0)));
});
testWidgets('Can update compassEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
compassEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.compassEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
compassEnabled: true,
),
),
);
expect(platformGoogleMap.compassEnabled, true);
});
testWidgets('Can update mapToolbarEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
mapToolbarEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.mapToolbarEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
mapToolbarEnabled: true,
),
),
);
expect(platformGoogleMap.mapToolbarEnabled, true);
});
testWidgets('Can update cameraTargetBounds', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition:
const CameraPosition(target: LatLng(10.0, 15.0)),
cameraTargetBounds: CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(10.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(
platformGoogleMap.cameraTargetBounds,
CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(10.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition:
const CameraPosition(target: LatLng(10.0, 15.0)),
cameraTargetBounds: CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(16.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
),
),
),
);
expect(
platformGoogleMap.cameraTargetBounds,
CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(16.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
));
});
testWidgets('Can update mapType', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
mapType: MapType.hybrid,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.mapType, MapType.hybrid);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
mapType: MapType.satellite,
),
),
);
expect(platformGoogleMap.mapType, MapType.satellite);
});
testWidgets('Can update minMaxZoom', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
minMaxZoomPreference: MinMaxZoomPreference(1.0, 3.0),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.minMaxZoomPreference,
const MinMaxZoomPreference(1.0, 3.0));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
minMaxZoomPreference: MinMaxZoomPreference.unbounded,
),
),
);
expect(
platformGoogleMap.minMaxZoomPreference, MinMaxZoomPreference.unbounded);
});
testWidgets('Can update rotateGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
rotateGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.rotateGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
rotateGesturesEnabled: true,
),
),
);
expect(platformGoogleMap.rotateGesturesEnabled, true);
});
testWidgets('Can update scrollGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
scrollGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.scrollGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
scrollGesturesEnabled: true,
),
),
);
expect(platformGoogleMap.scrollGesturesEnabled, true);
});
testWidgets('Can update tiltGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
tiltGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.tiltGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
tiltGesturesEnabled: true,
),
),
);
expect(platformGoogleMap.tiltGesturesEnabled, true);
});
testWidgets('Can update trackCameraPosition', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.trackCameraPosition, false);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition:
const CameraPosition(target: LatLng(10.0, 15.0)),
onCameraMove: (CameraPosition position) {},
),
),
);
expect(platformGoogleMap.trackCameraPosition, true);
});
testWidgets('Can update zoomGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
zoomGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.zoomGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
zoomGesturesEnabled: true,
),
),
);
expect(platformGoogleMap.zoomGesturesEnabled, true);
});
testWidgets('Can update zoomControlsEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
zoomControlsEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.zoomControlsEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
zoomControlsEnabled: true,
),
),
);
expect(platformGoogleMap.zoomControlsEnabled, true);
});
testWidgets('Can update myLocationEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
myLocationEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.myLocationEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
myLocationEnabled: true,
),
),
);
expect(platformGoogleMap.myLocationEnabled, true);
});
testWidgets('Can update myLocationButtonEnabled',
(WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
myLocationEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.myLocationButtonEnabled, true);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
myLocationButtonEnabled: false,
),
),
);
expect(platformGoogleMap.myLocationButtonEnabled, false);
});
testWidgets('Is default padding 0', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.padding, <double>[0, 0, 0, 0]);
});
testWidgets('Can update padding', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.padding, <double>[0, 0, 0, 0]);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
padding: EdgeInsets.fromLTRB(10, 20, 30, 40),
),
),
);
expect(platformGoogleMap.padding, <double>[20, 10, 40, 30]);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
padding: EdgeInsets.fromLTRB(50, 60, 70, 80),
),
),
);
expect(platformGoogleMap.padding, <double>[60, 50, 80, 70]);
});
testWidgets('Can update traffic', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
trafficEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.trafficEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
trafficEnabled: true,
),
),
);
expect(platformGoogleMap.trafficEnabled, true);
});
testWidgets('Can update buildings', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
buildingsEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.buildingsEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
buildingsEnabled: true,
),
),
);
expect(platformGoogleMap.buildingsEnabled, true);
});
testWidgets(
'Default Android widget is AndroidView',
(WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(find.byType(AndroidView), findsOneWidget);
},
);
testWidgets('Use PlatformViewLink on Android', (WidgetTester tester) async {
final MethodChannelGoogleMapsFlutter platform =
GoogleMapsFlutterPlatform.instance as MethodChannelGoogleMapsFlutter;
platform.useAndroidViewSurface = true;
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(find.byType(PlatformViewLink), findsOneWidget);
platform.useAndroidViewSurface = false;
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart/0 | {'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart', 'repo_id': 'plugins', 'token_count': 7474} |
// 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.dart';
/// Callback that receives updates to the camera position.
///
/// This callback is triggered when the platform Google Map
/// registers a camera movement.
///
/// This is used in [GoogleMap.onCameraMove].
typedef void CameraPositionCallback(CameraPosition position);
/// Callback function taking a single argument.
typedef void ArgumentCallback<T>(T argument);
/// Mutable collection of [ArgumentCallback] instances, itself an [ArgumentCallback].
///
/// Additions and removals happening during a single [call] invocation do not
/// change who gets a callback until the next such invocation.
///
/// Optimized for the singleton case.
class ArgumentCallbacks<T> {
final List<ArgumentCallback<T>> _callbacks = <ArgumentCallback<T>>[];
/// Callback method. Invokes the corresponding method on each callback
/// in this collection.
///
/// The list of callbacks being invoked is computed at the start of the
/// method and is unaffected by any changes subsequently made to this
/// collection.
void call(T argument) {
final int length = _callbacks.length;
if (length == 1) {
_callbacks[0].call(argument);
} else if (0 < length) {
for (ArgumentCallback<T> callback
in List<ArgumentCallback<T>>.from(_callbacks)) {
callback(argument);
}
}
}
/// Adds a callback to this collection.
void add(ArgumentCallback<T> callback) {
assert(callback != null);
_callbacks.add(callback);
}
/// Removes a callback from this collection.
///
/// Does nothing, if the callback was not present.
void remove(ArgumentCallback<T> callback) {
_callbacks.remove(callback);
}
/// Whether this collection is empty.
bool get isEmpty => _callbacks.isEmpty;
/// Whether this collection is non-empty.
bool get isNotEmpty => _callbacks.isNotEmpty;
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/callbacks.dart/0 | {'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/callbacks.dart', 'repo_id': 'plugins', 'token_count': 584} |
// 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:ui' show hashValues;
import 'package:flutter/foundation.dart' show immutable;
/// Represents a point coordinate in the [GoogleMap]'s view.
///
/// The screen location is specified in screen pixels (not display pixels) relative
/// to the top left of the map, not top left of the whole screen. (x, y) = (0, 0)
/// corresponds to top-left of the [GoogleMap] not the whole screen.
@immutable
class ScreenCoordinate {
/// Creates an immutable representation of a point coordinate in the [GoogleMap]'s view.
const ScreenCoordinate({
required this.x,
required this.y,
});
/// Represents the number of pixels from the left of the [GoogleMap].
final int x;
/// Represents the number of pixels from the top of the [GoogleMap].
final int y;
/// Converts this object to something serializable in JSON.
Object toJson() {
return <String, int>{
"x": x,
"y": y,
};
}
@override
String toString() => '$runtimeType($x, $y)';
@override
bool operator ==(Object o) {
return o is ScreenCoordinate && o.x == x && o.y == y;
}
@override
int get hashCode => hashValues(x, y);
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/screen_coordinate.dart/0 | {'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/screen_coordinate.dart', 'repo_id': 'plugins', 'token_count': 408} |
// 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_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$BitmapDescriptor', () {
test('toJson / fromJson', () {
final descriptor =
BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan);
final json = descriptor.toJson();
// Rehydrate a new bitmap descriptor...
// ignore: deprecated_member_use_from_same_package
final descriptorFromJson = BitmapDescriptor.fromJson(json);
expect(descriptorFromJson, isNot(descriptor)); // New instance
expect(identical(descriptorFromJson.toJson(), json), isTrue); // Same JSON
});
group('fromJson validation', () {
group('type validation', () {
test('correct type', () {
expect(BitmapDescriptor.fromJson(['defaultMarker']),
isA<BitmapDescriptor>());
});
test('wrong type', () {
expect(() {
BitmapDescriptor.fromJson(['bogusType']);
}, throwsAssertionError);
});
});
group('defaultMarker', () {
test('hue is null', () {
expect(BitmapDescriptor.fromJson(['defaultMarker']),
isA<BitmapDescriptor>());
});
test('hue is number', () {
expect(BitmapDescriptor.fromJson(['defaultMarker', 158]),
isA<BitmapDescriptor>());
});
test('hue is not number', () {
expect(() {
BitmapDescriptor.fromJson(['defaultMarker', 'nope']);
}, throwsAssertionError);
});
test('hue is out of range', () {
expect(() {
BitmapDescriptor.fromJson(['defaultMarker', -1]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson(['defaultMarker', 361]);
}, throwsAssertionError);
});
});
group('fromBytes', () {
test('with bytes', () {
expect(
BitmapDescriptor.fromJson([
'fromBytes',
Uint8List.fromList([1, 2, 3])
]),
isA<BitmapDescriptor>());
});
test('without bytes', () {
expect(() {
BitmapDescriptor.fromJson(['fromBytes', null]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson(['fromBytes', []]);
}, throwsAssertionError);
});
});
group('fromAsset', () {
test('name is passed', () {
expect(BitmapDescriptor.fromJson(['fromAsset', 'some/path.png']),
isA<BitmapDescriptor>());
});
test('name cannot be null or empty', () {
expect(() {
BitmapDescriptor.fromJson(['fromAsset', null]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson(['fromAsset', '']);
}, throwsAssertionError);
});
test('package is passed', () {
expect(
BitmapDescriptor.fromJson(
['fromAsset', 'some/path.png', 'some_package']),
isA<BitmapDescriptor>());
});
test('package cannot be null or empty', () {
expect(() {
BitmapDescriptor.fromJson(['fromAsset', 'some/path.png', null]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson(['fromAsset', 'some/path.png', '']);
}, throwsAssertionError);
});
});
group('fromAssetImage', () {
test('name and dpi passed', () {
expect(
BitmapDescriptor.fromJson(
['fromAssetImage', 'some/path.png', 1.0]),
isA<BitmapDescriptor>());
});
test('name cannot be null or empty', () {
expect(() {
BitmapDescriptor.fromJson(['fromAssetImage', null, 1.0]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson(['fromAssetImage', '', 1.0]);
}, throwsAssertionError);
});
test('dpi must be number', () {
expect(() {
BitmapDescriptor.fromJson(
['fromAssetImage', 'some/path.png', null]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson(
['fromAssetImage', 'some/path.png', 'one']);
}, throwsAssertionError);
});
test('with optional [width, height] List', () {
expect(
BitmapDescriptor.fromJson([
'fromAssetImage',
'some/path.png',
1.0,
[640, 480]
]),
isA<BitmapDescriptor>());
});
test(
'optional [width, height] List cannot be null or not contain 2 elements',
() {
expect(() {
BitmapDescriptor.fromJson(
['fromAssetImage', 'some/path.png', 1.0, null]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson(
['fromAssetImage', 'some/path.png', 1.0, []]);
}, throwsAssertionError);
expect(() {
BitmapDescriptor.fromJson([
'fromAssetImage',
'some/path.png',
1.0,
[640, 480, 1024]
]);
}, throwsAssertionError);
});
});
});
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart/0 | {'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart', 'repo_id': 'plugins', 'token_count': 2860} |
name: google_sign_in_web_integration_tests
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=2.2.0"
dependencies:
flutter:
sdk: flutter
google_sign_in_web:
path: ../
dev_dependencies:
http: ^0.13.0
js: ^0.6.3
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
| plugins/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml/0 | {'file_path': 'plugins/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml', 'repo_id': 'plugins', 'token_count': 171} |
include: ../../../analysis_options_legacy.yaml
| plugins/packages/image_picker/image_picker/analysis_options.yaml/0 | {'file_path': 'plugins/packages/image_picker/image_picker/analysis_options.yaml', 'repo_id': 'plugins', 'token_count': 16} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: deprecated_member_use_from_same_package
// This file preserves the tests for the deprecated methods as they were before
// the migration. See image_picker_test.dart for the current tests.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$ImagePicker', () {
const MethodChannel channel =
MethodChannel('plugins.flutter.io/image_picker');
final List<MethodCall> log = <MethodCall>[];
final picker = ImagePicker();
test('ImagePicker platform instance overrides the actual platform used',
() {
final ImagePickerPlatform savedPlatform = ImagePickerPlatform.instance;
final MockPlatform mockPlatform = MockPlatform();
ImagePickerPlatform.instance = mockPlatform;
expect(ImagePicker.platform, mockPlatform);
ImagePickerPlatform.instance = savedPlatform;
});
group('#Single image/video', () {
setUp(() {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
log.add(methodCall);
return '';
});
log.clear();
});
group('#pickImage', () {
test('passes the image source argument correctly', () async {
await picker.getImage(source: ImageSource.camera);
await picker.getImage(source: ImageSource.gallery);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 1,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0
}),
],
);
});
test('passes the width and height arguments correctly', () async {
await picker.getImage(source: ImageSource.camera);
await picker.getImage(
source: ImageSource.camera,
maxWidth: 10.0,
);
await picker.getImage(
source: ImageSource.camera,
maxHeight: 10.0,
);
await picker.getImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.getImage(
source: ImageSource.camera, maxWidth: 10.0, imageQuality: 70);
await picker.getImage(
source: ImageSource.camera, maxHeight: 10.0, imageQuality: 70);
await picker.getImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
imageQuality: 70);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'cameraDevice': 0
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'cameraDevice': 0
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'cameraDevice': 0
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'cameraDevice': 0
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'cameraDevice': 0
}),
],
);
});
test('does not accept a negative width or height argument', () {
expect(
picker.getImage(source: ImageSource.camera, maxWidth: -1.0),
throwsArgumentError,
);
expect(
picker.getImage(source: ImageSource.camera, maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
channel.setMockMethodCallHandler((MethodCall methodCall) => null);
expect(await picker.getImage(source: ImageSource.gallery), isNull);
expect(await picker.getImage(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
await picker.getImage(source: ImageSource.camera);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 1,
}),
],
);
});
});
group('#pickVideo', () {
test('passes the image source argument correctly', () async {
await picker.getVideo(source: ImageSource.camera);
await picker.getVideo(source: ImageSource.gallery);
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'cameraDevice': 0,
'maxDuration': null,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 1,
'cameraDevice': 0,
'maxDuration': null,
}),
],
);
});
test('passes the duration argument correctly', () async {
await picker.getVideo(source: ImageSource.camera);
await picker.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 10));
await picker.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(minutes: 1));
await picker.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(hours: 1));
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': null,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 10,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 60,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 3600,
'cameraDevice': 0,
}),
],
);
});
test('handles a null video path response gracefully', () async {
channel.setMockMethodCallHandler((MethodCall methodCall) => null);
expect(await picker.getVideo(source: ImageSource.gallery), isNull);
expect(await picker.getVideo(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
await picker.getVideo(source: ImageSource.camera);
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'cameraDevice': 0,
'maxDuration': null,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': null,
'cameraDevice': 1,
}),
],
);
});
});
group('#retrieveLostData', () {
test('retrieveLostData get success response', () async {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return <String, String>{
'type': 'image',
'path': '/example/path',
};
});
final LostData response = await picker.getLostData();
expect(response.type, RetrieveType.image);
expect(response.file!.path, '/example/path');
});
test('retrieveLostData get error response', () async {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return <String, String>{
'type': 'video',
'errorCode': 'test_error_code',
'errorMessage': 'test_error_message',
};
});
final LostData response = await picker.getLostData();
expect(response.type, RetrieveType.video);
expect(response.exception!.code, 'test_error_code');
expect(response.exception!.message, 'test_error_message');
});
test('retrieveLostData get null response', () async {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return null;
});
expect((await picker.getLostData()).isEmpty, true);
});
test('retrieveLostData get both path and error should throw', () async {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return <String, String>{
'type': 'video',
'errorCode': 'test_error_code',
'errorMessage': 'test_error_message',
'path': '/example/path',
};
});
expect(picker.getLostData(), throwsAssertionError);
});
});
});
group('Multi images', () {
setUp(() {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
log.add(methodCall);
return [];
});
log.clear();
});
group('#pickMultiImage', () {
test('passes the width and height arguments correctly', () async {
await picker.getMultiImage();
await picker.getMultiImage(
maxWidth: 10.0,
);
await picker.getMultiImage(
maxHeight: 10.0,
);
await picker.getMultiImage(
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.getMultiImage(
maxWidth: 10.0,
imageQuality: 70,
);
await picker.getMultiImage(
maxHeight: 10.0,
imageQuality: 70,
);
await picker.getMultiImage(
maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70);
expect(
log,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
}),
],
);
});
test('does not accept a negative width or height argument', () {
expect(
picker.getMultiImage(maxWidth: -1.0),
throwsArgumentError,
);
expect(
picker.getMultiImage(maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
channel.setMockMethodCallHandler((MethodCall methodCall) => null);
expect(await picker.getMultiImage(), isNull);
expect(await picker.getMultiImage(), isNull);
});
});
});
});
}
class MockPlatform extends Mock
with MockPlatformInterfaceMixin
implements ImagePickerPlatform {}
| plugins/packages/image_picker/image_picker/test/image_picker_deprecated_test.dart/0 | {'file_path': 'plugins/packages/image_picker/image_picker/test/image_picker_deprecated_test.dart', 'repo_id': 'plugins', 'token_count': 7770} |
// 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:math';
import 'dart:ui';
import 'package:image_picker_for_web/src/image_resizer_utils.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'dart:html' as html;
/// Helper class that resizes images.
class ImageResizer {
/// Resizes the image if needed.
/// (Does not support gif images)
Future<XFile> resizeImageIfNeeded(XFile file, double? maxWidth,
double? maxHeight, int? imageQuality) async {
if (!imageResizeNeeded(maxWidth, maxHeight, imageQuality) ||
file.mimeType == "image/gif") {
// Implement maxWidth and maxHeight for image/gif
return file;
}
try {
final imageElement = await loadImage(file.path);
final canvas = resizeImageElement(imageElement, maxWidth, maxHeight);
final resizedImage = await writeCanvasToFile(file, canvas, imageQuality);
html.Url.revokeObjectUrl(file.path);
return resizedImage;
} catch (e) {
return file;
}
}
/// function that loads the blobUrl into an imageElement
Future<html.ImageElement> loadImage(String blobUrl) {
final imageLoadCompleter = Completer<html.ImageElement>();
final imageElement = html.ImageElement();
imageElement.src = blobUrl;
imageElement.onLoad.listen((event) {
imageLoadCompleter.complete(imageElement);
});
imageElement.onError.listen((event) {
final exception = ("Error while loading image.");
imageElement.remove();
imageLoadCompleter.completeError(exception);
});
return imageLoadCompleter.future;
}
/// Draws image to a canvas while resizing the image to fit the [maxWidth],[maxHeight] constraints
html.CanvasElement resizeImageElement(
html.ImageElement source, double? maxWidth, double? maxHeight) {
final newImageSize = calculateSizeOfDownScaledImage(
Size(source.width!.toDouble(), source.height!.toDouble()),
maxWidth,
maxHeight);
final canvas = html.CanvasElement();
canvas.width = newImageSize.width.toInt();
canvas.height = newImageSize.height.toInt();
final context = canvas.context2D;
if (maxHeight == null && maxWidth == null) {
context.drawImage(source, 0, 0);
} else {
context.drawImageScaled(source, 0, 0, canvas.width!, canvas.height!);
}
return canvas;
}
/// function that converts a canvas element to Xfile
/// [imageQuality] is only supported for jpeg and webp images.
Future<XFile> writeCanvasToFile(
XFile originalFile, html.CanvasElement canvas, int? imageQuality) async {
final calculatedImageQuality = ((min(imageQuality ?? 100, 100)) / 100.0);
final blob =
await canvas.toBlob(originalFile.mimeType, calculatedImageQuality);
return XFile(html.Url.createObjectUrlFromBlob(blob),
mimeType: originalFile.mimeType,
name: "scaled_" + originalFile.name,
lastModified: DateTime.now(),
length: blob.size);
}
}
| plugins/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart/0 | {'file_path': 'plugins/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart', 'repo_id': 'plugins', 'token_count': 1094} |
name: in_app_purchase_android_example
description: Demonstrates how to use the in_app_purchase_android plugin.
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=1.9.1+hotfix.2"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.0
in_app_purchase_android:
# When depending on this package from a real application you should use:
# in_app_purchase_android: ^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: ../
in_app_purchase_platform_interface: ^1.0.0
dev_dependencies:
flutter_driver:
sdk: flutter
integration_test:
sdk: flutter
pedantic: ^1.10.0
flutter:
uses-material-design: true
| plugins/packages/in_app_purchase/in_app_purchase_android/example/pubspec.yaml/0 | {'file_path': 'plugins/packages/in_app_purchase/in_app_purchase_android/example/pubspec.yaml', 'repo_id': 'plugins', 'token_count': 318} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../../billing_client_wrappers.dart';
import '../in_app_purchase_android_platform.dart';
/// The class represents the information of a purchase made using Google Play.
class GooglePlayPurchaseDetails extends PurchaseDetails {
/// Creates a new Google Play specific purchase details object with the
/// provided details.
GooglePlayPurchaseDetails({
String? purchaseID,
required String productID,
required PurchaseVerificationData verificationData,
required String? transactionDate,
required this.billingClientPurchase,
required PurchaseStatus status,
}) : super(
productID: productID,
purchaseID: purchaseID,
transactionDate: transactionDate,
verificationData: verificationData,
status: status,
) {
this.pendingCompletePurchase = !billingClientPurchase.isAcknowledged;
}
/// Points back to the [PurchaseWrapper] which was used to generate this
/// [GooglePlayPurchaseDetails] object.
final PurchaseWrapper billingClientPurchase;
/// Generate a [PurchaseDetails] object based on an Android [Purchase] object.
factory GooglePlayPurchaseDetails.fromPurchase(PurchaseWrapper purchase) {
final GooglePlayPurchaseDetails purchaseDetails = GooglePlayPurchaseDetails(
purchaseID: purchase.orderId,
productID: purchase.sku,
verificationData: PurchaseVerificationData(
localVerificationData: purchase.originalJson,
serverVerificationData: purchase.purchaseToken,
source: kIAPSource),
transactionDate: purchase.purchaseTime.toString(),
billingClientPurchase: purchase,
status: PurchaseStateConverter().toPurchaseStatus(purchase.purchaseState),
);
if (purchaseDetails.status == PurchaseStatus.error) {
purchaseDetails.error = IAPError(
source: kIAPSource,
code: kPurchaseErrorCode,
message: '',
);
}
return purchaseDetails;
}
}
| plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart/0 | {'file_path': 'plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart', 'repo_id': 'plugins', 'token_count': 694} |
name: quick_actions_example
description: Demonstrates how to use the quick_actions plugin.
publish_to: none
environment:
sdk: ">=2.15.0 <3.0.0"
flutter: ">=2.8.0"
dependencies:
flutter:
sdk: flutter
quick_actions_android:
# When depending on this package from a real application you should use:
# quick_actions_android: ^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: ../
dev_dependencies:
espresso: ^0.1.0+2
flutter_driver:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/quick_actions/quick_actions_android/example/pubspec.yaml/0 | {'file_path': 'plugins/packages/quick_actions/quick_actions_android/example/pubspec.yaml', 'repo_id': 'plugins', 'token_count': 265} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_ios/shared_preferences_ios.dart';
import 'package:shared_preferences_platform_interface/method_channel_shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group(MethodChannelSharedPreferencesStore, () {
const MethodChannel channel = MethodChannel(
'plugins.flutter.io/shared_preferences_ios',
);
const Map<String, Object> kTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.Bool': true,
'flutter.Int': 42,
'flutter.Double': 3.14159,
'flutter.StringList': <String>['foo', 'bar'],
};
// Create a dummy in-memory implementation to back the mocked method channel
// API to simplify validation of the expected calls.
late InMemorySharedPreferencesStore testData;
final List<MethodCall> log = <MethodCall>[];
late SharedPreferencesStorePlatform store;
setUp(() async {
testData = InMemorySharedPreferencesStore.empty();
channel.setMockMethodCallHandler((MethodCall methodCall) async {
log.add(methodCall);
if (methodCall.method == 'getAll') {
return await testData.getAll();
}
if (methodCall.method == 'remove') {
final String key = methodCall.arguments['key'] as String;
return await testData.remove(key);
}
if (methodCall.method == 'clear') {
return await testData.clear();
}
final RegExp setterRegExp = RegExp(r'set(.*)');
final Match? match = setterRegExp.matchAsPrefix(methodCall.method);
if (match?.groupCount == 1) {
final String valueType = match!.group(1)!;
final String key = methodCall.arguments['key'] as String;
final Object value = methodCall.arguments['value'] as Object;
return await testData.setValue(valueType, key, value);
}
fail('Unexpected method call: ${methodCall.method}');
});
log.clear();
});
test('registered instance', () {
SharedPreferencesIOS.registerWith();
expect(
SharedPreferencesStorePlatform.instance, isA<SharedPreferencesIOS>());
});
test('getAll', () async {
store = SharedPreferencesIOS();
testData = InMemorySharedPreferencesStore.withData(kTestValues);
expect(await store.getAll(), kTestValues);
expect(log.single.method, 'getAll');
});
test('remove', () async {
store = SharedPreferencesIOS();
testData = InMemorySharedPreferencesStore.withData(kTestValues);
expect(await store.remove('flutter.String'), true);
expect(await store.remove('flutter.Bool'), true);
expect(await store.remove('flutter.Int'), true);
expect(await store.remove('flutter.Double'), true);
expect(await testData.getAll(), <String, dynamic>{
'flutter.StringList': <String>['foo', 'bar'],
});
expect(log, hasLength(4));
for (final MethodCall call in log) {
expect(call.method, 'remove');
}
});
test('setValue', () async {
store = SharedPreferencesIOS();
expect(await testData.getAll(), isEmpty);
for (final String key in kTestValues.keys) {
final Object value = kTestValues[key]!;
expect(await store.setValue(key.split('.').last, key, value), true);
}
expect(await testData.getAll(), kTestValues);
expect(log, hasLength(5));
expect(log[0].method, 'setString');
expect(log[1].method, 'setBool');
expect(log[2].method, 'setInt');
expect(log[3].method, 'setDouble');
expect(log[4].method, 'setStringList');
});
test('clear', () async {
store = SharedPreferencesIOS();
testData = InMemorySharedPreferencesStore.withData(kTestValues);
expect(await testData.getAll(), isNotEmpty);
expect(await store.clear(), true);
expect(await testData.getAll(), isEmpty);
expect(log.single.method, 'clear');
});
});
}
| plugins/packages/shared_preferences/shared_preferences_ios/test/shared_preferences_ios_test.dart/0 | {'file_path': 'plugins/packages/shared_preferences/shared_preferences_ios/test/shared_preferences_ios_test.dart', 'repo_id': 'plugins', 'token_count': 1660} |
// 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/services.dart';
import 'android_webview.dart';
import 'android_webview.pigeon.dart';
import 'instance_manager.dart';
/// Converts [WebResourceRequestData] to [WebResourceRequest]
WebResourceRequest _toWebResourceRequest(WebResourceRequestData data) {
return WebResourceRequest(
url: data.url!,
isForMainFrame: data.isForMainFrame!,
isRedirect: data.isRedirect,
hasGesture: data.hasGesture!,
method: data.method!,
requestHeaders:
data.requestHeaders?.cast<String, String>() ?? <String, String>{},
);
}
/// Converts [WebResourceErrorData] to [WebResourceError].
WebResourceError _toWebResourceError(WebResourceErrorData data) {
return WebResourceError(
errorCode: data.errorCode!,
description: data.description!,
);
}
/// Handles initialization of Flutter APIs for Android WebView.
class AndroidWebViewFlutterApis {
/// Creates a [AndroidWebViewFlutterApis].
AndroidWebViewFlutterApis({
DownloadListenerFlutterApiImpl? downloadListenerFlutterApi,
WebViewClientFlutterApiImpl? webViewClientFlutterApi,
WebChromeClientFlutterApiImpl? webChromeClientFlutterApi,
JavaScriptChannelFlutterApiImpl? javaScriptChannelFlutterApi,
}) {
this.downloadListenerFlutterApi =
downloadListenerFlutterApi ?? DownloadListenerFlutterApiImpl();
this.webViewClientFlutterApi =
webViewClientFlutterApi ?? WebViewClientFlutterApiImpl();
this.webChromeClientFlutterApi =
webChromeClientFlutterApi ?? WebChromeClientFlutterApiImpl();
this.javaScriptChannelFlutterApi =
javaScriptChannelFlutterApi ?? JavaScriptChannelFlutterApiImpl();
}
static bool _haveBeenSetUp = false;
/// Mutable instance containing all Flutter Apis for Android WebView.
///
/// This should only be changed for testing purposes.
static AndroidWebViewFlutterApis instance = AndroidWebViewFlutterApis();
/// Flutter Api for [DownloadListener].
late final DownloadListenerFlutterApiImpl downloadListenerFlutterApi;
/// Flutter Api for [WebViewClient].
late final WebViewClientFlutterApiImpl webViewClientFlutterApi;
/// Flutter Api for [WebChromeClient].
late final WebChromeClientFlutterApiImpl webChromeClientFlutterApi;
/// Flutter Api for [JavaScriptChannel].
late final JavaScriptChannelFlutterApiImpl javaScriptChannelFlutterApi;
/// Ensures all the Flutter APIs have been setup to receive calls from native code.
void ensureSetUp() {
if (!_haveBeenSetUp) {
DownloadListenerFlutterApi.setup(downloadListenerFlutterApi);
WebViewClientFlutterApi.setup(webViewClientFlutterApi);
WebChromeClientFlutterApi.setup(webChromeClientFlutterApi);
JavaScriptChannelFlutterApi.setup(javaScriptChannelFlutterApi);
_haveBeenSetUp = true;
}
}
}
/// Host api implementation for [WebView].
class WebViewHostApiImpl extends WebViewHostApi {
/// Constructs a [WebViewHostApiImpl].
WebViewHostApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
/// Helper method to convert instances ids to objects.
Future<void> createFromInstance(WebView instance) async {
final int? instanceId = instanceManager.tryAddInstance(instance);
if (instanceId != null) {
return create(instanceId, instance.useHybridComposition);
}
}
/// Helper method to convert instances ids to objects.
Future<void> disposeFromInstance(WebView instance) async {
final int? instanceId = instanceManager.getInstanceId(instance);
if (instanceId != null) {
await dispose(instanceId);
}
instanceManager.removeInstance(instance);
}
/// Helper method to convert the instances ids to objects.
Future<void> loadDataFromInstance(
WebView instance,
String data,
String mimeType,
String encoding,
) {
return loadData(
instanceManager.getInstanceId(instance)!,
data,
mimeType,
encoding,
);
}
/// Helper method to convert instances ids to objects.
Future<void> loadDataWithBaseUrlFromInstance(
WebView instance,
String baseUrl,
String data,
String mimeType,
String encoding,
String historyUrl,
) {
return loadDataWithBaseUrl(
instanceManager.getInstanceId(instance)!,
baseUrl,
data,
mimeType,
encoding,
historyUrl,
);
}
/// Helper method to convert instances ids to objects.
Future<void> loadUrlFromInstance(
WebView instance,
String url,
Map<String, String> headers,
) {
return loadUrl(instanceManager.getInstanceId(instance)!, url, headers);
}
/// Helper method to convert instances ids to objects.
Future<void> postUrlFromInstance(
WebView instance,
String url,
Uint8List data,
) {
return postUrl(instanceManager.getInstanceId(instance)!, url, data);
}
/// Helper method to convert instances ids to objects.
Future<String> getUrlFromInstance(WebView instance) {
return getUrl(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<bool> canGoBackFromInstance(WebView instance) {
return canGoBack(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<bool> canGoForwardFromInstance(WebView instance) {
return canGoForward(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<void> goBackFromInstance(WebView instance) {
return goBack(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<void> goForwardFromInstance(WebView instance) {
return goForward(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<void> reloadFromInstance(WebView instance) {
return reload(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<void> clearCacheFromInstance(WebView instance, bool includeDiskFiles) {
return clearCache(
instanceManager.getInstanceId(instance)!,
includeDiskFiles,
);
}
/// Helper method to convert instances ids to objects.
Future<String> evaluateJavascriptFromInstance(
WebView instance,
String javascriptString,
) {
return evaluateJavascript(
instanceManager.getInstanceId(instance)!, javascriptString);
}
/// Helper method to convert instances ids to objects.
Future<String> getTitleFromInstance(WebView instance) {
return getTitle(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<void> scrollToFromInstance(WebView instance, int x, int y) {
return scrollTo(instanceManager.getInstanceId(instance)!, x, y);
}
/// Helper method to convert instances ids to objects.
Future<void> scrollByFromInstance(WebView instance, int x, int y) {
return scrollBy(instanceManager.getInstanceId(instance)!, x, y);
}
/// Helper method to convert instances ids to objects.
Future<int> getScrollXFromInstance(WebView instance) {
return getScrollX(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<int> getScrollYFromInstance(WebView instance) {
return getScrollY(instanceManager.getInstanceId(instance)!);
}
/// Helper method to convert instances ids to objects.
Future<void> setWebViewClientFromInstance(
WebView instance,
WebViewClient webViewClient,
) {
return setWebViewClient(
instanceManager.getInstanceId(instance)!,
instanceManager.getInstanceId(webViewClient)!,
);
}
/// Helper method to convert instances ids to objects.
Future<void> addJavaScriptChannelFromInstance(
WebView instance,
JavaScriptChannel javaScriptChannel,
) {
return addJavaScriptChannel(
instanceManager.getInstanceId(instance)!,
instanceManager.getInstanceId(javaScriptChannel)!,
);
}
/// Helper method to convert instances ids to objects.
Future<void> removeJavaScriptChannelFromInstance(
WebView instance,
JavaScriptChannel javaScriptChannel,
) {
return removeJavaScriptChannel(
instanceManager.getInstanceId(instance)!,
instanceManager.getInstanceId(javaScriptChannel)!,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setDownloadListenerFromInstance(
WebView instance,
DownloadListener listener,
) {
return setDownloadListener(
instanceManager.getInstanceId(instance)!,
instanceManager.getInstanceId(listener)!,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setWebChromeClientFromInstance(
WebView instance,
WebChromeClient client,
) {
return setWebChromeClient(
instanceManager.getInstanceId(instance)!,
instanceManager.getInstanceId(client)!,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setBackgroundColorFromInstance(WebView instance, int color) {
return setBackgroundColor(instanceManager.getInstanceId(instance)!, color);
}
}
/// Host api implementation for [WebSettings].
class WebSettingsHostApiImpl extends WebSettingsHostApi {
/// Constructs a [WebSettingsHostApiImpl].
WebSettingsHostApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
/// Helper method to convert instances ids to objects.
Future<void> createFromInstance(WebSettings instance, WebView webView) async {
final int? instanceId = instanceManager.tryAddInstance(instance);
if (instanceId != null) {
return create(
instanceId,
instanceManager.getInstanceId(webView)!,
);
}
}
/// Helper method to convert instances ids to objects.
Future<void> disposeFromInstance(WebSettings instance) async {
final int? instanceId = instanceManager.removeInstance(instance);
if (instanceId != null) {
return dispose(instanceId);
}
}
/// Helper method to convert instances ids to objects.
Future<void> setDomStorageEnabledFromInstance(
WebSettings instance,
bool flag,
) {
return setDomStorageEnabled(instanceManager.getInstanceId(instance)!, flag);
}
/// Helper method to convert instances ids to objects.
Future<void> setJavaScriptCanOpenWindowsAutomaticallyFromInstance(
WebSettings instance,
bool flag,
) {
return setJavaScriptCanOpenWindowsAutomatically(
instanceManager.getInstanceId(instance)!,
flag,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setSupportMultipleWindowsFromInstance(
WebSettings instance,
bool support,
) {
return setSupportMultipleWindows(
instanceManager.getInstanceId(instance)!, support);
}
/// Helper method to convert instances ids to objects.
Future<void> setJavaScriptEnabledFromInstance(
WebSettings instance,
bool flag,
) {
return setJavaScriptEnabled(
instanceManager.getInstanceId(instance)!,
flag,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setUserAgentStringFromInstance(
WebSettings instance,
String userAgentString,
) {
return setUserAgentString(
instanceManager.getInstanceId(instance)!,
userAgentString,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setMediaPlaybackRequiresUserGestureFromInstance(
WebSettings instance,
bool require,
) {
return setMediaPlaybackRequiresUserGesture(
instanceManager.getInstanceId(instance)!,
require,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setSupportZoomFromInstance(
WebSettings instance,
bool support,
) {
return setSupportZoom(instanceManager.getInstanceId(instance)!, support);
}
/// Helper method to convert instances ids to objects.
Future<void> setLoadWithOverviewModeFromInstance(
WebSettings instance,
bool overview,
) {
return setLoadWithOverviewMode(
instanceManager.getInstanceId(instance)!,
overview,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setUseWideViewPortFromInstance(
WebSettings instance,
bool use,
) {
return setUseWideViewPort(instanceManager.getInstanceId(instance)!, use);
}
/// Helper method to convert instances ids to objects.
Future<void> setDisplayZoomControlsFromInstance(
WebSettings instance,
bool enabled,
) {
return setDisplayZoomControls(
instanceManager.getInstanceId(instance)!,
enabled,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setBuiltInZoomControlsFromInstance(
WebSettings instance,
bool enabled,
) {
return setBuiltInZoomControls(
instanceManager.getInstanceId(instance)!,
enabled,
);
}
/// Helper method to convert instances ids to objects.
Future<void> setAllowFileAccessFromInstance(
WebSettings instance,
bool enabled,
) {
return setAllowFileAccess(
instanceManager.getInstanceId(instance)!,
enabled,
);
}
}
/// Host api implementation for [JavaScriptChannel].
class JavaScriptChannelHostApiImpl extends JavaScriptChannelHostApi {
/// Constructs a [JavaScriptChannelHostApiImpl].
JavaScriptChannelHostApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
/// Helper method to convert instances ids to objects.
Future<void> createFromInstance(JavaScriptChannel instance) async {
final int? instanceId = instanceManager.tryAddInstance(instance);
if (instanceId != null) {
return create(instanceId, instance.channelName);
}
}
}
/// Flutter api implementation for [JavaScriptChannel].
class JavaScriptChannelFlutterApiImpl extends JavaScriptChannelFlutterApi {
/// Constructs a [JavaScriptChannelFlutterApiImpl].
JavaScriptChannelFlutterApiImpl({InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
@override
void dispose(int instanceId) {
instanceManager.removeInstance(instanceId);
}
@override
void postMessage(int instanceId, String message) {
final JavaScriptChannel? instance =
instanceManager.getInstance(instanceId) as JavaScriptChannel?;
assert(
instance != null,
'InstanceManager does not contain an JavaScriptChannel with instanceId: $instanceId',
);
instance!.postMessage(message);
}
}
/// Host api implementation for [WebViewClient].
class WebViewClientHostApiImpl extends WebViewClientHostApi {
/// Constructs a [WebViewClientHostApiImpl].
WebViewClientHostApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
/// Helper method to convert instances ids to objects.
Future<void> createFromInstance(WebViewClient instance) async {
final int? instanceId = instanceManager.tryAddInstance(instance);
if (instanceId != null) {
return create(instanceId, instance.shouldOverrideUrlLoading);
}
}
}
/// Flutter api implementation for [WebViewClient].
class WebViewClientFlutterApiImpl extends WebViewClientFlutterApi {
/// Constructs a [WebViewClientFlutterApiImpl].
WebViewClientFlutterApiImpl({InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
@override
void dispose(int instanceId) {
instanceManager.removeInstance(instanceId);
}
@override
void onPageFinished(int instanceId, int webViewInstanceId, String url) {
final WebViewClient? instance =
instanceManager.getInstance(instanceId) as WebViewClient?;
final WebView? webViewInstance =
instanceManager.getInstance(webViewInstanceId) as WebView?;
assert(
instance != null,
'InstanceManager does not contain an WebViewClient with instanceId: $instanceId',
);
assert(
webViewInstance != null,
'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId',
);
instance!.onPageFinished(webViewInstance!, url);
}
@override
void onPageStarted(int instanceId, int webViewInstanceId, String url) {
final WebViewClient? instance =
instanceManager.getInstance(instanceId) as WebViewClient?;
final WebView? webViewInstance =
instanceManager.getInstance(webViewInstanceId) as WebView?;
assert(
instance != null,
'InstanceManager does not contain an WebViewClient with instanceId: $instanceId',
);
assert(
webViewInstance != null,
'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId',
);
instance!.onPageStarted(webViewInstance!, url);
}
@override
void onReceivedError(
int instanceId,
int webViewInstanceId,
int errorCode,
String description,
String failingUrl,
) {
final WebViewClient? instance =
instanceManager.getInstance(instanceId) as WebViewClient?;
final WebView? webViewInstance =
instanceManager.getInstance(webViewInstanceId) as WebView?;
assert(
instance != null,
'InstanceManager does not contain an WebViewClient with instanceId: $instanceId',
);
assert(
webViewInstance != null,
'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId',
);
// ignore: deprecated_member_use_from_same_package
instance!.onReceivedError(
webViewInstance!,
errorCode,
description,
failingUrl,
);
}
@override
void onReceivedRequestError(
int instanceId,
int webViewInstanceId,
WebResourceRequestData request,
WebResourceErrorData error,
) {
final WebViewClient? instance =
instanceManager.getInstance(instanceId) as WebViewClient?;
final WebView? webViewInstance =
instanceManager.getInstance(webViewInstanceId) as WebView?;
assert(
instance != null,
'InstanceManager does not contain an WebViewClient with instanceId: $instanceId',
);
assert(
webViewInstance != null,
'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId',
);
instance!.onReceivedRequestError(
webViewInstance!,
_toWebResourceRequest(request),
_toWebResourceError(error),
);
}
@override
void requestLoading(
int instanceId,
int webViewInstanceId,
WebResourceRequestData request,
) {
final WebViewClient? instance =
instanceManager.getInstance(instanceId) as WebViewClient?;
final WebView? webViewInstance =
instanceManager.getInstance(webViewInstanceId) as WebView?;
assert(
instance != null,
'InstanceManager does not contain an WebViewClient with instanceId: $instanceId',
);
assert(
webViewInstance != null,
'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId',
);
instance!.requestLoading(webViewInstance!, _toWebResourceRequest(request));
}
@override
void urlLoading(
int instanceId,
int webViewInstanceId,
String url,
) {
final WebViewClient? instance =
instanceManager.getInstance(instanceId) as WebViewClient?;
final WebView? webViewInstance =
instanceManager.getInstance(webViewInstanceId) as WebView?;
assert(
instance != null,
'InstanceManager does not contain an WebViewClient with instanceId: $instanceId',
);
assert(
webViewInstance != null,
'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId',
);
instance!.urlLoading(webViewInstance!, url);
}
}
/// Host api implementation for [DownloadListener].
class DownloadListenerHostApiImpl extends DownloadListenerHostApi {
/// Constructs a [DownloadListenerHostApiImpl].
DownloadListenerHostApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
/// Helper method to convert instances ids to objects.
Future<void> createFromInstance(DownloadListener instance) async {
final int? instanceId = instanceManager.tryAddInstance(instance);
if (instanceId != null) {
return create(instanceId);
}
}
}
/// Flutter api implementation for [DownloadListener].
class DownloadListenerFlutterApiImpl extends DownloadListenerFlutterApi {
/// Constructs a [DownloadListenerFlutterApiImpl].
DownloadListenerFlutterApiImpl({InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
@override
void dispose(int instanceId) {
instanceManager.removeInstance(instanceId);
}
@override
void onDownloadStart(
int instanceId,
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
) {
final DownloadListener? instance =
instanceManager.getInstance(instanceId) as DownloadListener?;
assert(
instance != null,
'InstanceManager does not contain an DownloadListener with instanceId: $instanceId',
);
instance!.onDownloadStart(
url,
userAgent,
contentDisposition,
mimetype,
contentLength,
);
}
}
/// Host api implementation for [DownloadListener].
class WebChromeClientHostApiImpl extends WebChromeClientHostApi {
/// Constructs a [WebChromeClientHostApiImpl].
WebChromeClientHostApiImpl({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
/// Helper method to convert instances ids to objects.
Future<void> createFromInstance(
WebChromeClient instance,
WebViewClient webViewClient,
) async {
final int? instanceId = instanceManager.tryAddInstance(instance);
if (instanceId != null) {
return create(instanceId, instanceManager.getInstanceId(webViewClient)!);
}
}
}
/// Flutter api implementation for [DownloadListener].
class WebChromeClientFlutterApiImpl extends WebChromeClientFlutterApi {
/// Constructs a [DownloadListenerFlutterApiImpl].
WebChromeClientFlutterApiImpl({InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? InstanceManager.instance;
}
/// Maintains instances stored to communicate with java objects.
late final InstanceManager instanceManager;
@override
void dispose(int instanceId) {
instanceManager.removeInstance(instanceId);
}
@override
void onProgressChanged(int instanceId, int webViewInstanceId, int progress) {
final WebChromeClient? instance =
instanceManager.getInstance(instanceId) as WebChromeClient?;
final WebView? webViewInstance =
instanceManager.getInstance(webViewInstanceId) as WebView?;
assert(
instance != null,
'InstanceManager does not contain an WebChromeClient with instanceId: $instanceId',
);
assert(
webViewInstance != null,
'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId',
);
instance!.onProgressChanged(webViewInstance!, progress);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_api_impls.dart/0 | {'file_path': 'plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_api_impls.dart', 'repo_id': 'plugins', 'token_count': 7853} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export 'auto_media_playback_policy.dart';
export 'creation_params.dart';
export 'javascript_channel.dart';
export 'javascript_message.dart';
export 'javascript_mode.dart';
export 'web_resource_error.dart';
export 'web_resource_error_type.dart';
export 'web_settings.dart';
export 'webview_cookie.dart';
export 'webview_request.dart';
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/types.dart/0 | {'file_path': 'plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/types.dart', 'repo_id': 'plugins', 'token_count': 155} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.