text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:html' as html;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart';
import 'package:integration_test/integration_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'google_maps_controller_test.mocks.dart';
// This value is used when comparing long~num, like
// LatLng values.
const double _acceptableDelta = 0.0000000001;
@GenerateMocks(<Type>[], customMocks: <MockSpec<dynamic>>[
MockSpec<CirclesController>(onMissingStub: OnMissingStub.returnDefault),
MockSpec<PolygonsController>(onMissingStub: OnMissingStub.returnDefault),
MockSpec<PolylinesController>(onMissingStub: OnMissingStub.returnDefault),
MockSpec<MarkersController>(onMissingStub: OnMissingStub.returnDefault),
])
/// Test Google Map Controller
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('GoogleMapController', () {
const int mapId = 33930;
late GoogleMapController controller;
late StreamController<MapEvent<Object?>> stream;
// Creates a controller with the default mapId and stream controller, and any `options` needed.
GoogleMapController createController({
CameraPosition initialCameraPosition =
const CameraPosition(target: LatLng(0, 0)),
MapObjects mapObjects = const MapObjects(),
MapConfiguration mapConfiguration = const MapConfiguration(),
}) {
return GoogleMapController(
mapId: mapId,
streamController: stream,
widgetConfiguration: MapWidgetConfiguration(
initialCameraPosition: initialCameraPosition,
textDirection: TextDirection.ltr),
mapObjects: mapObjects,
mapConfiguration: mapConfiguration,
);
}
setUp(() {
stream = StreamController<MapEvent<Object?>>.broadcast();
});
group('construct/dispose', () {
setUp(() {
controller = createController();
});
testWidgets('constructor creates widget', (WidgetTester tester) async {
expect(controller.widget, isNotNull);
expect(controller.widget, isA<HtmlElementView>());
expect((controller.widget! as HtmlElementView).viewType,
endsWith('$mapId'));
});
testWidgets('widget is cached when reused', (WidgetTester tester) async {
final Widget? first = controller.widget;
final Widget? again = controller.widget;
expect(identical(first, again), isTrue);
});
group('dispose', () {
testWidgets('closes the stream and removes the widget',
(WidgetTester tester) async {
controller.dispose();
expect(stream.isClosed, isTrue);
expect(controller.widget, isNull);
});
testWidgets('cannot call getVisibleRegion after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() async {
await controller.getVisibleRegion();
}, throwsAssertionError);
});
testWidgets('cannot call getScreenCoordinate after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() async {
await controller.getScreenCoordinate(
const LatLng(43.3072465, -5.6918241),
);
}, throwsAssertionError);
});
testWidgets('cannot call getLatLng after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() async {
await controller.getLatLng(
const ScreenCoordinate(x: 640, y: 480),
);
}, throwsAssertionError);
});
testWidgets('cannot call moveCamera after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() async {
await controller.moveCamera(CameraUpdate.zoomIn());
}, throwsAssertionError);
});
testWidgets('cannot call getZoomLevel after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() async {
await controller.getZoomLevel();
}, throwsAssertionError);
});
testWidgets('cannot updateCircles after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() {
controller.updateCircles(
CircleUpdates.from(
const <Circle>{},
const <Circle>{},
),
);
}, throwsAssertionError);
});
testWidgets('cannot updatePolygons after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() {
controller.updatePolygons(
PolygonUpdates.from(
const <Polygon>{},
const <Polygon>{},
),
);
}, throwsAssertionError);
});
testWidgets('cannot updatePolylines after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() {
controller.updatePolylines(
PolylineUpdates.from(
const <Polyline>{},
const <Polyline>{},
),
);
}, throwsAssertionError);
});
testWidgets('cannot updateMarkers after dispose',
(WidgetTester tester) async {
controller.dispose();
expect(() {
controller.updateMarkers(
MarkerUpdates.from(
const <Marker>{},
const <Marker>{},
),
);
}, throwsAssertionError);
expect(() {
controller.showInfoWindow(const MarkerId('any'));
}, throwsAssertionError);
expect(() {
controller.hideInfoWindow(const MarkerId('any'));
}, throwsAssertionError);
});
testWidgets('isInfoWindowShown defaults to false',
(WidgetTester tester) async {
controller.dispose();
expect(controller.isInfoWindowShown(const MarkerId('any')), false);
});
});
});
group('init', () {
late MockCirclesController circles;
late MockMarkersController markers;
late MockPolygonsController polygons;
late MockPolylinesController polylines;
late gmaps.GMap map;
setUp(() {
circles = MockCirclesController();
markers = MockMarkersController();
polygons = MockPolygonsController();
polylines = MockPolylinesController();
map = gmaps.GMap(html.DivElement());
});
testWidgets('listens to map events', (WidgetTester tester) async {
controller = createController();
controller.debugSetOverrides(
createMap: (_, __) => map,
circles: circles,
markers: markers,
polygons: polygons,
polylines: polylines,
);
controller.init();
// Trigger events on the map, and verify they've been broadcast to the stream
final Stream<MapEvent<Object?>> capturedEvents = stream.stream.take(5);
gmaps.Event.trigger(
map,
'click',
<Object>[gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)],
);
gmaps.Event.trigger(
map,
'rightclick',
<Object>[gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)],
);
// The following line causes 2 events
gmaps.Event.trigger(map, 'bounds_changed', <Object>[]);
gmaps.Event.trigger(map, 'idle', <Object>[]);
final List<MapEvent<Object?>> events = await capturedEvents.toList();
expect(events[0], isA<MapTapEvent>());
expect(events[1], isA<MapLongPressEvent>());
expect(events[2], isA<CameraMoveStartedEvent>());
expect(events[3], isA<CameraMoveEvent>());
expect(events[4], isA<CameraIdleEvent>());
});
testWidgets("binds geometry controllers to map's",
(WidgetTester tester) async {
controller = createController();
controller.debugSetOverrides(
createMap: (_, __) => map,
circles: circles,
markers: markers,
polygons: polygons,
polylines: polylines,
);
controller.init();
verify(circles.bindToMap(mapId, map));
verify(markers.bindToMap(mapId, map));
verify(polygons.bindToMap(mapId, map));
verify(polylines.bindToMap(mapId, map));
});
testWidgets('renders initial geometry', (WidgetTester tester) async {
controller = createController(
mapObjects: MapObjects(circles: <Circle>{
const Circle(
circleId: CircleId('circle-1'),
zIndex: 1234,
),
}, markers: <Marker>{
const Marker(
markerId: MarkerId('marker-1'),
infoWindow: InfoWindow(
title: 'title for test',
snippet: 'snippet for test',
),
),
}, polygons: <Polygon>{
const Polygon(polygonId: PolygonId('polygon-1'), points: <LatLng>[
LatLng(43.355114, -5.851333),
LatLng(43.354797, -5.851860),
LatLng(43.354469, -5.851318),
LatLng(43.354762, -5.850824),
]),
const Polygon(
polygonId: PolygonId('polygon-2-with-holes'),
points: <LatLng>[
LatLng(43.355114, -5.851333),
LatLng(43.354797, -5.851860),
LatLng(43.354469, -5.851318),
LatLng(43.354762, -5.850824),
],
holes: <List<LatLng>>[
<LatLng>[
LatLng(41.354797, -6.851860),
LatLng(41.354469, -6.851318),
LatLng(41.354762, -6.850824),
]
],
),
}, polylines: <Polyline>{
const Polyline(polylineId: PolylineId('polyline-1'), points: <LatLng>[
LatLng(43.355114, -5.851333),
LatLng(43.354797, -5.851860),
LatLng(43.354469, -5.851318),
LatLng(43.354762, -5.850824),
])
}));
controller.debugSetOverrides(
circles: circles,
markers: markers,
polygons: polygons,
polylines: polylines,
);
controller.init();
final Set<Circle> capturedCircles =
verify(circles.addCircles(captureAny)).captured[0] as Set<Circle>;
final Set<Marker> capturedMarkers =
verify(markers.addMarkers(captureAny)).captured[0] as Set<Marker>;
final Set<Polygon> capturedPolygons =
verify(polygons.addPolygons(captureAny)).captured[0]
as Set<Polygon>;
final Set<Polyline> capturedPolylines =
verify(polylines.addPolylines(captureAny)).captured[0]
as Set<Polyline>;
expect(capturedCircles.first.circleId.value, 'circle-1');
expect(capturedCircles.first.zIndex, 1234);
expect(capturedMarkers.first.markerId.value, 'marker-1');
expect(capturedMarkers.first.infoWindow.snippet, 'snippet for test');
expect(capturedMarkers.first.infoWindow.title, 'title for test');
expect(capturedPolygons.first.polygonId.value, 'polygon-1');
expect(capturedPolygons.elementAt(1).polygonId.value,
'polygon-2-with-holes');
expect(capturedPolygons.elementAt(1).holes, isNot(null));
expect(capturedPolylines.first.polylineId.value, 'polyline-1');
});
testWidgets('empty infoWindow does not create InfoWindow instance.',
(WidgetTester tester) async {
controller = createController(
mapObjects: MapObjects(markers: <Marker>{
const Marker(markerId: MarkerId('marker-1')),
}));
controller.debugSetOverrides(
markers: markers,
);
controller.init();
final Set<Marker> capturedMarkers =
verify(markers.addMarkers(captureAny)).captured[0] as Set<Marker>;
expect(capturedMarkers.first.infoWindow, InfoWindow.noText);
});
group('Initialization options', () {
gmaps.MapOptions? capturedOptions;
setUp(() {
capturedOptions = null;
});
testWidgets('translates initial options', (WidgetTester tester) async {
controller = createController(
mapConfiguration: const MapConfiguration(
mapType: MapType.satellite,
zoomControlsEnabled: true,
));
controller.debugSetOverrides(
createMap: (_, gmaps.MapOptions options) {
capturedOptions = options;
return map;
});
controller.init();
expect(capturedOptions, isNotNull);
expect(capturedOptions!.mapTypeId, gmaps.MapTypeId.SATELLITE);
expect(capturedOptions!.zoomControl, true);
expect(capturedOptions!.gestureHandling, 'auto',
reason:
'by default the map handles zoom/pan gestures internally');
});
testWidgets('disables gestureHandling with scrollGesturesEnabled false',
(WidgetTester tester) async {
controller = createController(
mapConfiguration: const MapConfiguration(
scrollGesturesEnabled: false,
));
controller.debugSetOverrides(
createMap: (_, gmaps.MapOptions options) {
capturedOptions = options;
return map;
});
controller.init();
expect(capturedOptions, isNotNull);
expect(capturedOptions!.gestureHandling, 'none',
reason:
'disabling scroll gestures disables all gesture handling');
});
testWidgets('disables gestureHandling with zoomGesturesEnabled false',
(WidgetTester tester) async {
controller = createController(
mapConfiguration: const MapConfiguration(
zoomGesturesEnabled: false,
));
controller.debugSetOverrides(
createMap: (_, gmaps.MapOptions options) {
capturedOptions = options;
return map;
});
controller.init();
expect(capturedOptions, isNotNull);
expect(capturedOptions!.gestureHandling, 'none',
reason:
'disabling scroll gestures disables all gesture handling');
});
testWidgets('sets initial position when passed',
(WidgetTester tester) async {
controller = createController(
initialCameraPosition: const CameraPosition(
target: LatLng(43.308, -5.6910),
zoom: 12,
),
);
controller.debugSetOverrides(
createMap: (_, gmaps.MapOptions options) {
capturedOptions = options;
return map;
});
controller.init();
expect(capturedOptions, isNotNull);
expect(capturedOptions!.zoom, 12);
expect(capturedOptions!.center, isNotNull);
});
});
group('Traffic Layer', () {
testWidgets('by default is disabled', (WidgetTester tester) async {
controller = createController();
controller.init();
expect(controller.trafficLayer, isNull);
});
testWidgets('initializes with traffic layer',
(WidgetTester tester) async {
controller = createController(
mapConfiguration: const MapConfiguration(
trafficEnabled: true,
));
controller.debugSetOverrides(createMap: (_, __) => map);
controller.init();
expect(controller.trafficLayer, isNotNull);
});
});
});
// These are the methods that are delegated to the gmaps.GMap object, that we can mock...
group('Map control methods', () {
late gmaps.GMap map;
setUp(() {
map = gmaps.GMap(
html.DivElement(),
gmaps.MapOptions()
..zoom = 10
..center = gmaps.LatLng(0, 0),
);
controller = createController();
controller.debugSetOverrides(createMap: (_, __) => map);
controller.init();
});
group('updateRawOptions', () {
testWidgets('can update `options`', (WidgetTester tester) async {
controller.updateMapConfiguration(const MapConfiguration(
mapType: MapType.satellite,
));
expect(map.mapTypeId, gmaps.MapTypeId.SATELLITE);
});
testWidgets('can turn on/off traffic', (WidgetTester tester) async {
expect(controller.trafficLayer, isNull);
controller.updateMapConfiguration(const MapConfiguration(
trafficEnabled: true,
));
expect(controller.trafficLayer, isNotNull);
controller.updateMapConfiguration(const MapConfiguration(
trafficEnabled: false,
));
expect(controller.trafficLayer, isNull);
});
});
group('viewport getters', () {
testWidgets('getVisibleRegion', (WidgetTester tester) async {
final gmaps.LatLng gmCenter = map.center!;
final LatLng center =
LatLng(gmCenter.lat.toDouble(), gmCenter.lng.toDouble());
final LatLngBounds bounds = await controller.getVisibleRegion();
expect(bounds.contains(center), isTrue,
reason:
'The computed visible region must contain the center of the created map.');
});
testWidgets('getZoomLevel', (WidgetTester tester) async {
expect(await controller.getZoomLevel(), map.zoom);
});
});
group('moveCamera', () {
testWidgets('newLatLngZoom', (WidgetTester tester) async {
await controller.moveCamera(
CameraUpdate.newLatLngZoom(
const LatLng(19, 26),
12,
),
);
final gmaps.LatLng gmCenter = map.center!;
expect(map.zoom, 12);
expect(gmCenter.lat, closeTo(19, _acceptableDelta));
expect(gmCenter.lng, closeTo(26, _acceptableDelta));
});
});
group('map.projection methods', () {
// Tested in projection_test.dart
});
});
// These are the methods that get forwarded to other controllers, so we just verify calls.
group('Pass-through methods', () {
setUp(() {
controller = createController();
});
testWidgets('updateCircles', (WidgetTester tester) async {
final MockCirclesController mock = MockCirclesController();
controller.debugSetOverrides(circles: mock);
final Set<Circle> previous = <Circle>{
const Circle(circleId: CircleId('to-be-updated')),
const Circle(circleId: CircleId('to-be-removed')),
};
final Set<Circle> current = <Circle>{
const Circle(circleId: CircleId('to-be-updated'), visible: false),
const Circle(circleId: CircleId('to-be-added')),
};
controller.updateCircles(CircleUpdates.from(previous, current));
verify(mock.removeCircles(<CircleId>{
const CircleId('to-be-removed'),
}));
verify(mock.addCircles(<Circle>{
const Circle(circleId: CircleId('to-be-added')),
}));
verify(mock.changeCircles(<Circle>{
const Circle(circleId: CircleId('to-be-updated'), visible: false),
}));
});
testWidgets('updateMarkers', (WidgetTester tester) async {
final MockMarkersController mock = MockMarkersController();
controller.debugSetOverrides(markers: mock);
final Set<Marker> previous = <Marker>{
const Marker(markerId: MarkerId('to-be-updated')),
const Marker(markerId: MarkerId('to-be-removed')),
};
final Set<Marker> current = <Marker>{
const Marker(markerId: MarkerId('to-be-updated'), visible: false),
const Marker(markerId: MarkerId('to-be-added')),
};
controller.updateMarkers(MarkerUpdates.from(previous, current));
verify(mock.removeMarkers(<MarkerId>{
const MarkerId('to-be-removed'),
}));
verify(mock.addMarkers(<Marker>{
const Marker(markerId: MarkerId('to-be-added')),
}));
verify(mock.changeMarkers(<Marker>{
const Marker(markerId: MarkerId('to-be-updated'), visible: false),
}));
});
testWidgets('updatePolygons', (WidgetTester tester) async {
final MockPolygonsController mock = MockPolygonsController();
controller.debugSetOverrides(polygons: mock);
final Set<Polygon> previous = <Polygon>{
const Polygon(polygonId: PolygonId('to-be-updated')),
const Polygon(polygonId: PolygonId('to-be-removed')),
};
final Set<Polygon> current = <Polygon>{
const Polygon(polygonId: PolygonId('to-be-updated'), visible: false),
const Polygon(polygonId: PolygonId('to-be-added')),
};
controller.updatePolygons(PolygonUpdates.from(previous, current));
verify(mock.removePolygons(<PolygonId>{
const PolygonId('to-be-removed'),
}));
verify(mock.addPolygons(<Polygon>{
const Polygon(polygonId: PolygonId('to-be-added')),
}));
verify(mock.changePolygons(<Polygon>{
const Polygon(polygonId: PolygonId('to-be-updated'), visible: false),
}));
});
testWidgets('updatePolylines', (WidgetTester tester) async {
final MockPolylinesController mock = MockPolylinesController();
controller.debugSetOverrides(polylines: mock);
final Set<Polyline> previous = <Polyline>{
const Polyline(polylineId: PolylineId('to-be-updated')),
const Polyline(polylineId: PolylineId('to-be-removed')),
};
final Set<Polyline> current = <Polyline>{
const Polyline(
polylineId: PolylineId('to-be-updated'),
visible: false,
),
const Polyline(polylineId: PolylineId('to-be-added')),
};
controller.updatePolylines(PolylineUpdates.from(previous, current));
verify(mock.removePolylines(<PolylineId>{
const PolylineId('to-be-removed'),
}));
verify(mock.addPolylines(<Polyline>{
const Polyline(polylineId: PolylineId('to-be-added')),
}));
verify(mock.changePolylines(<Polyline>{
const Polyline(
polylineId: PolylineId('to-be-updated'),
visible: false,
),
}));
});
testWidgets('infoWindow visibility', (WidgetTester tester) async {
final MockMarkersController mock = MockMarkersController();
const MarkerId markerId = MarkerId('marker-with-infowindow');
when(mock.isInfoWindowShown(markerId)).thenReturn(true);
controller.debugSetOverrides(markers: mock);
controller.showInfoWindow(markerId);
verify(mock.showMarkerInfoWindow(markerId));
controller.hideInfoWindow(markerId);
verify(mock.hideMarkerInfoWindow(markerId));
controller.isInfoWindowShown(markerId);
verify(mock.isInfoWindowShown(markerId));
});
});
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart",
"repo_id": "plugins",
"token_count": 10893
} | 1,154 |
// 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.
library google_maps_flutter_web;
import 'dart:async';
import 'dart:convert';
import 'dart:html';
import 'dart:js_util';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:sanitize_html/sanitize_html.dart';
import 'package:stream_transform/stream_transform.dart';
import 'src/shims/dart_ui.dart' as ui; // Conditionally imports dart:ui in web
import 'src/third_party/to_screen_location/to_screen_location.dart';
import 'src/types.dart';
part 'src/circle.dart';
part 'src/circles.dart';
part 'src/convert.dart';
part 'src/google_maps_controller.dart';
part 'src/google_maps_flutter_web.dart';
part 'src/marker.dart';
part 'src/markers.dart';
part 'src/polygon.dart';
part 'src/polygons.dart';
part 'src/polyline.dart';
part 'src/polylines.dart';
| plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/google_maps_flutter_web.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/google_maps_flutter_web.dart",
"repo_id": "plugins",
"token_count": 448
} | 1,155 |
# to_screen_location
The code in this directory is a Dart re-implementation of Krasimir Tsonev's blog
post: [GoogleMaps API v3: convert LatLng object to actual pixels][blog-post].
The blog post describes a way to implement the [`toScreenLocation` method][method]
of the Google Maps Platform SDK for the web.
Used under license (MIT), [available here][blog-license], and in the accompanying
LICENSE file.
[blog-license]: https://krasimirtsonev.com/license
[blog-post]: https://krasimirtsonev.com/blog/article/google-maps-api-v3-convert-latlng-object-to-actual-pixels-point-object
[method]: https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/Projection#toScreenLocation(com.google.android.libraries.maps.model.LatLng)
| plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/README.md/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/README.md",
"repo_id": "plugins",
"token_count": 239
} | 1,156 |
name: google_sign_in_example
description: Example of Google Sign-In plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
google_sign_in:
# When depending on this package from a real application you should use:
# google_sign_in: ^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: ../
http: ^0.13.0
dev_dependencies:
espresso: ^0.2.0
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/google_sign_in/google_sign_in/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 287
} | 1,157 |
## 6.1.6
* Minor implementation cleanup
* Updates minimum Flutter version to 3.0.
## 6.1.5
* Updates play-services-auth version to 20.4.1.
## 6.1.4
* Rolls Guava to version 31.1.
## 6.1.3
* Updates play-services-auth version to 20.4.0.
## 6.1.2
* Fixes passing `serverClientId` via the channelled `init` call
## 6.1.1
* Corrects typos in plugin error logs and removes not actionable warnings.
* Updates minimum Flutter version to 2.10.
* Updates play-services-auth version to 20.3.0.
## 6.1.0
* Adds override for `GoogleSignIn.initWithParams` to handle new `forceCodeForRefreshToken` parameter.
## 6.0.1
* Updates gradle version to 7.2.1 on Android.
## 6.0.0
* Deprecates `clientId` and adds support for `serverClientId` instead.
Historically `clientId` was interpreted as `serverClientId`, but only on Android. On
other platforms it was interpreted as the OAuth `clientId` of the app. For backwards-compatibility
`clientId` will still be used as a server client ID if `serverClientId` is not provided.
* **BREAKING CHANGES**:
* Adds `serverClientId` parameter to `IDelegate.init` (Java).
## 5.2.8
* Suppresses `deprecation` warnings (for using Android V1 embedding).
## 5.2.7
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 5.2.6
* Switches to an internal method channel, rather than the default.
## 5.2.5
* Splits from `google_sign_in` as a federated implementation.
| plugins/packages/google_sign_in/google_sign_in_android/CHANGELOG.md/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_android/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 494
} | 1,158 |
// 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 os.log;
@import XCTest;
@interface GoogleSignInUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@end
@implementation GoogleSignInUITests
- (void)setUp {
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
[self.app launch];
}
- (void)testSignInPopUp {
XCUIApplication *app = self.app;
XCUIElement *signInButton = app.buttons[@"SIGN IN"];
if (![signInButton waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find Sign In button");
}
[signInButton tap];
[self allowSignInPermissions];
}
- (void)allowSignInPermissions {
// The "Sign In" system permissions pop up isn't caught by
// addUIInterruptionMonitorWithDescription.
XCUIApplication *springboard =
[[XCUIApplication alloc] initWithBundleIdentifier:@"com.apple.springboard"];
XCUIElement *permissionAlert = springboard.alerts.firstMatch;
if ([permissionAlert waitForExistenceWithTimeout:5.0]) {
[permissionAlert.buttons[@"Continue"] tap];
} else {
os_log(OS_LOG_DEFAULT, "Permission alert not detected, continuing.");
}
}
@end
| plugins/packages/google_sign_in/google_sign_in_ios/example/ios/RunnerUITests/GoogleSignInUITests.m/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/example/ios/RunnerUITests/GoogleSignInUITests.m",
"repo_id": "plugins",
"token_count": 462
} | 1,159 |
// 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';
// TODO(dit): Split `id` and `oauth2` "services" for mocking. https://github.com/flutter/flutter/issues/120657
import 'package:google_identity_services_web/id.dart';
import 'package:google_identity_services_web/oauth2.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
// ignore: unnecessary_import
import 'package:js/js.dart';
import 'package:js/js_util.dart';
import 'people.dart' as people;
import 'utils.dart' as utils;
/// A client to hide (most) of the interaction with the GIS SDK from the plugin.
///
/// (Overridable for testing)
class GisSdkClient {
/// Create a GisSdkClient object.
GisSdkClient({
required List<String> initialScopes,
required String clientId,
bool loggingEnabled = false,
String? hostedDomain,
}) : _initialScopes = initialScopes {
if (loggingEnabled) {
id.setLogLevel('debug');
}
// Configure the Stream objects that are going to be used by the clients.
_configureStreams();
// Initialize the SDK clients we need.
_initializeIdClient(
clientId,
onResponse: _onCredentialResponse,
);
_tokenClient = _initializeTokenClient(
clientId,
hostedDomain: hostedDomain,
onResponse: _onTokenResponse,
onError: _onTokenError,
);
}
// Configure the credential (authentication) and token (authorization) response streams.
void _configureStreams() {
_tokenResponses = StreamController<TokenResponse>.broadcast();
_credentialResponses = StreamController<CredentialResponse>.broadcast();
_tokenResponses.stream.listen((TokenResponse response) {
_lastTokenResponse = response;
}, onError: (Object error) {
_lastTokenResponse = null;
});
_credentialResponses.stream.listen((CredentialResponse response) {
_lastCredentialResponse = response;
}, onError: (Object error) {
_lastCredentialResponse = null;
});
}
// Initializes the `id` SDK for the silent-sign in (authentication) client.
void _initializeIdClient(
String clientId, {
required CallbackFn onResponse,
}) {
// Initialize `id` for the silent-sign in code.
final IdConfiguration idConfig = IdConfiguration(
client_id: clientId,
callback: allowInterop(onResponse),
cancel_on_tap_outside: false,
auto_select: true, // Attempt to sign-in silently.
);
id.initialize(idConfig);
}
// Handle a "normal" credential (authentication) response.
//
// (Normal doesn't mean successful, this might contain `error` information.)
void _onCredentialResponse(CredentialResponse response) {
if (response.error != null) {
_credentialResponses.addError(response.error!);
} else {
_credentialResponses.add(response);
}
}
// Creates a `oauth2.TokenClient` used for authorization (scope) requests.
TokenClient _initializeTokenClient(
String clientId, {
String? hostedDomain,
required TokenClientCallbackFn onResponse,
required ErrorCallbackFn onError,
}) {
// Create a Token Client for authorization calls.
final TokenClientConfig tokenConfig = TokenClientConfig(
client_id: clientId,
hosted_domain: hostedDomain,
callback: allowInterop(_onTokenResponse),
error_callback: allowInterop(_onTokenError),
// `scope` will be modified by the `signIn` method, in case we need to
// backfill user Profile info.
scope: ' ',
);
return oauth2.initTokenClient(tokenConfig);
}
// Handle a "normal" token (authorization) response.
//
// (Normal doesn't mean successful, this might contain `error` information.)
void _onTokenResponse(TokenResponse response) {
if (response.error != null) {
_tokenResponses.addError(response.error!);
} else {
_tokenResponses.add(response);
}
}
// Handle a "not-directly-related-to-authorization" error.
//
// Token clients have an additional `error_callback` for miscellaneous
// errors, like "popup couldn't open" or "popup closed by user".
void _onTokenError(Object? error) {
// This is handled in a funky (js_interop) way because of:
// https://github.com/dart-lang/sdk/issues/50899
_tokenResponses.addError(getProperty(error!, 'type'));
}
/// Attempts to sign-in the user using the OneTap UX flow.
///
/// If the user consents, to OneTap, the [GoogleSignInUserData] will be
/// generated from a proper [CredentialResponse], which contains `idToken`.
/// Else, it'll be synthesized by a request to the People API later, and the
/// `idToken` will be null.
Future<GoogleSignInUserData?> signInSilently() async {
final Completer<GoogleSignInUserData?> userDataCompleter =
Completer<GoogleSignInUserData?>();
// Ask the SDK to render the OneClick sign-in.
//
// And also handle its "moments".
id.prompt(allowInterop((PromptMomentNotification moment) {
_onPromptMoment(moment, userDataCompleter);
}));
return userDataCompleter.future;
}
// Handles "prompt moments" of the OneClick card UI.
//
// See: https://developers.google.com/identity/gsi/web/guides/receive-notifications-prompt-ui-status
Future<void> _onPromptMoment(
PromptMomentNotification moment,
Completer<GoogleSignInUserData?> completer,
) async {
if (completer.isCompleted) {
return; // Skip once the moment has been handled.
}
if (moment.isDismissedMoment() &&
moment.getDismissedReason() ==
MomentDismissedReason.credential_returned) {
// Kick this part of the handler to the bottom of the JS event queue, so
// the _credentialResponses stream has time to propagate its last value,
// and we can use _lastCredentialResponse.
return Future<void>.delayed(Duration.zero, () {
completer
.complete(utils.gisResponsesToUserData(_lastCredentialResponse));
});
}
// In any other 'failed' moments, return null and add an error to the stream.
if (moment.isNotDisplayed() ||
moment.isSkippedMoment() ||
moment.isDismissedMoment()) {
final String reason = moment.getNotDisplayedReason()?.toString() ??
moment.getSkippedReason()?.toString() ??
moment.getDismissedReason()?.toString() ??
'unknown_error';
_credentialResponses.addError(reason);
completer.complete(null);
}
}
/// Starts an oauth2 "implicit" flow to authorize requests.
///
/// The new GIS SDK does not return user authentication from this flow, so:
/// * If [_lastCredentialResponse] is **not** null (the user has successfully
/// `signInSilently`), we return that after this method completes.
/// * If [_lastCredentialResponse] is null, we add [people.scopes] to the
/// [_initialScopes], so we can retrieve User Profile information back
/// from the People API (without idToken). See [people.requestUserData].
Future<GoogleSignInUserData?> signIn() async {
// If we already know the user, use their `email` as a `hint`, so they don't
// have to pick their user again in the Authorization popup.
final GoogleSignInUserData? knownUser =
utils.gisResponsesToUserData(_lastCredentialResponse);
// This toggles a popup, so `signIn` *must* be called with
// user activation.
_tokenClient.requestAccessToken(OverridableTokenClientConfig(
prompt: knownUser == null ? 'select_account' : '',
hint: knownUser?.email,
scope: <String>[
..._initialScopes,
// If the user hasn't gone through the auth process,
// the plugin will attempt to `requestUserData` after,
// so we need extra scopes to retrieve that info.
if (_lastCredentialResponse == null) ...people.scopes,
].join(' '),
));
await _tokenResponses.stream.first;
return _computeUserDataForLastToken();
}
// This function returns the currently signed-in [GoogleSignInUserData].
//
// It'll do a request to the People API (if needed).
Future<GoogleSignInUserData?> _computeUserDataForLastToken() async {
// If the user hasn't authenticated, request their basic profile info
// from the People API.
//
// This synthetic response will *not* contain an `idToken` field.
if (_lastCredentialResponse == null && _requestedUserData == null) {
assert(_lastTokenResponse != null);
_requestedUserData = await people.requestUserData(_lastTokenResponse!);
}
// Complete user data either with the _lastCredentialResponse seen,
// or the synthetic _requestedUserData from above.
return utils.gisResponsesToUserData(_lastCredentialResponse) ??
_requestedUserData;
}
/// Returns a [GoogleSignInTokenData] from the latest seen responses.
GoogleSignInTokenData getTokens() {
return utils.gisResponsesToTokenData(
_lastCredentialResponse,
_lastTokenResponse,
);
}
/// Revokes the current authentication.
Future<void> signOut() async {
clearAuthCache();
id.disableAutoSelect();
}
/// Revokes the current authorization and authentication.
Future<void> disconnect() async {
if (_lastTokenResponse != null) {
oauth2.revoke(_lastTokenResponse!.access_token);
}
signOut();
}
/// Returns true if the client has recognized this user before.
Future<bool> isSignedIn() async {
return _lastCredentialResponse != null || _requestedUserData != null;
}
/// Clears all the cached results from authentication and authorization.
Future<void> clearAuthCache() async {
_lastCredentialResponse = null;
_lastTokenResponse = null;
_requestedUserData = null;
}
/// Requests the list of [scopes] passed in to the client.
///
/// Keeps the previously granted scopes.
Future<bool> requestScopes(List<String> scopes) async {
_tokenClient.requestAccessToken(OverridableTokenClientConfig(
scope: scopes.join(' '),
include_granted_scopes: true,
));
await _tokenResponses.stream.first;
return oauth2.hasGrantedAllScopes(_lastTokenResponse!, scopes);
}
// The scopes initially requested by the developer.
//
// We store this because we might need to add more at `signIn`. If the user
// doesn't `silentSignIn`, we expand this list to consult the People API to
// return some basic Authentication information.
final List<String> _initialScopes;
// The Google Identity Services client for oauth requests.
late TokenClient _tokenClient;
// Streams of credential and token responses.
late StreamController<CredentialResponse> _credentialResponses;
late StreamController<TokenResponse> _tokenResponses;
// The last-seen credential and token responses
CredentialResponse? _lastCredentialResponse;
TokenResponse? _lastTokenResponse;
// If the user *authenticates* (signs in) through oauth2, the SDK doesn't return
// identity information anymore, so we synthesize it by calling the PeopleAPI
// (if needed)
//
// (This is a synthetic _lastCredentialResponse)
GoogleSignInUserData? _requestedUserData;
}
| plugins/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart",
"repo_id": "plugins",
"token_count": 3780
} | 1,160 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.imagepicker;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertTrue;
import static org.robolectric.Shadows.shadowOf;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.test.core.app.ApplicationProvider;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowContentResolver;
@RunWith(RobolectricTestRunner.class)
public class FileUtilTest {
private Context context;
private FileUtils fileUtils;
ShadowContentResolver shadowContentResolver;
@Before
public void before() {
context = ApplicationProvider.getApplicationContext();
shadowContentResolver = shadowOf(context.getContentResolver());
fileUtils = new FileUtils();
}
@Test
public void FileUtil_GetPathFromUri() throws IOException {
Uri uri = Uri.parse("content://dummy/dummy.png");
shadowContentResolver.registerInputStream(
uri, new ByteArrayInputStream("imageStream".getBytes(UTF_8)));
String path = fileUtils.getPathFromUri(context, uri);
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
assertTrue(bytes.length > 0);
String imageStream = new String(bytes, UTF_8);
assertTrue(imageStream.equals("imageStream"));
}
@Test
public void FileUtil_getImageExtension() throws IOException {
Uri uri = Uri.parse("content://dummy/dummy.png");
shadowContentResolver.registerInputStream(
uri, new ByteArrayInputStream("imageStream".getBytes(UTF_8)));
String path = fileUtils.getPathFromUri(context, uri);
assertTrue(path.endsWith(".jpg"));
}
@Test
public void FileUtil_getImageName() throws IOException {
Uri uri = Uri.parse("content://dummy/dummy.png");
Robolectric.buildContentProvider(MockContentProvider.class).create("dummy");
shadowContentResolver.registerInputStream(
uri, new ByteArrayInputStream("imageStream".getBytes(UTF_8)));
String path = fileUtils.getPathFromUri(context, uri);
assertTrue(path.endsWith("dummy.png"));
}
private static class MockContentProvider extends ContentProvider {
@Override
public boolean onCreate() {
return true;
}
@Nullable
@Override
public Cursor query(
@NonNull Uri uri,
@Nullable String[] projection,
@Nullable String selection,
@Nullable String[] selectionArgs,
@Nullable String sortOrder) {
MatrixCursor cursor = new MatrixCursor(new String[] {MediaStore.MediaColumns.DISPLAY_NAME});
cursor.addRow(new Object[] {"dummy.png"});
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return "image/png";
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
return null;
}
@Override
public int delete(
@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
@Override
public int update(
@NonNull Uri uri,
@Nullable ContentValues values,
@Nullable String selection,
@Nullable String[] selectionArgs) {
return 0;
}
}
}
| plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/FileUtilTest.java/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/FileUtilTest.java",
"repo_id": "plugins",
"token_count": 1417
} | 1,161 |
// 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_test/flutter_test.dart';
import 'package:image_picker_ios/image_picker_ios.dart';
import 'package:image_picker_ios/src/messages.g.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'test_api.g.dart';
@immutable
class _LoggedMethodCall {
const _LoggedMethodCall(this.name, {required this.arguments});
final String name;
final Map<String, Object?> arguments;
@override
bool operator ==(Object other) {
return other is _LoggedMethodCall &&
name == other.name &&
mapEquals(arguments, other.arguments);
}
@override
int get hashCode => Object.hash(name, arguments);
@override
String toString() {
return 'MethodCall: $name $arguments';
}
}
class _ApiLogger implements TestHostImagePickerApi {
// The value to return from future calls.
dynamic returnValue = '';
final List<_LoggedMethodCall> calls = <_LoggedMethodCall>[];
@override
Future<String?> pickImage(
SourceSpecification source,
MaxSize maxSize,
int? imageQuality,
bool requestFullMetadata,
) async {
// Flatten arguments for easy comparison.
calls.add(_LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': source.type,
'cameraDevice': source.camera,
'maxWidth': maxSize.width,
'maxHeight': maxSize.height,
'imageQuality': imageQuality,
'requestFullMetadata': requestFullMetadata,
}));
return returnValue as String?;
}
@override
Future<List<String?>?> pickMultiImage(
MaxSize maxSize,
int? imageQuality,
bool requestFullMetadata,
) async {
calls.add(_LoggedMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': maxSize.width,
'maxHeight': maxSize.height,
'imageQuality': imageQuality,
'requestFullMetadata': requestFullMetadata,
}));
return returnValue as List<String?>?;
}
@override
Future<String?> pickVideo(
SourceSpecification source, int? maxDurationSeconds) async {
calls.add(_LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': source.type,
'cameraDevice': source.camera,
'maxDuration': maxDurationSeconds,
}));
return returnValue as String?;
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final ImagePickerIOS picker = ImagePickerIOS();
late _ApiLogger log;
setUp(() {
log = _ApiLogger();
TestHostImagePickerApi.setup(log);
});
test('registration', () async {
ImagePickerIOS.registerWith();
expect(ImagePickerPlatform.instance, isA<ImagePickerIOS>());
});
group('#pickImage', () {
test('passes the image source argument correctly', () async {
await picker.pickImage(source: ImageSource.camera);
await picker.pickImage(source: ImageSource.gallery);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.gallery,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width and height arguments correctly', () async {
await picker.pickImage(source: ImageSource.camera);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
);
await picker.pickImage(
source: ImageSource.camera,
maxHeight: 10.0,
);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
imageQuality: 70,
);
await picker.pickImage(
source: ImageSource.camera,
maxHeight: 10.0,
imageQuality: 70,
);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
imageQuality: 70,
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a invalid imageQuality argument', () {
expect(
() => picker.pickImage(imageQuality: -1, source: ImageSource.gallery),
throwsArgumentError,
);
expect(
() => picker.pickImage(imageQuality: 101, source: ImageSource.gallery),
throwsArgumentError,
);
expect(
() => picker.pickImage(imageQuality: -1, source: ImageSource.camera),
throwsArgumentError,
);
expect(
() => picker.pickImage(imageQuality: 101, source: ImageSource.camera),
throwsArgumentError,
);
});
test('does not accept a negative width or height argument', () {
expect(
() => picker.pickImage(source: ImageSource.camera, maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickImage(source: ImageSource.camera, maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
log.returnValue = null;
expect(await picker.pickImage(source: ImageSource.gallery), isNull);
expect(await picker.pickImage(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
await picker.pickImage(source: ImageSource.camera);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('camera position can set to front', () async {
await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.front,
'requestFullMetadata': true,
}),
],
);
});
});
group('#pickMultiImage', () {
test('calls the method correctly', () async {
log.returnValue = <String>['0', '1'];
await picker.pickMultiImage();
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width and height arguments correctly', () async {
log.returnValue = <String>['0', '1'];
await picker.pickMultiImage();
await picker.pickMultiImage(
maxWidth: 10.0,
);
await picker.pickMultiImage(
maxHeight: 10.0,
);
await picker.pickMultiImage(
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickMultiImage(
maxWidth: 10.0,
imageQuality: 70,
);
await picker.pickMultiImage(
maxHeight: 10.0,
imageQuality: 70,
);
await picker.pickMultiImage(
maxWidth: 10.0,
maxHeight: 20.0,
imageQuality: 70,
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a negative width or height argument', () {
expect(
() => picker.pickMultiImage(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickMultiImage(maxHeight: -1.0),
throwsArgumentError,
);
});
test('does not accept a invalid imageQuality argument', () {
expect(
() => picker.pickMultiImage(imageQuality: -1),
throwsArgumentError,
);
expect(
() => picker.pickMultiImage(imageQuality: 101),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
log.returnValue = null;
expect(await picker.pickMultiImage(), isNull);
});
});
group('#pickVideo', () {
test('passes the image source argument correctly', () async {
await picker.pickVideo(source: ImageSource.camera);
await picker.pickVideo(source: ImageSource.gallery);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'cameraDevice': SourceCamera.rear,
'maxDuration': null,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.gallery,
'cameraDevice': SourceCamera.rear,
'maxDuration': null,
}),
],
);
});
test('passes the duration argument correctly', () async {
await picker.pickVideo(source: ImageSource.camera);
await picker.pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 10),
);
await picker.pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(minutes: 1),
);
await picker.pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(hours: 1),
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': null,
'cameraDevice': SourceCamera.rear,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': 10,
'cameraDevice': SourceCamera.rear,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': 60,
'cameraDevice': SourceCamera.rear,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': 3600,
'cameraDevice': SourceCamera.rear,
}),
],
);
});
test('handles a null video path response gracefully', () async {
log.returnValue = null;
expect(await picker.pickVideo(source: ImageSource.gallery), isNull);
expect(await picker.pickVideo(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
await picker.pickVideo(source: ImageSource.camera);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'cameraDevice': SourceCamera.rear,
'maxDuration': null,
}),
],
);
});
test('camera position can set to front', () async {
await picker.pickVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': null,
'cameraDevice': SourceCamera.front,
}),
],
);
});
});
group('#getImage', () {
test('passes the image source argument correctly', () async {
await picker.getImage(source: ImageSource.camera);
await picker.getImage(source: ImageSource.gallery);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.gallery,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
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.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a invalid imageQuality argument', () {
expect(
() => picker.getImage(imageQuality: -1, source: ImageSource.gallery),
throwsArgumentError,
);
expect(
() => picker.getImage(imageQuality: 101, source: ImageSource.gallery),
throwsArgumentError,
);
expect(
() => picker.getImage(imageQuality: -1, source: ImageSource.camera),
throwsArgumentError,
);
expect(
() => picker.getImage(imageQuality: 101, source: ImageSource.camera),
throwsArgumentError,
);
});
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 {
log.returnValue = 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.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.front,
'requestFullMetadata': true,
}),
],
);
});
});
group('#getMultiImage', () {
test('calls the method correctly', () async {
log.returnValue = <String>['0', '1'];
await picker.getMultiImage();
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width and height arguments correctly', () async {
log.returnValue = <String>['0', '1'];
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.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a negative width or height argument', () {
log.returnValue = <String>['0', '1'];
expect(
() => picker.getMultiImage(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.getMultiImage(maxHeight: -1.0),
throwsArgumentError,
);
});
test('does not accept a invalid imageQuality argument', () {
log.returnValue = <String>['0', '1'];
expect(
() => picker.getMultiImage(imageQuality: -1),
throwsArgumentError,
);
expect(
() => picker.getMultiImage(imageQuality: 101),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
log.returnValue = null;
expect(await picker.getMultiImage(), isNull);
expect(await picker.getMultiImage(), isNull);
});
});
group('#getVideo', () {
test('passes the image source argument correctly', () async {
await picker.getVideo(source: ImageSource.camera);
await picker.getVideo(source: ImageSource.gallery);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'cameraDevice': SourceCamera.rear,
'maxDuration': null,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.gallery,
'cameraDevice': SourceCamera.rear,
'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.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': null,
'cameraDevice': SourceCamera.rear,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': 10,
'cameraDevice': SourceCamera.rear,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': 60,
'cameraDevice': SourceCamera.rear,
}),
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': 3600,
'cameraDevice': SourceCamera.rear,
}),
],
);
});
test('handles a null video path response gracefully', () async {
log.returnValue = 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.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'cameraDevice': SourceCamera.rear,
'maxDuration': null,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickVideo', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxDuration': null,
'cameraDevice': SourceCamera.front,
}),
],
);
});
});
group('#getImageFromSource', () {
test('passes the image source argument correctly', () async {
await picker.getImageFromSource(source: ImageSource.camera);
await picker.getImageFromSource(source: ImageSource.gallery);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.gallery,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width and height arguments correctly', () async {
await picker.getImageFromSource(source: ImageSource.camera);
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(maxWidth: 10.0),
);
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(maxHeight: 10.0),
);
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(
maxWidth: 10.0,
maxHeight: 20.0,
),
);
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(
maxWidth: 10.0,
imageQuality: 70,
),
);
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(
maxHeight: 10.0,
imageQuality: 70,
),
);
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(
maxWidth: 10.0,
maxHeight: 20.0,
imageQuality: 70,
),
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a invalid imageQuality argument', () {
expect(
() => picker.getImageFromSource(
source: ImageSource.gallery,
options: const ImagePickerOptions(imageQuality: -1),
),
throwsArgumentError,
);
expect(
() => picker.getImageFromSource(
source: ImageSource.gallery,
options: const ImagePickerOptions(imageQuality: 101),
),
throwsArgumentError,
);
expect(
() => picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(imageQuality: -1),
),
throwsArgumentError,
);
expect(
() => picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(imageQuality: 101),
),
throwsArgumentError,
);
});
test('does not accept a negative width or height argument', () {
expect(
() => picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(maxWidth: -1.0),
),
throwsArgumentError,
);
expect(
() => picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(maxHeight: -1.0),
),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
log.returnValue = null;
expect(
await picker.getImageFromSource(source: ImageSource.gallery), isNull);
expect(
await picker.getImageFromSource(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
await picker.getImageFromSource(source: ImageSource.camera);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getImageFromSource(
source: ImageSource.camera,
options:
const ImagePickerOptions(preferredCameraDevice: CameraDevice.front),
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.camera,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.front,
'requestFullMetadata': true,
}),
],
);
});
test('Request full metadata argument defaults to true', () async {
await picker.getImageFromSource(source: ImageSource.gallery);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.gallery,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': true,
}),
],
);
});
test('passes the request full metadata argument correctly', () async {
await picker.getImageFromSource(
source: ImageSource.gallery,
options: const ImagePickerOptions(requestFullMetadata: false),
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickImage', arguments: <String, dynamic>{
'source': SourceType.gallery,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': SourceCamera.rear,
'requestFullMetadata': false,
}),
],
);
});
});
group('#getMultiImageWithOptions', () {
test('calls the method correctly', () async {
log.returnValue = <String>['0', '1'];
await picker.getMultiImageWithOptions();
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width and height arguments correctly', () async {
log.returnValue = <String>['0', '1'];
await picker.getMultiImageWithOptions();
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(maxWidth: 10.0),
),
);
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(maxHeight: 10.0),
),
);
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(maxWidth: 10.0, maxHeight: 20.0),
),
);
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(maxWidth: 10.0, imageQuality: 70),
),
);
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(maxHeight: 10.0, imageQuality: 70),
),
);
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(
maxWidth: 10.0,
maxHeight: 20.0,
imageQuality: 70,
),
),
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a negative width or height argument', () {
log.returnValue = <String>['0', '1'];
expect(
() => picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(maxWidth: -1.0),
),
),
throwsArgumentError,
);
expect(
() => picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(maxHeight: -1.0),
),
),
throwsArgumentError,
);
});
test('does not accept a invalid imageQuality argument', () {
log.returnValue = <String>['0', '1'];
expect(
() => picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(imageQuality: -1),
),
),
throwsArgumentError,
);
expect(
() => picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(imageQuality: 101),
),
),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
log.returnValue = null;
expect(await picker.getMultiImageWithOptions(), isEmpty);
});
test('Request full metadata argument defaults to true', () async {
log.returnValue = <String>['0', '1'];
await picker.getMultiImageWithOptions();
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('Passes the request full metadata argument correctly', () async {
log.returnValue = <String>['0', '1'];
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(requestFullMetadata: false),
),
);
expect(
log.calls,
<_LoggedMethodCall>[
const _LoggedMethodCall('pickMultiImage',
arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': false,
}),
],
);
});
});
}
| plugins/packages/image_picker/image_picker_ios/test/image_picker_ios_test.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/test/image_picker_ios_test.dart",
"repo_id": "plugins",
"token_count": 21245
} | 1,162 |
## 0.2.4+1
* Updates Google Play Billing Library to 5.1.0.
* Updates androidx.annotation to 1.5.0.
## 0.2.4
* Updates minimum Flutter version to 3.0.
* Ignores a lint in the example app for backwards compatibility.
## 0.2.3+9
* Updates `androidx.test.espresso:espresso-core` to 3.5.1.
## 0.2.3+8
* Updates code for stricter lint checks.
## 0.2.3+7
* Updates code for new analysis options.
## 0.2.3+6
* Updates android gradle plugin to 7.3.1.
## 0.2.3+5
* Updates imports for `prefer_relative_imports`.
## 0.2.3+4
* Updates minimum Flutter version to 2.10.
* Adds IMMEDIATE_AND_CHARGE_FULL_PRICE to the `ProrationMode`.
## 0.2.3+3
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 0.2.3+2
* Fixes incorrect json key in `queryPurchasesAsync` that fixes restore purchases functionality.
## 0.2.3+1
* Updates `json_serializable` to fix warnings in generated code.
## 0.2.3
* Upgrades Google Play Billing Library to 5.0
* Migrates APIs to support breaking changes in new Google Play Billing API
* `PurchaseWrapper` and `PurchaseHistoryRecordWrapper` now handles `skus` a list of sku strings. `sku` is deprecated.
## 0.2.2+8
* Ignores deprecation warnings for upcoming styleFrom button API changes.
## 0.2.2+7
* Updates references to the obsolete master branch.
## 0.2.2+6
* Enables mocking models by changing overridden operator == parameter type from `dynamic` to `Object`.
## 0.2.2+5
* Minor fixes for new analysis options.
## 0.2.2+4
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.2.2+3
* Migrates from `ui.hash*` to `Object.hash*`.
* Updates minimum Flutter version to 2.5.0.
## 0.2.2+2
* Internal code cleanup for stricter analysis options.
## 0.2.2+1
* Removes the dependency on `meta`.
## 0.2.2
* Fixes the `purchaseStream` incorrectly reporting `PurchaseStatus.error` when user upgrades subscription by deferred proration mode.
## 0.2.1
* Deprecated the `InAppPurchaseAndroidPlatformAddition.enablePendingPurchases()` method and `InAppPurchaseAndroidPlatformAddition.enablePendingPurchase` property. Since Google Play no longer accepts App submissions that don't support pending purchases it is no longer necessary to acknowledge this through code.
* Updates example app Android compileSdkVersion to 31.
## 0.2.0
* BREAKING CHANGE : Refactor to handle new `PurchaseStatus` named `canceled`. This means developers
can distinguish between an error and user cancellation.
## 0.1.6
* Require Dart SDK >= 2.14.
* Update `json_annotation` dependency to `^4.3.0`.
## 0.1.5+1
* Fix a broken link in the README.
## 0.1.5
* Introduced the `SkuDetailsWrapper.introductoryPriceAmountMicros` field of the correct type (`int`) and deprecated the `SkuDetailsWrapper.introductoryPriceMicros` field.
* Update dev_dependency `build_runner` to ^2.0.0 and `json_serializable` to ^5.0.2.
## 0.1.4+7
* Ensure that the `SkuDetailsWrapper.introductoryPriceMicros` is populated correctly.
## 0.1.4+6
* Ensure that purchases correctly indicate whether they are acknowledged or not. The `PurchaseDetails.pendingCompletePurchase` field now correctly indicates if the purchase still needs to be completed.
## 0.1.4+5
* Add `implements` to pubspec.
* Updated Android lint settings.
## 0.1.4+4
* Removed dependency on the `test` package.
## 0.1.4+3
* Updated installation instructions in README.
## 0.1.4+2
* Added price currency symbol to SkuDetailsWrapper.
## 0.1.4+1
* Fixed typos.
## 0.1.4
* Added support for launchPriceChangeConfirmationFlow in the BillingClientWrapper and in InAppPurchaseAndroidPlatformAddition.
## 0.1.3+1
* Add payment proxy.
## 0.1.3
* Added support for isFeatureSupported in the BillingClientWrapper and in InAppPurchaseAndroidPlatformAddition.
## 0.1.2
* Added support for the obfuscatedAccountId and obfuscatedProfileId in the PurchaseWrapper.
## 0.1.1
* Added support to request a list of active subscriptions and non-consumed one-time purchases on Android, through the `InAppPurchaseAndroidPlatformAddition.queryPastPurchases` method.
## 0.1.0+1
* Migrate maven repository from jcenter to mavenCentral.
## 0.1.0
* Initial open-source release.
| plugins/packages/in_app_purchase/in_app_purchase_android/CHANGELOG.md/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 1384
} | 1,163 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.inapppurchase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import androidx.annotation.NonNull;
import com.android.billingclient.api.AccountIdentifiers;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.SkuDetails;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
public class TranslatorTest {
private static final String SKU_DETAIL_EXAMPLE_JSON =
"{\"productId\":\"example\",\"type\":\"inapp\",\"price\":\"$0.99\",\"price_amount_micros\":990000,\"price_currency_code\":\"USD\",\"title\":\"Example title\",\"description\":\"Example description.\",\"original_price\":\"$0.99\",\"original_price_micros\":990000}";
private static final String PURCHASE_EXAMPLE_JSON =
"{\"orderId\":\"foo\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\", \"obfuscatedAccountId\":\"Account101\", \"obfuscatedProfileId\": \"Profile105\"}";
@Before
public void setup() {
Locale locale = new Locale("en", "us");
Locale.setDefault(locale);
}
@Test
public void fromSkuDetail() throws JSONException {
final SkuDetails expected = new SkuDetails(SKU_DETAIL_EXAMPLE_JSON);
Map<String, Object> serialized = Translator.fromSkuDetail(expected);
assertSerialized(expected, serialized);
}
@Test
public void fromSkuDetailsList() throws JSONException {
final String SKU_DETAIL_EXAMPLE_2_JSON =
"{\"productId\":\"example2\",\"type\":\"inapp\",\"price\":\"$0.99\",\"price_amount_micros\":990000,\"price_currency_code\":\"USD\",\"title\":\"Example title\",\"description\":\"Example description.\",\"original_price\":\"$0.99\",\"original_price_micros\":990000}";
final List<SkuDetails> expected =
Arrays.asList(
new SkuDetails(SKU_DETAIL_EXAMPLE_JSON), new SkuDetails(SKU_DETAIL_EXAMPLE_2_JSON));
final List<HashMap<String, Object>> serialized = Translator.fromSkuDetailsList(expected);
assertEquals(expected.size(), serialized.size());
assertSerialized(expected.get(0), serialized.get(0));
assertSerialized(expected.get(1), serialized.get(1));
}
@Test
public void fromSkuDetailsList_null() {
assertEquals(Collections.emptyList(), Translator.fromSkuDetailsList(null));
}
@Test
public void fromPurchase() throws JSONException {
final Purchase expected = new Purchase(PURCHASE_EXAMPLE_JSON, "signature");
assertSerialized(expected, Translator.fromPurchase(expected));
}
@Test
public void fromPurchaseWithoutAccountIds() throws JSONException {
final Purchase expected =
new PurchaseWithoutAccountIdentifiers(PURCHASE_EXAMPLE_JSON, "signature");
Map<String, Object> serialized = Translator.fromPurchase(expected);
assertNotNull(serialized.get("orderId"));
assertNull(serialized.get("obfuscatedProfileId"));
assertNull(serialized.get("obfuscatedAccountId"));
}
@Test
public void fromPurchaseHistoryRecord() throws JSONException {
final PurchaseHistoryRecord expected =
new PurchaseHistoryRecord(PURCHASE_EXAMPLE_JSON, "signature");
assertSerialized(expected, Translator.fromPurchaseHistoryRecord(expected));
}
@Test
public void fromPurchasesHistoryRecordList() throws JSONException {
final String purchase2Json =
"{\"orderId\":\"foo2\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\"}";
final String signature = "signature";
final List<PurchaseHistoryRecord> expected =
Arrays.asList(
new PurchaseHistoryRecord(PURCHASE_EXAMPLE_JSON, signature),
new PurchaseHistoryRecord(purchase2Json, signature));
final List<HashMap<String, Object>> serialized =
Translator.fromPurchaseHistoryRecordList(expected);
assertEquals(expected.size(), serialized.size());
assertSerialized(expected.get(0), serialized.get(0));
assertSerialized(expected.get(1), serialized.get(1));
}
@Test
public void fromPurchasesHistoryRecordList_null() {
assertEquals(Collections.emptyList(), Translator.fromPurchaseHistoryRecordList(null));
}
@Test
public void fromPurchasesList() throws JSONException {
final String purchase2Json =
"{\"orderId\":\"foo2\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\"}";
final String signature = "signature";
final List<Purchase> expected =
Arrays.asList(
new Purchase(PURCHASE_EXAMPLE_JSON, signature), new Purchase(purchase2Json, signature));
final List<HashMap<String, Object>> serialized = Translator.fromPurchasesList(expected);
assertEquals(expected.size(), serialized.size());
assertSerialized(expected.get(0), serialized.get(0));
assertSerialized(expected.get(1), serialized.get(1));
}
@Test
public void fromPurchasesList_null() {
assertEquals(Collections.emptyList(), Translator.fromPurchasesList(null));
}
@Test
public void fromBillingResult() throws JSONException {
BillingResult newBillingResult =
BillingResult.newBuilder()
.setDebugMessage("dummy debug message")
.setResponseCode(BillingClient.BillingResponseCode.OK)
.build();
Map<String, Object> billingResultMap = Translator.fromBillingResult(newBillingResult);
assertEquals(billingResultMap.get("responseCode"), newBillingResult.getResponseCode());
assertEquals(billingResultMap.get("debugMessage"), newBillingResult.getDebugMessage());
}
@Test
public void fromBillingResult_debugMessageNull() throws JSONException {
BillingResult newBillingResult =
BillingResult.newBuilder().setResponseCode(BillingClient.BillingResponseCode.OK).build();
Map<String, Object> billingResultMap = Translator.fromBillingResult(newBillingResult);
assertEquals(billingResultMap.get("responseCode"), newBillingResult.getResponseCode());
assertEquals(billingResultMap.get("debugMessage"), newBillingResult.getDebugMessage());
}
@Test
public void currencyCodeFromSymbol() {
assertEquals("$", Translator.currencySymbolFromCode("USD"));
try {
Translator.currencySymbolFromCode("EUROPACOIN");
fail("Translator should throw an exception");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
private void assertSerialized(SkuDetails expected, Map<String, Object> serialized) {
assertEquals(expected.getDescription(), serialized.get("description"));
assertEquals(expected.getFreeTrialPeriod(), serialized.get("freeTrialPeriod"));
assertEquals(expected.getIntroductoryPrice(), serialized.get("introductoryPrice"));
assertEquals(
expected.getIntroductoryPriceAmountMicros(),
serialized.get("introductoryPriceAmountMicros"));
assertEquals(expected.getIntroductoryPriceCycles(), serialized.get("introductoryPriceCycles"));
assertEquals(expected.getIntroductoryPricePeriod(), serialized.get("introductoryPricePeriod"));
assertEquals(expected.getPrice(), serialized.get("price"));
assertEquals(expected.getPriceAmountMicros(), serialized.get("priceAmountMicros"));
assertEquals(expected.getPriceCurrencyCode(), serialized.get("priceCurrencyCode"));
assertEquals("$", serialized.get("priceCurrencySymbol"));
assertEquals(expected.getSku(), serialized.get("sku"));
assertEquals(expected.getSubscriptionPeriod(), serialized.get("subscriptionPeriod"));
assertEquals(expected.getTitle(), serialized.get("title"));
assertEquals(expected.getType(), serialized.get("type"));
assertEquals(expected.getOriginalPrice(), serialized.get("originalPrice"));
assertEquals(
expected.getOriginalPriceAmountMicros(), serialized.get("originalPriceAmountMicros"));
}
private void assertSerialized(Purchase expected, Map<String, Object> serialized) {
assertEquals(expected.getOrderId(), serialized.get("orderId"));
assertEquals(expected.getPackageName(), serialized.get("packageName"));
assertEquals(expected.getPurchaseTime(), serialized.get("purchaseTime"));
assertEquals(expected.getPurchaseToken(), serialized.get("purchaseToken"));
assertEquals(expected.getSignature(), serialized.get("signature"));
assertEquals(expected.getOriginalJson(), serialized.get("originalJson"));
assertEquals(expected.getSkus(), serialized.get("skus"));
assertEquals(expected.getDeveloperPayload(), serialized.get("developerPayload"));
assertEquals(expected.isAcknowledged(), serialized.get("isAcknowledged"));
assertEquals(expected.getPurchaseState(), serialized.get("purchaseState"));
assertNotNull(expected.getAccountIdentifiers().getObfuscatedAccountId());
assertEquals(
expected.getAccountIdentifiers().getObfuscatedAccountId(),
serialized.get("obfuscatedAccountId"));
assertNotNull(expected.getAccountIdentifiers().getObfuscatedProfileId());
assertEquals(
expected.getAccountIdentifiers().getObfuscatedProfileId(),
serialized.get("obfuscatedProfileId"));
}
private void assertSerialized(PurchaseHistoryRecord expected, Map<String, Object> serialized) {
assertEquals(expected.getPurchaseTime(), serialized.get("purchaseTime"));
assertEquals(expected.getPurchaseToken(), serialized.get("purchaseToken"));
assertEquals(expected.getSignature(), serialized.get("signature"));
assertEquals(expected.getOriginalJson(), serialized.get("originalJson"));
assertEquals(expected.getSkus(), serialized.get("skus"));
assertEquals(expected.getDeveloperPayload(), serialized.get("developerPayload"));
}
}
class PurchaseWithoutAccountIdentifiers extends Purchase {
public PurchaseWithoutAccountIdentifiers(@NonNull String s, @NonNull String s1)
throws JSONException {
super(s, s1);
}
@Override
public AccountIdentifiers getAccountIdentifiers() {
return null;
}
}
| plugins/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/TranslatorTest.java/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/TranslatorTest.java",
"repo_id": "plugins",
"token_count": 3535
} | 1,164 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/src/types/google_play_product_details.dart';
import 'package:test/test.dart';
const SkuDetailsWrapper dummySkuDetails = SkuDetailsWrapper(
description: 'description',
freeTrialPeriod: 'freeTrialPeriod',
introductoryPrice: 'introductoryPrice',
introductoryPriceAmountMicros: 990000,
introductoryPriceCycles: 1,
introductoryPricePeriod: 'introductoryPricePeriod',
price: 'price',
priceAmountMicros: 1000,
priceCurrencyCode: 'priceCurrencyCode',
priceCurrencySymbol: r'$',
sku: 'sku',
subscriptionPeriod: 'subscriptionPeriod',
title: 'title',
type: SkuType.inapp,
originalPrice: 'originalPrice',
originalPriceAmountMicros: 1000,
);
void main() {
group('SkuDetailsWrapper', () {
test('converts from map', () {
const SkuDetailsWrapper expected = dummySkuDetails;
final SkuDetailsWrapper parsed =
SkuDetailsWrapper.fromJson(buildSkuMap(expected));
expect(parsed, equals(expected));
});
});
group('SkuDetailsResponseWrapper', () {
test('parsed from map', () {
const BillingResponse responseCode = BillingResponse.ok;
const String debugMessage = 'dummy message';
final List<SkuDetailsWrapper> skusDetails = <SkuDetailsWrapper>[
dummySkuDetails,
dummySkuDetails
];
const BillingResultWrapper result = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
final SkuDetailsResponseWrapper expected = SkuDetailsResponseWrapper(
billingResult: result, skuDetailsList: skusDetails);
final SkuDetailsResponseWrapper parsed =
SkuDetailsResponseWrapper.fromJson(<String, dynamic>{
'billingResult': <String, dynamic>{
'responseCode': const BillingResponseConverter().toJson(responseCode),
'debugMessage': debugMessage,
},
'skuDetailsList': <Map<String, dynamic>>[
buildSkuMap(dummySkuDetails),
buildSkuMap(dummySkuDetails)
]
});
expect(parsed.billingResult, equals(expected.billingResult));
expect(parsed.skuDetailsList, containsAll(expected.skuDetailsList));
});
test('toProductDetails() should return correct Product object', () {
final SkuDetailsWrapper wrapper =
SkuDetailsWrapper.fromJson(buildSkuMap(dummySkuDetails));
final GooglePlayProductDetails product =
GooglePlayProductDetails.fromSkuDetails(wrapper);
expect(product.title, wrapper.title);
expect(product.description, wrapper.description);
expect(product.id, wrapper.sku);
expect(product.price, wrapper.price);
expect(product.skuDetails, wrapper);
});
test('handles empty list of skuDetails', () {
const BillingResponse responseCode = BillingResponse.error;
const String debugMessage = 'dummy message';
final List<SkuDetailsWrapper> skusDetails = <SkuDetailsWrapper>[];
const BillingResultWrapper billingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
final SkuDetailsResponseWrapper expected = SkuDetailsResponseWrapper(
billingResult: billingResult, skuDetailsList: skusDetails);
final SkuDetailsResponseWrapper parsed =
SkuDetailsResponseWrapper.fromJson(<String, dynamic>{
'billingResult': <String, dynamic>{
'responseCode': const BillingResponseConverter().toJson(responseCode),
'debugMessage': debugMessage,
},
'skuDetailsList': const <Map<String, dynamic>>[]
});
expect(parsed.billingResult, equals(expected.billingResult));
expect(parsed.skuDetailsList, containsAll(expected.skuDetailsList));
});
test('fromJson creates an object with default values', () {
final SkuDetailsResponseWrapper skuDetails =
SkuDetailsResponseWrapper.fromJson(const <String, dynamic>{});
expect(
skuDetails.billingResult,
equals(const BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: kInvalidBillingResultErrorMessage)));
expect(skuDetails.skuDetailsList, isEmpty);
});
});
group('BillingResultWrapper', () {
test('fromJson on empty map creates an object with default values', () {
final BillingResultWrapper billingResult =
BillingResultWrapper.fromJson(const <String, dynamic>{});
expect(billingResult.debugMessage, kInvalidBillingResultErrorMessage);
expect(billingResult.responseCode, BillingResponse.error);
});
test('fromJson on null creates an object with default values', () {
final BillingResultWrapper billingResult =
BillingResultWrapper.fromJson(null);
expect(billingResult.debugMessage, kInvalidBillingResultErrorMessage);
expect(billingResult.responseCode, BillingResponse.error);
});
test('operator == of SkuDetailsWrapper works fine', () {
const SkuDetailsWrapper firstSkuDetailsInstance = SkuDetailsWrapper(
description: 'description',
freeTrialPeriod: 'freeTrialPeriod',
introductoryPrice: 'introductoryPrice',
introductoryPriceAmountMicros: 990000,
introductoryPriceCycles: 1,
introductoryPricePeriod: 'introductoryPricePeriod',
price: 'price',
priceAmountMicros: 1000,
priceCurrencyCode: 'priceCurrencyCode',
priceCurrencySymbol: r'$',
sku: 'sku',
subscriptionPeriod: 'subscriptionPeriod',
title: 'title',
type: SkuType.inapp,
originalPrice: 'originalPrice',
originalPriceAmountMicros: 1000,
);
const SkuDetailsWrapper secondSkuDetailsInstance = SkuDetailsWrapper(
description: 'description',
freeTrialPeriod: 'freeTrialPeriod',
introductoryPrice: 'introductoryPrice',
introductoryPriceAmountMicros: 990000,
introductoryPriceCycles: 1,
introductoryPricePeriod: 'introductoryPricePeriod',
price: 'price',
priceAmountMicros: 1000,
priceCurrencyCode: 'priceCurrencyCode',
priceCurrencySymbol: r'$',
sku: 'sku',
subscriptionPeriod: 'subscriptionPeriod',
title: 'title',
type: SkuType.inapp,
originalPrice: 'originalPrice',
originalPriceAmountMicros: 1000,
);
expect(firstSkuDetailsInstance == secondSkuDetailsInstance, isTrue);
});
test('operator == of BillingResultWrapper works fine', () {
const BillingResultWrapper firstBillingResultInstance =
BillingResultWrapper(
responseCode: BillingResponse.ok,
debugMessage: 'debugMessage',
);
const BillingResultWrapper secondBillingResultInstance =
BillingResultWrapper(
responseCode: BillingResponse.ok,
debugMessage: 'debugMessage',
);
expect(firstBillingResultInstance == secondBillingResultInstance, isTrue);
});
});
}
Map<String, dynamic> buildSkuMap(SkuDetailsWrapper original) {
return <String, dynamic>{
'description': original.description,
'freeTrialPeriod': original.freeTrialPeriod,
'introductoryPrice': original.introductoryPrice,
'introductoryPriceAmountMicros': original.introductoryPriceAmountMicros,
'introductoryPriceCycles': original.introductoryPriceCycles,
'introductoryPricePeriod': original.introductoryPricePeriod,
'price': original.price,
'priceAmountMicros': original.priceAmountMicros,
'priceCurrencyCode': original.priceCurrencyCode,
'priceCurrencySymbol': original.priceCurrencySymbol,
'sku': original.sku,
'subscriptionPeriod': original.subscriptionPeriod,
'title': original.title,
'type': original.type.toString().substring(8),
'originalPrice': original.originalPrice,
'originalPriceAmountMicros': original.originalPriceAmountMicros,
};
}
| plugins/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/sku_details_wrapper_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/sku_details_wrapper_test.dart",
"repo_id": "plugins",
"token_count": 2965
} | 1,165 |
// 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 '../errors/in_app_purchase_error.dart';
import 'product_details.dart';
/// The response returned by [InAppPurchasePlatform.queryProductDetails].
///
/// A list of [ProductDetails] can be obtained from the this response.
class ProductDetailsResponse {
/// Creates a new [ProductDetailsResponse] with the provided response details.
ProductDetailsResponse(
{required this.productDetails, required this.notFoundIDs, this.error});
/// Each [ProductDetails] uniquely matches one valid identifier in [identifiers] of [InAppPurchasePlatform.queryProductDetails].
final List<ProductDetails> productDetails;
/// The list of identifiers that are in the `identifiers` of [InAppPurchasePlatform.queryProductDetails] but failed to be fetched.
///
/// There are multiple platform-specific reasons that product information could fail to be fetched,
/// ranging from products not being correctly configured in the storefront to the queried IDs not existing.
final List<String> notFoundIDs;
/// A caught platform exception thrown while querying the purchases.
///
/// The value is `null` if there is no error.
///
/// It's possible for this to be null but for there still to be notFoundIds in cases where the request itself was a success but the
/// requested IDs could not be found.
final IAPError? error;
}
| plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details_response.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details_response.dart",
"repo_id": "plugins",
"token_count": 376
} | 1,166 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_storekit/src/channel.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'sk_test_stub_objects.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform();
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform, fakeStoreKitPlatform.onMethodCall);
});
setUp(() {});
tearDown(() {
fakeStoreKitPlatform.testReturnNull = false;
fakeStoreKitPlatform.queueIsActive = null;
fakeStoreKitPlatform.getReceiptFailTest = false;
});
group('sk_request_maker', () {
test('get products method channel', () async {
final SkProductResponseWrapper productResponseWrapper =
await SKRequestMaker().startProductRequest(<String>['xxx']);
expect(
productResponseWrapper.products,
isNotEmpty,
);
expect(
productResponseWrapper.products.first.priceLocale.currencySymbol,
r'$',
);
expect(
productResponseWrapper.products.first.priceLocale.currencySymbol,
isNot('A'),
);
expect(
productResponseWrapper.products.first.priceLocale.currencyCode,
'USD',
);
expect(
productResponseWrapper.products.first.priceLocale.countryCode,
'US',
);
expect(
productResponseWrapper.invalidProductIdentifiers,
isNotEmpty,
);
expect(
fakeStoreKitPlatform.startProductRequestParam,
<String>['xxx'],
);
});
test('get products method channel should throw exception', () async {
fakeStoreKitPlatform.getProductRequestFailTest = true;
expect(
SKRequestMaker().startProductRequest(<String>['xxx']),
throwsException,
);
fakeStoreKitPlatform.getProductRequestFailTest = false;
});
test('refreshed receipt', () async {
final int receiptCountBefore = fakeStoreKitPlatform.refreshReceipt;
await SKRequestMaker().startRefreshReceiptRequest(
receiptProperties: <String, dynamic>{'isExpired': true});
expect(fakeStoreKitPlatform.refreshReceipt, receiptCountBefore + 1);
expect(fakeStoreKitPlatform.refreshReceiptParam,
<String, dynamic>{'isExpired': true});
});
test('should get null receipt if any exceptions are raised', () async {
fakeStoreKitPlatform.getReceiptFailTest = true;
expect(() async => SKReceiptManager.retrieveReceiptData(),
throwsA(const TypeMatcher<PlatformException>()));
});
});
group('sk_receipt_manager', () {
test('should get receipt (faking it by returning a `receipt data` string)',
() async {
final String receiptData = await SKReceiptManager.retrieveReceiptData();
expect(receiptData, 'receipt data');
});
});
group('sk_payment_queue', () {
test('canMakePayment should return true', () async {
expect(await SKPaymentQueueWrapper.canMakePayments(), true);
});
test('canMakePayment returns false if method channel returns null',
() async {
fakeStoreKitPlatform.testReturnNull = true;
expect(await SKPaymentQueueWrapper.canMakePayments(), false);
});
test('transactions should return a valid list of transactions', () async {
expect(await SKPaymentQueueWrapper().transactions(), isNotEmpty);
});
test(
'throws if observer is not set for payment queue before adding payment',
() async {
expect(SKPaymentQueueWrapper().addPayment(dummyPayment),
throwsAssertionError);
});
test('should add payment to the payment queue', () async {
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
final TestPaymentTransactionObserver observer =
TestPaymentTransactionObserver();
queue.setTransactionObserver(observer);
await queue.addPayment(dummyPayment);
expect(fakeStoreKitPlatform.payments.first, equals(dummyPayment));
});
test('should finish transaction', () async {
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
final TestPaymentTransactionObserver observer =
TestPaymentTransactionObserver();
queue.setTransactionObserver(observer);
await queue.finishTransaction(dummyTransaction);
expect(fakeStoreKitPlatform.transactionsFinished.first,
equals(dummyTransaction.toFinishMap()));
});
test('should restore transaction', () async {
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
final TestPaymentTransactionObserver observer =
TestPaymentTransactionObserver();
queue.setTransactionObserver(observer);
await queue.restoreTransactions(applicationUserName: 'aUserID');
expect(fakeStoreKitPlatform.applicationNameHasTransactionRestored,
'aUserID');
});
test('startObservingTransactionQueue should call methodChannel', () async {
expect(fakeStoreKitPlatform.queueIsActive, isNot(true));
await SKPaymentQueueWrapper().startObservingTransactionQueue();
expect(fakeStoreKitPlatform.queueIsActive, true);
});
test('stopObservingTransactionQueue should call methodChannel', () async {
expect(fakeStoreKitPlatform.queueIsActive, isNot(false));
await SKPaymentQueueWrapper().stopObservingTransactionQueue();
expect(fakeStoreKitPlatform.queueIsActive, false);
});
test('setDelegate should call methodChannel', () async {
expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, false);
await SKPaymentQueueWrapper().setDelegate(TestPaymentQueueDelegate());
expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, true);
await SKPaymentQueueWrapper().setDelegate(null);
expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, false);
});
test('showPriceConsentIfNeeded should call methodChannel', () async {
expect(fakeStoreKitPlatform.showPriceConsentIfNeeded, false);
await SKPaymentQueueWrapper().showPriceConsentIfNeeded();
expect(fakeStoreKitPlatform.showPriceConsentIfNeeded, true);
});
});
group('Code Redemption Sheet', () {
test('presentCodeRedemptionSheet should not throw', () async {
expect(fakeStoreKitPlatform.presentCodeRedemption, false);
await SKPaymentQueueWrapper().presentCodeRedemptionSheet();
expect(fakeStoreKitPlatform.presentCodeRedemption, true);
fakeStoreKitPlatform.presentCodeRedemption = false;
});
});
}
class FakeStoreKitPlatform {
FakeStoreKitPlatform() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, onMethodCall);
}
// get product request
List<dynamic> startProductRequestParam = <dynamic>[];
bool getProductRequestFailTest = false;
bool testReturnNull = false;
// get receipt request
bool getReceiptFailTest = false;
// refresh receipt request
int refreshReceipt = 0;
late Map<String, dynamic> refreshReceiptParam;
// payment queue
List<SKPaymentWrapper> payments = <SKPaymentWrapper>[];
List<Map<String, String>> transactionsFinished = <Map<String, String>>[];
String applicationNameHasTransactionRestored = '';
// present Code Redemption
bool presentCodeRedemption = false;
// show price consent sheet
bool showPriceConsentIfNeeded = false;
// indicate if the payment queue delegate is registered
bool isPaymentQueueDelegateRegistered = false;
// Listen to purchase updates
bool? queueIsActive;
Future<dynamic> onMethodCall(MethodCall call) {
switch (call.method) {
// request makers
case '-[InAppPurchasePlugin startProductRequest:result:]':
startProductRequestParam = call.arguments as List<dynamic>;
if (getProductRequestFailTest) {
return Future<dynamic>.value();
}
return Future<Map<String, dynamic>>.value(
buildProductResponseMap(dummyProductResponseWrapper));
case '-[InAppPurchasePlugin refreshReceipt:result:]':
refreshReceipt++;
refreshReceiptParam = Map.castFrom<dynamic, dynamic, String, dynamic>(
call.arguments as Map<dynamic, dynamic>);
return Future<void>.sync(() {});
// receipt manager
case '-[InAppPurchasePlugin retrieveReceiptData:result:]':
if (getReceiptFailTest) {
throw Exception('some arbitrary error');
}
return Future<String>.value('receipt data');
// payment queue
case '-[SKPaymentQueue canMakePayments:]':
if (testReturnNull) {
return Future<dynamic>.value();
}
return Future<bool>.value(true);
case '-[SKPaymentQueue transactions]':
return Future<List<dynamic>>.value(
<dynamic>[buildTransactionMap(dummyTransaction)]);
case '-[InAppPurchasePlugin addPayment:result:]':
payments.add(SKPaymentWrapper.fromJson(Map<String, dynamic>.from(
call.arguments as Map<dynamic, dynamic>)));
return Future<void>.sync(() {});
case '-[InAppPurchasePlugin finishTransaction:result:]':
transactionsFinished.add(
Map<String, String>.from(call.arguments as Map<dynamic, dynamic>));
return Future<void>.sync(() {});
case '-[InAppPurchasePlugin restoreTransactions:result:]':
applicationNameHasTransactionRestored = call.arguments as String;
return Future<void>.sync(() {});
case '-[InAppPurchasePlugin presentCodeRedemptionSheet:result:]':
presentCodeRedemption = true;
return Future<void>.sync(() {});
case '-[SKPaymentQueue startObservingTransactionQueue]':
queueIsActive = true;
return Future<void>.sync(() {});
case '-[SKPaymentQueue stopObservingTransactionQueue]':
queueIsActive = false;
return Future<void>.sync(() {});
case '-[SKPaymentQueue registerDelegate]':
isPaymentQueueDelegateRegistered = true;
return Future<void>.sync(() {});
case '-[SKPaymentQueue removeDelegate]':
isPaymentQueueDelegateRegistered = false;
return Future<void>.sync(() {});
case '-[SKPaymentQueue showPriceConsentIfNeeded]':
showPriceConsentIfNeeded = true;
return Future<void>.sync(() {});
}
return Future<dynamic>.error('method not mocked');
}
}
class TestPaymentQueueDelegate extends SKPaymentQueueDelegateWrapper {}
class TestPaymentTransactionObserver extends SKTransactionObserverWrapper {
@override
void updatedTransactions(
{required List<SKPaymentTransactionWrapper> transactions}) {}
@override
void removedTransactions(
{required List<SKPaymentTransactionWrapper> transactions}) {}
@override
void restoreCompletedTransactionsFailed({required SKError error}) {}
@override
void paymentQueueRestoreCompletedTransactionsFinished() {}
@override
bool shouldAddStorePayment(
{required SKPaymentWrapper payment, required SKProductWrapper product}) {
return true;
}
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart",
"repo_id": "plugins",
"token_count": 4092
} | 1,167 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
#import "UIImage+ios_platform_images.h"
@implementation UIImage (ios_platform_images)
+ (UIImage *)flutterImageWithName:(NSString *)name {
NSString *filename = [name lastPathComponent];
NSString *path = [name stringByDeletingLastPathComponent];
for (int screenScale = [UIScreen mainScreen].scale; screenScale > 1; --screenScale) {
NSString *key = [FlutterDartProject
lookupKeyForAsset:[NSString stringWithFormat:@"%@/%d.0x/%@", path, screenScale, filename]];
UIImage *image = [UIImage imageNamed:key
inBundle:[NSBundle mainBundle]
compatibleWithTraitCollection:nil];
if (image) {
return image;
}
}
NSString *key = [FlutterDartProject lookupKeyForAsset:name];
return [UIImage imageNamed:key inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
}
@end
| plugins/packages/ios_platform_images/ios/Classes/UIImage+ios_platform_images.m/0 | {
"file_path": "plugins/packages/ios_platform_images/ios/Classes/UIImage+ios_platform_images.m",
"repo_id": "plugins",
"token_count": 374
} | 1,168 |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,19m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0"/>
<path
android:fillColor="#FFFFFFFF"
android:pathData="M10,3h4v12h-4z"/>
</vector>
| plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/ic_priority_high_white_24dp.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/ic_priority_high_white_24dp.xml",
"repo_id": "plugins",
"token_count": 210
} | 1,169 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 1.0.12
* Adds compatibility with `intl` 0.18.0.
## 1.0.11
* Fixes issue where failed authentication was failing silently
## 1.0.10
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 1.0.9
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 1.0.8
* Updates `local_auth_platform_interface` constraint to the correct minimum
version.
## 1.0.7
* Updates references to the obsolete master branch.
## 1.0.6
* Suppresses warnings for pre-iOS-11 codepaths.
## 1.0.5
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 1.0.4
* Fixes `deviceSupportsBiometrics` to return true when biometric hardware
is available but not enrolled.
## 1.0.3
* Adopts `Object.hash`.
## 1.0.2
* Adds support `localizedFallbackTitle` in authenticateWithBiometrics on iOS.
## 1.0.1
* BREAKING CHANGE: Changes `stopAuthentication` to always return false instead of throwing an error.
## 1.0.0
* Initial release from migration to federated architecture.
| plugins/packages/local_auth/local_auth_ios/CHANGELOG.md/0 | {
"file_path": "plugins/packages/local_auth/local_auth_ios/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 387
} | 1,170 |
name: path_provider_linux
description: Linux implementation of the path_provider plugin
repository: https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider_linux
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22
version: 2.1.8
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: path_provider
platforms:
linux:
dartPluginClass: PathProviderLinux
dependencies:
ffi: ">=1.1.2 <3.0.0"
flutter:
sdk: flutter
path: ^1.8.0
path_provider_platform_interface: ^2.0.0
xdg_directories: ">=0.2.0 <2.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/path_provider/path_provider_linux/pubspec.yaml/0 | {
"file_path": "plugins/packages/path_provider/path_provider_linux/pubspec.yaml",
"repo_id": "plugins",
"token_count": 312
} | 1,171 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 1.0.2
* Migrates remaining components to Swift and removes all Objective-C settings.
* Migrates `RunnerUITests` to Swift.
## 1.0.1
* Removes custom modulemap file with "Test" submodule and private headers for Swift migration.
* Migrates `FLTQuickActionsPlugin` class to Swift.
## 1.0.0
* Updates version to 1.0 to reflect current status.
* Updates minimum Flutter version to 2.10.
## 0.6.0+14
* Refactors `FLTQuickActionsPlugin` class into multiple components.
* Increases unit tests coverage to 100%.
## 0.6.0+13
* Adds some unit tests for `FLTQuickActionsPlugin` class.
## 0.6.0+12
* Adds a custom module map with a Test submodule for unit tests on iOS platform.
## 0.6.0+11
* Updates references to the obsolete master branch.
## 0.6.0+10
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.6.0+9
* Switches to a package-internal implementation of the platform interface.
| plugins/packages/quick_actions/quick_actions_ios/CHANGELOG.md/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 331
} | 1,172 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Flutter
public final class QuickActionsPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(
name: "plugins.flutter.io/quick_actions_ios",
binaryMessenger: registrar.messenger())
let instance = QuickActionsPlugin(channel: channel)
registrar.addMethodCallDelegate(instance, channel: channel)
registrar.addApplicationDelegate(instance)
}
private let channel: MethodChannel
private let shortcutItemProvider: ShortcutItemProviding
private let shortcutItemParser: ShortcutItemParser
/// The type of the shortcut item selected when launching the app.
private var launchingShortcutType: String? = nil
init(
channel: MethodChannel,
shortcutItemProvider: ShortcutItemProviding = UIApplication.shared,
shortcutItemParser: ShortcutItemParser = DefaultShortcutItemParser()
) {
self.channel = channel
self.shortcutItemProvider = shortcutItemProvider
self.shortcutItemParser = shortcutItemParser
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "setShortcutItems":
// `arguments` must be an array of dictionaries
let items = call.arguments as! [[String: Any]]
shortcutItemProvider.shortcutItems = shortcutItemParser.parseShortcutItems(items)
result(nil)
case "clearShortcutItems":
shortcutItemProvider.shortcutItems = []
result(nil)
case "getLaunchAction":
result(nil)
case _:
result(FlutterMethodNotImplemented)
}
}
public func application(
_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem,
completionHandler: @escaping (Bool) -> Void
) -> Bool {
handleShortcut(shortcutItem.type)
return true
}
public func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [AnyHashable: Any] = [:]
) -> Bool {
if let shortcutItem = launchOptions[UIApplication.LaunchOptionsKey.shortcutItem]
as? UIApplicationShortcutItem
{
// Keep hold of the shortcut type and handle it in the
// `applicationDidBecomeActive:` method once the Dart MethodChannel
// is initialized.
launchingShortcutType = shortcutItem.type
// Return false to indicate we handled the quick action to ensure
// the `application:performActionFor:` method is not called (as
// per Apple's documentation:
// https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622935-application).
return false
}
return true
}
public func applicationDidBecomeActive(_ application: UIApplication) {
if let shortcutType = launchingShortcutType {
handleShortcut(shortcutType)
launchingShortcutType = nil
}
}
private func handleShortcut(_ shortcut: String) {
channel.invokeMethod("launch", arguments: shortcut)
}
}
| plugins/packages/quick_actions/quick_actions_ios/ios/Classes/QuickActionsPlugin.swift/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/ios/Classes/QuickActionsPlugin.swift",
"repo_id": "plugins",
"token_count": 991
} | 1,173 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.sharedpreferences">
</manifest>
| plugins/packages/shared_preferences/shared_preferences_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/android/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 47
} | 1,174 |
name: shared_preferences_android
description: Android implementation of the shared_preferences plugin
repository: https://github.com/flutter/plugins/tree/main/packages/shared_preferences/shared_preferences_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
version: 2.0.15
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: shared_preferences
platforms:
android:
package: io.flutter.plugins.sharedpreferences
pluginClass: SharedPreferencesPlugin
dartPluginClass: SharedPreferencesAndroid
dependencies:
flutter:
sdk: flutter
shared_preferences_platform_interface: ^2.0.0
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/shared_preferences/shared_preferences_android/pubspec.yaml/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/pubspec.yaml",
"repo_id": "plugins",
"token_count": 302
} | 1,175 |
name: shared_preferences_windows
description: Windows implementation of shared_preferences
repository: https://github.com/flutter/plugins/tree/main/packages/shared_preferences/shared_preferences_windows
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
version: 2.1.3
environment:
sdk: '>=2.12.0 <3.0.0'
flutter: ">=3.0.0"
flutter:
plugin:
implements: shared_preferences
platforms:
windows:
dartPluginClass: SharedPreferencesWindows
dependencies:
file: ^6.0.0
flutter:
sdk: flutter
path: ^1.8.0
path_provider_platform_interface: ^2.0.0
path_provider_windows: ^2.0.0
shared_preferences_platform_interface: ^2.0.0
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/shared_preferences/shared_preferences_windows/pubspec.yaml/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_windows/pubspec.yaml",
"repo_id": "plugins",
"token_count": 316
} | 1,176 |
name: url_launcher_linux
description: Linux implementation of the url_launcher plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_linux
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 3.0.2
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: url_launcher
platforms:
linux:
pluginClass: UrlLauncherPlugin
dartPluginClass: UrlLauncherLinux
dependencies:
flutter:
sdk: flutter
url_launcher_platform_interface: ^2.0.3
dev_dependencies:
flutter_test:
sdk: flutter
test: ^1.16.3
| plugins/packages/url_launcher/url_launcher_linux/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_linux/pubspec.yaml",
"repo_id": "plugins",
"token_count": 287
} | 1,177 |
// Mocks generated by Mockito 5.3.2 from annotations
// in regular_integration_tests/integration_test/url_launcher_web_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'dart:html' as _i2;
import 'dart:math' as _i4;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeDocument_0 extends _i1.SmartFake implements _i2.Document {
_FakeDocument_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeLocation_1 extends _i1.SmartFake implements _i2.Location {
_FakeLocation_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeConsole_2 extends _i1.SmartFake implements _i2.Console {
_FakeConsole_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeHistory_3 extends _i1.SmartFake implements _i2.History {
_FakeHistory_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeStorage_4 extends _i1.SmartFake implements _i2.Storage {
_FakeStorage_4(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeNavigator_5 extends _i1.SmartFake implements _i2.Navigator {
_FakeNavigator_5(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePerformance_6 extends _i1.SmartFake implements _i2.Performance {
_FakePerformance_6(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeEvents_7 extends _i1.SmartFake implements _i2.Events {
_FakeEvents_7(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWindowBase_8 extends _i1.SmartFake implements _i2.WindowBase {
_FakeWindowBase_8(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeFileSystem_9 extends _i1.SmartFake implements _i2.FileSystem {
_FakeFileSystem_9(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeStylePropertyMapReadonly_10 extends _i1.SmartFake
implements _i2.StylePropertyMapReadonly {
_FakeStylePropertyMapReadonly_10(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeMediaQueryList_11 extends _i1.SmartFake
implements _i2.MediaQueryList {
_FakeMediaQueryList_11(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeEntry_12 extends _i1.SmartFake implements _i2.Entry {
_FakeEntry_12(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeGeolocation_13 extends _i1.SmartFake implements _i2.Geolocation {
_FakeGeolocation_13(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeMediaStream_14 extends _i1.SmartFake implements _i2.MediaStream {
_FakeMediaStream_14(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeRelatedApplication_15 extends _i1.SmartFake
implements _i2.RelatedApplication {
_FakeRelatedApplication_15(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [Window].
///
/// See the documentation for Mockito's code generation for more information.
class MockWindow extends _i1.Mock implements _i2.Window {
MockWindow() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<num> get animationFrame => (super.noSuchMethod(
Invocation.getter(#animationFrame),
returnValue: _i3.Future<num>.value(0),
) as _i3.Future<num>);
@override
_i2.Document get document => (super.noSuchMethod(
Invocation.getter(#document),
returnValue: _FakeDocument_0(
this,
Invocation.getter(#document),
),
) as _i2.Document);
@override
_i2.Location get location => (super.noSuchMethod(
Invocation.getter(#location),
returnValue: _FakeLocation_1(
this,
Invocation.getter(#location),
),
) as _i2.Location);
@override
set location(_i2.LocationBase? value) => super.noSuchMethod(
Invocation.setter(
#location,
value,
),
returnValueForMissingStub: null,
);
@override
_i2.Console get console => (super.noSuchMethod(
Invocation.getter(#console),
returnValue: _FakeConsole_2(
this,
Invocation.getter(#console),
),
) as _i2.Console);
@override
set defaultStatus(String? value) => super.noSuchMethod(
Invocation.setter(
#defaultStatus,
value,
),
returnValueForMissingStub: null,
);
@override
set defaultstatus(String? value) => super.noSuchMethod(
Invocation.setter(
#defaultstatus,
value,
),
returnValueForMissingStub: null,
);
@override
num get devicePixelRatio => (super.noSuchMethod(
Invocation.getter(#devicePixelRatio),
returnValue: 0,
) as num);
@override
_i2.History get history => (super.noSuchMethod(
Invocation.getter(#history),
returnValue: _FakeHistory_3(
this,
Invocation.getter(#history),
),
) as _i2.History);
@override
_i2.Storage get localStorage => (super.noSuchMethod(
Invocation.getter(#localStorage),
returnValue: _FakeStorage_4(
this,
Invocation.getter(#localStorage),
),
) as _i2.Storage);
@override
set name(String? value) => super.noSuchMethod(
Invocation.setter(
#name,
value,
),
returnValueForMissingStub: null,
);
@override
_i2.Navigator get navigator => (super.noSuchMethod(
Invocation.getter(#navigator),
returnValue: _FakeNavigator_5(
this,
Invocation.getter(#navigator),
),
) as _i2.Navigator);
@override
set opener(_i2.WindowBase? value) => super.noSuchMethod(
Invocation.setter(
#opener,
value,
),
returnValueForMissingStub: null,
);
@override
int get outerHeight => (super.noSuchMethod(
Invocation.getter(#outerHeight),
returnValue: 0,
) as int);
@override
int get outerWidth => (super.noSuchMethod(
Invocation.getter(#outerWidth),
returnValue: 0,
) as int);
@override
_i2.Performance get performance => (super.noSuchMethod(
Invocation.getter(#performance),
returnValue: _FakePerformance_6(
this,
Invocation.getter(#performance),
),
) as _i2.Performance);
@override
_i2.Storage get sessionStorage => (super.noSuchMethod(
Invocation.getter(#sessionStorage),
returnValue: _FakeStorage_4(
this,
Invocation.getter(#sessionStorage),
),
) as _i2.Storage);
@override
set status(String? value) => super.noSuchMethod(
Invocation.setter(
#status,
value,
),
returnValueForMissingStub: null,
);
@override
_i3.Stream<_i2.Event> get onContentLoaded => (super.noSuchMethod(
Invocation.getter(#onContentLoaded),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onAbort => (super.noSuchMethod(
Invocation.getter(#onAbort),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onBlur => (super.noSuchMethod(
Invocation.getter(#onBlur),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onCanPlay => (super.noSuchMethod(
Invocation.getter(#onCanPlay),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onCanPlayThrough => (super.noSuchMethod(
Invocation.getter(#onCanPlayThrough),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onChange => (super.noSuchMethod(
Invocation.getter(#onChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.MouseEvent> get onClick => (super.noSuchMethod(
Invocation.getter(#onClick),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onContextMenu => (super.noSuchMethod(
Invocation.getter(#onContextMenu),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.Event> get onDoubleClick => (super.noSuchMethod(
Invocation.getter(#onDoubleClick),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.DeviceMotionEvent> get onDeviceMotion => (super.noSuchMethod(
Invocation.getter(#onDeviceMotion),
returnValue: _i3.Stream<_i2.DeviceMotionEvent>.empty(),
) as _i3.Stream<_i2.DeviceMotionEvent>);
@override
_i3.Stream<_i2.DeviceOrientationEvent> get onDeviceOrientation =>
(super.noSuchMethod(
Invocation.getter(#onDeviceOrientation),
returnValue: _i3.Stream<_i2.DeviceOrientationEvent>.empty(),
) as _i3.Stream<_i2.DeviceOrientationEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDrag => (super.noSuchMethod(
Invocation.getter(#onDrag),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragEnd => (super.noSuchMethod(
Invocation.getter(#onDragEnd),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragEnter => (super.noSuchMethod(
Invocation.getter(#onDragEnter),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragLeave => (super.noSuchMethod(
Invocation.getter(#onDragLeave),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragOver => (super.noSuchMethod(
Invocation.getter(#onDragOver),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragStart => (super.noSuchMethod(
Invocation.getter(#onDragStart),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDrop => (super.noSuchMethod(
Invocation.getter(#onDrop),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.Event> get onDurationChange => (super.noSuchMethod(
Invocation.getter(#onDurationChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onEmptied => (super.noSuchMethod(
Invocation.getter(#onEmptied),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onEnded => (super.noSuchMethod(
Invocation.getter(#onEnded),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onError => (super.noSuchMethod(
Invocation.getter(#onError),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onFocus => (super.noSuchMethod(
Invocation.getter(#onFocus),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onHashChange => (super.noSuchMethod(
Invocation.getter(#onHashChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onInput => (super.noSuchMethod(
Invocation.getter(#onInput),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onInvalid => (super.noSuchMethod(
Invocation.getter(#onInvalid),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.KeyboardEvent> get onKeyDown => (super.noSuchMethod(
Invocation.getter(#onKeyDown),
returnValue: _i3.Stream<_i2.KeyboardEvent>.empty(),
) as _i3.Stream<_i2.KeyboardEvent>);
@override
_i3.Stream<_i2.KeyboardEvent> get onKeyPress => (super.noSuchMethod(
Invocation.getter(#onKeyPress),
returnValue: _i3.Stream<_i2.KeyboardEvent>.empty(),
) as _i3.Stream<_i2.KeyboardEvent>);
@override
_i3.Stream<_i2.KeyboardEvent> get onKeyUp => (super.noSuchMethod(
Invocation.getter(#onKeyUp),
returnValue: _i3.Stream<_i2.KeyboardEvent>.empty(),
) as _i3.Stream<_i2.KeyboardEvent>);
@override
_i3.Stream<_i2.Event> get onLoad => (super.noSuchMethod(
Invocation.getter(#onLoad),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onLoadedData => (super.noSuchMethod(
Invocation.getter(#onLoadedData),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onLoadedMetadata => (super.noSuchMethod(
Invocation.getter(#onLoadedMetadata),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onLoadStart => (super.noSuchMethod(
Invocation.getter(#onLoadStart),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.MessageEvent> get onMessage => (super.noSuchMethod(
Invocation.getter(#onMessage),
returnValue: _i3.Stream<_i2.MessageEvent>.empty(),
) as _i3.Stream<_i2.MessageEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseDown => (super.noSuchMethod(
Invocation.getter(#onMouseDown),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseEnter => (super.noSuchMethod(
Invocation.getter(#onMouseEnter),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseLeave => (super.noSuchMethod(
Invocation.getter(#onMouseLeave),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseMove => (super.noSuchMethod(
Invocation.getter(#onMouseMove),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseOut => (super.noSuchMethod(
Invocation.getter(#onMouseOut),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseOver => (super.noSuchMethod(
Invocation.getter(#onMouseOver),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseUp => (super.noSuchMethod(
Invocation.getter(#onMouseUp),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.WheelEvent> get onMouseWheel => (super.noSuchMethod(
Invocation.getter(#onMouseWheel),
returnValue: _i3.Stream<_i2.WheelEvent>.empty(),
) as _i3.Stream<_i2.WheelEvent>);
@override
_i3.Stream<_i2.Event> get onOffline => (super.noSuchMethod(
Invocation.getter(#onOffline),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onOnline => (super.noSuchMethod(
Invocation.getter(#onOnline),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPageHide => (super.noSuchMethod(
Invocation.getter(#onPageHide),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPageShow => (super.noSuchMethod(
Invocation.getter(#onPageShow),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPause => (super.noSuchMethod(
Invocation.getter(#onPause),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPlay => (super.noSuchMethod(
Invocation.getter(#onPlay),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPlaying => (super.noSuchMethod(
Invocation.getter(#onPlaying),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.PopStateEvent> get onPopState => (super.noSuchMethod(
Invocation.getter(#onPopState),
returnValue: _i3.Stream<_i2.PopStateEvent>.empty(),
) as _i3.Stream<_i2.PopStateEvent>);
@override
_i3.Stream<_i2.Event> get onProgress => (super.noSuchMethod(
Invocation.getter(#onProgress),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onRateChange => (super.noSuchMethod(
Invocation.getter(#onRateChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onReset => (super.noSuchMethod(
Invocation.getter(#onReset),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onResize => (super.noSuchMethod(
Invocation.getter(#onResize),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onScroll => (super.noSuchMethod(
Invocation.getter(#onScroll),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSearch => (super.noSuchMethod(
Invocation.getter(#onSearch),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSeeked => (super.noSuchMethod(
Invocation.getter(#onSeeked),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSeeking => (super.noSuchMethod(
Invocation.getter(#onSeeking),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSelect => (super.noSuchMethod(
Invocation.getter(#onSelect),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onStalled => (super.noSuchMethod(
Invocation.getter(#onStalled),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.StorageEvent> get onStorage => (super.noSuchMethod(
Invocation.getter(#onStorage),
returnValue: _i3.Stream<_i2.StorageEvent>.empty(),
) as _i3.Stream<_i2.StorageEvent>);
@override
_i3.Stream<_i2.Event> get onSubmit => (super.noSuchMethod(
Invocation.getter(#onSubmit),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSuspend => (super.noSuchMethod(
Invocation.getter(#onSuspend),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onTimeUpdate => (super.noSuchMethod(
Invocation.getter(#onTimeUpdate),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchCancel => (super.noSuchMethod(
Invocation.getter(#onTouchCancel),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchEnd => (super.noSuchMethod(
Invocation.getter(#onTouchEnd),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchMove => (super.noSuchMethod(
Invocation.getter(#onTouchMove),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchStart => (super.noSuchMethod(
Invocation.getter(#onTouchStart),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TransitionEvent> get onTransitionEnd => (super.noSuchMethod(
Invocation.getter(#onTransitionEnd),
returnValue: _i3.Stream<_i2.TransitionEvent>.empty(),
) as _i3.Stream<_i2.TransitionEvent>);
@override
_i3.Stream<_i2.Event> get onUnload => (super.noSuchMethod(
Invocation.getter(#onUnload),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onVolumeChange => (super.noSuchMethod(
Invocation.getter(#onVolumeChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onWaiting => (super.noSuchMethod(
Invocation.getter(#onWaiting),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.AnimationEvent> get onAnimationEnd => (super.noSuchMethod(
Invocation.getter(#onAnimationEnd),
returnValue: _i3.Stream<_i2.AnimationEvent>.empty(),
) as _i3.Stream<_i2.AnimationEvent>);
@override
_i3.Stream<_i2.AnimationEvent> get onAnimationIteration =>
(super.noSuchMethod(
Invocation.getter(#onAnimationIteration),
returnValue: _i3.Stream<_i2.AnimationEvent>.empty(),
) as _i3.Stream<_i2.AnimationEvent>);
@override
_i3.Stream<_i2.AnimationEvent> get onAnimationStart => (super.noSuchMethod(
Invocation.getter(#onAnimationStart),
returnValue: _i3.Stream<_i2.AnimationEvent>.empty(),
) as _i3.Stream<_i2.AnimationEvent>);
@override
_i3.Stream<_i2.Event> get onBeforeUnload => (super.noSuchMethod(
Invocation.getter(#onBeforeUnload),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.WheelEvent> get onWheel => (super.noSuchMethod(
Invocation.getter(#onWheel),
returnValue: _i3.Stream<_i2.WheelEvent>.empty(),
) as _i3.Stream<_i2.WheelEvent>);
@override
int get pageXOffset => (super.noSuchMethod(
Invocation.getter(#pageXOffset),
returnValue: 0,
) as int);
@override
int get pageYOffset => (super.noSuchMethod(
Invocation.getter(#pageYOffset),
returnValue: 0,
) as int);
@override
int get scrollX => (super.noSuchMethod(
Invocation.getter(#scrollX),
returnValue: 0,
) as int);
@override
int get scrollY => (super.noSuchMethod(
Invocation.getter(#scrollY),
returnValue: 0,
) as int);
@override
_i2.Events get on => (super.noSuchMethod(
Invocation.getter(#on),
returnValue: _FakeEvents_7(
this,
Invocation.getter(#on),
),
) as _i2.Events);
@override
_i2.WindowBase open(
String? url,
String? name, [
String? options,
]) =>
(super.noSuchMethod(
Invocation.method(
#open,
[
url,
name,
options,
],
),
returnValue: _FakeWindowBase_8(
this,
Invocation.method(
#open,
[
url,
name,
options,
],
),
),
) as _i2.WindowBase);
@override
int requestAnimationFrame(_i2.FrameRequestCallback? callback) =>
(super.noSuchMethod(
Invocation.method(
#requestAnimationFrame,
[callback],
),
returnValue: 0,
) as int);
@override
void cancelAnimationFrame(int? id) => super.noSuchMethod(
Invocation.method(
#cancelAnimationFrame,
[id],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<_i2.FileSystem> requestFileSystem(
int? size, {
bool? persistent = false,
}) =>
(super.noSuchMethod(
Invocation.method(
#requestFileSystem,
[size],
{#persistent: persistent},
),
returnValue: _i3.Future<_i2.FileSystem>.value(_FakeFileSystem_9(
this,
Invocation.method(
#requestFileSystem,
[size],
{#persistent: persistent},
),
)),
) as _i3.Future<_i2.FileSystem>);
@override
void alert([String? message]) => super.noSuchMethod(
Invocation.method(
#alert,
[message],
),
returnValueForMissingStub: null,
);
@override
void cancelIdleCallback(int? handle) => super.noSuchMethod(
Invocation.method(
#cancelIdleCallback,
[handle],
),
returnValueForMissingStub: null,
);
@override
void close() => super.noSuchMethod(
Invocation.method(
#close,
[],
),
returnValueForMissingStub: null,
);
@override
bool confirm([String? message]) => (super.noSuchMethod(
Invocation.method(
#confirm,
[message],
),
returnValue: false,
) as bool);
@override
_i3.Future<dynamic> fetch(
dynamic input, [
Map<dynamic, dynamic>? init,
]) =>
(super.noSuchMethod(
Invocation.method(
#fetch,
[
input,
init,
],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
bool find(
String? string,
bool? caseSensitive,
bool? backwards,
bool? wrap,
bool? wholeWord,
bool? searchInFrames,
bool? showDialog,
) =>
(super.noSuchMethod(
Invocation.method(
#find,
[
string,
caseSensitive,
backwards,
wrap,
wholeWord,
searchInFrames,
showDialog,
],
),
returnValue: false,
) as bool);
@override
_i2.StylePropertyMapReadonly getComputedStyleMap(
_i2.Element? element,
String? pseudoElement,
) =>
(super.noSuchMethod(
Invocation.method(
#getComputedStyleMap,
[
element,
pseudoElement,
],
),
returnValue: _FakeStylePropertyMapReadonly_10(
this,
Invocation.method(
#getComputedStyleMap,
[
element,
pseudoElement,
],
),
),
) as _i2.StylePropertyMapReadonly);
@override
List<_i2.CssRule> getMatchedCssRules(
_i2.Element? element,
String? pseudoElement,
) =>
(super.noSuchMethod(
Invocation.method(
#getMatchedCssRules,
[
element,
pseudoElement,
],
),
returnValue: <_i2.CssRule>[],
) as List<_i2.CssRule>);
@override
_i2.MediaQueryList matchMedia(String? query) => (super.noSuchMethod(
Invocation.method(
#matchMedia,
[query],
),
returnValue: _FakeMediaQueryList_11(
this,
Invocation.method(
#matchMedia,
[query],
),
),
) as _i2.MediaQueryList);
@override
void moveBy(
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#moveBy,
[
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void postMessage(
dynamic message,
String? targetOrigin, [
List<Object>? transfer,
]) =>
super.noSuchMethod(
Invocation.method(
#postMessage,
[
message,
targetOrigin,
transfer,
],
),
returnValueForMissingStub: null,
);
@override
void print() => super.noSuchMethod(
Invocation.method(
#print,
[],
),
returnValueForMissingStub: null,
);
@override
int requestIdleCallback(
_i2.IdleRequestCallback? callback, [
Map<dynamic, dynamic>? options,
]) =>
(super.noSuchMethod(
Invocation.method(
#requestIdleCallback,
[
callback,
options,
],
),
returnValue: 0,
) as int);
@override
void resizeBy(
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#resizeBy,
[
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void resizeTo(
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#resizeTo,
[
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void scroll([
dynamic options_OR_x,
dynamic y,
Map<dynamic, dynamic>? scrollOptions,
]) =>
super.noSuchMethod(
Invocation.method(
#scroll,
[
options_OR_x,
y,
scrollOptions,
],
),
returnValueForMissingStub: null,
);
@override
void scrollBy([
dynamic options_OR_x,
dynamic y,
Map<dynamic, dynamic>? scrollOptions,
]) =>
super.noSuchMethod(
Invocation.method(
#scrollBy,
[
options_OR_x,
y,
scrollOptions,
],
),
returnValueForMissingStub: null,
);
@override
void scrollTo([
dynamic options_OR_x,
dynamic y,
Map<dynamic, dynamic>? scrollOptions,
]) =>
super.noSuchMethod(
Invocation.method(
#scrollTo,
[
options_OR_x,
y,
scrollOptions,
],
),
returnValueForMissingStub: null,
);
@override
void stop() => super.noSuchMethod(
Invocation.method(
#stop,
[],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<_i2.Entry> resolveLocalFileSystemUrl(String? url) =>
(super.noSuchMethod(
Invocation.method(
#resolveLocalFileSystemUrl,
[url],
),
returnValue: _i3.Future<_i2.Entry>.value(_FakeEntry_12(
this,
Invocation.method(
#resolveLocalFileSystemUrl,
[url],
),
)),
) as _i3.Future<_i2.Entry>);
@override
String atob(String? atob) => (super.noSuchMethod(
Invocation.method(
#atob,
[atob],
),
returnValue: '',
) as String);
@override
String btoa(String? btoa) => (super.noSuchMethod(
Invocation.method(
#btoa,
[btoa],
),
returnValue: '',
) as String);
@override
void moveTo(_i4.Point<num>? p) => super.noSuchMethod(
Invocation.method(
#moveTo,
[p],
),
returnValueForMissingStub: null,
);
@override
void addEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#addEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
void removeEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#removeEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(
Invocation.method(
#dispatchEvent,
[event],
),
returnValue: false,
) as bool);
}
/// A class which mocks [Navigator].
///
/// See the documentation for Mockito's code generation for more information.
class MockNavigator extends _i1.Mock implements _i2.Navigator {
MockNavigator() {
_i1.throwOnMissingStub(this);
}
@override
String get language => (super.noSuchMethod(
Invocation.getter(#language),
returnValue: '',
) as String);
@override
_i2.Geolocation get geolocation => (super.noSuchMethod(
Invocation.getter(#geolocation),
returnValue: _FakeGeolocation_13(
this,
Invocation.getter(#geolocation),
),
) as _i2.Geolocation);
@override
String get vendor => (super.noSuchMethod(
Invocation.getter(#vendor),
returnValue: '',
) as String);
@override
String get vendorSub => (super.noSuchMethod(
Invocation.getter(#vendorSub),
returnValue: '',
) as String);
@override
String get appCodeName => (super.noSuchMethod(
Invocation.getter(#appCodeName),
returnValue: '',
) as String);
@override
String get appName => (super.noSuchMethod(
Invocation.getter(#appName),
returnValue: '',
) as String);
@override
String get appVersion => (super.noSuchMethod(
Invocation.getter(#appVersion),
returnValue: '',
) as String);
@override
String get product => (super.noSuchMethod(
Invocation.getter(#product),
returnValue: '',
) as String);
@override
String get userAgent => (super.noSuchMethod(
Invocation.getter(#userAgent),
returnValue: '',
) as String);
@override
List<_i2.Gamepad?> getGamepads() => (super.noSuchMethod(
Invocation.method(
#getGamepads,
[],
),
returnValue: <_i2.Gamepad?>[],
) as List<_i2.Gamepad?>);
@override
_i3.Future<_i2.MediaStream> getUserMedia({
dynamic audio = false,
dynamic video = false,
}) =>
(super.noSuchMethod(
Invocation.method(
#getUserMedia,
[],
{
#audio: audio,
#video: video,
},
),
returnValue: _i3.Future<_i2.MediaStream>.value(_FakeMediaStream_14(
this,
Invocation.method(
#getUserMedia,
[],
{
#audio: audio,
#video: video,
},
),
)),
) as _i3.Future<_i2.MediaStream>);
@override
void cancelKeyboardLock() => super.noSuchMethod(
Invocation.method(
#cancelKeyboardLock,
[],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<dynamic> getBattery() => (super.noSuchMethod(
Invocation.method(
#getBattery,
[],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
_i3.Future<_i2.RelatedApplication> getInstalledRelatedApps() =>
(super.noSuchMethod(
Invocation.method(
#getInstalledRelatedApps,
[],
),
returnValue:
_i3.Future<_i2.RelatedApplication>.value(_FakeRelatedApplication_15(
this,
Invocation.method(
#getInstalledRelatedApps,
[],
),
)),
) as _i3.Future<_i2.RelatedApplication>);
@override
_i3.Future<dynamic> getVRDisplays() => (super.noSuchMethod(
Invocation.method(
#getVRDisplays,
[],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
void registerProtocolHandler(
String? scheme,
String? url,
String? title,
) =>
super.noSuchMethod(
Invocation.method(
#registerProtocolHandler,
[
scheme,
url,
title,
],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<dynamic> requestKeyboardLock([List<String>? keyCodes]) =>
(super.noSuchMethod(
Invocation.method(
#requestKeyboardLock,
[keyCodes],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
_i3.Future<dynamic> requestMidiAccess([Map<dynamic, dynamic>? options]) =>
(super.noSuchMethod(
Invocation.method(
#requestMidiAccess,
[options],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
_i3.Future<dynamic> requestMediaKeySystemAccess(
String? keySystem,
List<Map<dynamic, dynamic>>? supportedConfigurations,
) =>
(super.noSuchMethod(
Invocation.method(
#requestMediaKeySystemAccess,
[
keySystem,
supportedConfigurations,
],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
bool sendBeacon(
String? url,
Object? data,
) =>
(super.noSuchMethod(
Invocation.method(
#sendBeacon,
[
url,
data,
],
),
returnValue: false,
) as bool);
@override
_i3.Future<dynamic> share([Map<dynamic, dynamic>? data]) =>
(super.noSuchMethod(
Invocation.method(
#share,
[data],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
}
| plugins/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.mocks.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.mocks.dart",
"repo_id": "plugins",
"token_count": 19002
} | 1,178 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@JS()
library integration_test_utils;
import 'dart:html';
import 'package:js/js.dart';
// Returns the URL to load an asset from this example app as a network source.
//
// TODO(stuartmorgan): Convert this to a local `HttpServer` that vends the
// assets directly, https://github.com/flutter/flutter/issues/95420
String getUrlForAssetAsNetworkSource(String assetKey) {
return 'https://github.com/flutter/plugins/blob/'
// This hash can be rolled forward to pick up newly-added assets.
'cb381ced070d356799dddf24aca38ce0579d3d7b'
'/packages/video_player/video_player/example/'
'$assetKey'
'?raw=true';
}
@JS()
@anonymous
class _Descriptor {
// May also contain "configurable" and "enumerable" bools.
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description
external factory _Descriptor({
// bool configurable,
// bool enumerable,
bool writable,
Object value,
});
}
@JS('Object.defineProperty')
external void _defineProperty(
Object object,
String property,
_Descriptor description,
);
/// Forces a VideoElement to report "Infinity" duration.
///
/// Uses JS Object.defineProperty to set the value of a readonly property.
void setInfinityDuration(VideoElement element) {
_defineProperty(
element,
'duration',
_Descriptor(
writable: true,
value: double.infinity,
));
}
| plugins/packages/video_player/video_player_web/example/integration_test/utils.dart/0 | {
"file_path": "plugins/packages/video_player/video_player_web/example/integration_test/utils.dart",
"repo_id": "plugins",
"token_count": 546
} | 1,179 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.content.Context;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
class FlutterWebViewFactory extends PlatformViewFactory {
private final InstanceManager instanceManager;
FlutterWebViewFactory(InstanceManager instanceManager) {
super(StandardMessageCodec.INSTANCE);
this.instanceManager = instanceManager;
}
@Override
public PlatformView create(Context context, int id, Object args) {
final PlatformView view = (PlatformView) instanceManager.getInstance((Integer) args);
if (view == null) {
throw new IllegalStateException("Unable to find WebView instance: " + args);
}
return view;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebViewFactory.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebViewFactory.java",
"repo_id": "plugins",
"token_count": 272
} | 1,180 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.CookieManagerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.DownloadListenerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.FlutterAssetManagerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.JavaObjectHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.JavaScriptChannelHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebChromeClientHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebSettingsHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebStorageHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebViewClientHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebViewHostApi;
/**
* Java platform implementation of the webview_flutter plugin.
*
* <p>Register this in an add to app scenario to gracefully handle activity and context changes.
*
* <p>Call {@link #registerWith} to use the stable {@code io.flutter.plugin.common} package instead.
*/
public class WebViewFlutterPlugin implements FlutterPlugin, ActivityAware {
@Nullable private InstanceManager instanceManager;
private FlutterPluginBinding pluginBinding;
private WebViewHostApiImpl webViewHostApi;
private JavaScriptChannelHostApiImpl javaScriptChannelHostApi;
/**
* Add an instance of this to {@link io.flutter.embedding.engine.plugins.PluginRegistry} to
* register it.
*
* <p>THIS PLUGIN CODE PATH DEPENDS ON A NEWER VERSION OF FLUTTER THAN THE ONE DEFINED IN THE
* PUBSPEC.YAML. Text input will fail on some Android devices unless this is used with at least
* flutter/flutter@1d4d63ace1f801a022ea9ec737bf8c15395588b9. Use the V1 embedding with {@link
* #registerWith} to use this plugin with older Flutter versions.
*
* <p>Registration should eventually be handled automatically by v2 of the
* GeneratedPluginRegistrant. https://github.com/flutter/flutter/issues/42694
*/
public WebViewFlutterPlugin() {}
/**
* Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common}
* package.
*
* <p>Calling this automatically initializes the plugin. However plugins initialized this way
* won't react to changes in activity or context, unlike {@link WebViewFlutterPlugin}.
*/
@SuppressWarnings({"unused", "deprecation"})
public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
new WebViewFlutterPlugin()
.setUp(
registrar.messenger(),
registrar.platformViewRegistry(),
registrar.activity(),
registrar.view(),
new FlutterAssetManager.RegistrarFlutterAssetManager(
registrar.context().getAssets(), registrar));
}
private void setUp(
BinaryMessenger binaryMessenger,
PlatformViewRegistry viewRegistry,
Context context,
View containerView,
FlutterAssetManager flutterAssetManager) {
instanceManager =
InstanceManager.open(
identifier ->
new GeneratedAndroidWebView.JavaObjectFlutterApi(binaryMessenger)
.dispose(identifier, reply -> {}));
viewRegistry.registerViewFactory(
"plugins.flutter.io/webview", new FlutterWebViewFactory(instanceManager));
webViewHostApi =
new WebViewHostApiImpl(
instanceManager,
binaryMessenger,
new WebViewHostApiImpl.WebViewProxy(),
context,
containerView);
javaScriptChannelHostApi =
new JavaScriptChannelHostApiImpl(
instanceManager,
new JavaScriptChannelHostApiImpl.JavaScriptChannelCreator(),
new JavaScriptChannelFlutterApiImpl(binaryMessenger, instanceManager),
new Handler(context.getMainLooper()));
JavaObjectHostApi.setup(binaryMessenger, new JavaObjectHostApiImpl(instanceManager));
WebViewHostApi.setup(binaryMessenger, webViewHostApi);
JavaScriptChannelHostApi.setup(binaryMessenger, javaScriptChannelHostApi);
WebViewClientHostApi.setup(
binaryMessenger,
new WebViewClientHostApiImpl(
instanceManager,
new WebViewClientHostApiImpl.WebViewClientCreator(),
new WebViewClientFlutterApiImpl(binaryMessenger, instanceManager)));
WebChromeClientHostApi.setup(
binaryMessenger,
new WebChromeClientHostApiImpl(
instanceManager,
new WebChromeClientHostApiImpl.WebChromeClientCreator(),
new WebChromeClientFlutterApiImpl(binaryMessenger, instanceManager)));
DownloadListenerHostApi.setup(
binaryMessenger,
new DownloadListenerHostApiImpl(
instanceManager,
new DownloadListenerHostApiImpl.DownloadListenerCreator(),
new DownloadListenerFlutterApiImpl(binaryMessenger, instanceManager)));
WebSettingsHostApi.setup(
binaryMessenger,
new WebSettingsHostApiImpl(
instanceManager, new WebSettingsHostApiImpl.WebSettingsCreator()));
FlutterAssetManagerHostApi.setup(
binaryMessenger, new FlutterAssetManagerHostApiImpl(flutterAssetManager));
CookieManagerHostApi.setup(binaryMessenger, new CookieManagerHostApiImpl());
WebStorageHostApi.setup(
binaryMessenger,
new WebStorageHostApiImpl(instanceManager, new WebStorageHostApiImpl.WebStorageCreator()));
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
pluginBinding = binding;
setUp(
binding.getBinaryMessenger(),
binding.getPlatformViewRegistry(),
binding.getApplicationContext(),
null,
new FlutterAssetManager.PluginBindingFlutterAssetManager(
binding.getApplicationContext().getAssets(), binding.getFlutterAssets()));
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
if (instanceManager != null) {
instanceManager.close();
instanceManager = null;
}
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
updateContext(activityPluginBinding.getActivity());
}
@Override
public void onDetachedFromActivityForConfigChanges() {
updateContext(pluginBinding.getApplicationContext());
}
@Override
public void onReattachedToActivityForConfigChanges(
@NonNull ActivityPluginBinding activityPluginBinding) {
updateContext(activityPluginBinding.getActivity());
}
@Override
public void onDetachedFromActivity() {
updateContext(pluginBinding.getApplicationContext());
}
private void updateContext(Context context) {
webViewHostApi.setContext(context);
javaScriptChannelHostApi.setPlatformThreadHandler(new Handler(context.getMainLooper()));
}
/** Maintains instances used to communicate with the corresponding objects in Dart. */
@Nullable
public InstanceManager getInstanceManager() {
return instanceManager;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterPlugin.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterPlugin.java",
"repo_id": "plugins",
"token_count": 2669
} | 1,181 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.net.Uri;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import io.flutter.plugins.webviewflutter.WebViewClientHostApiImpl.WebViewClientCompatImpl;
import io.flutter.plugins.webviewflutter.WebViewClientHostApiImpl.WebViewClientCreator;
import java.util.HashMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class WebViewClientTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public WebViewClientFlutterApiImpl mockFlutterApi;
@Mock public WebView mockWebView;
@Mock public WebViewClientCompatImpl mockWebViewClient;
InstanceManager instanceManager;
WebViewClientHostApiImpl hostApiImpl;
WebViewClientCompatImpl webViewClient;
@Before
public void setUp() {
instanceManager = InstanceManager.open(identifier -> {});
instanceManager.addDartCreatedInstance(mockWebView, 0L);
final WebViewClientCreator webViewClientCreator =
new WebViewClientCreator() {
@Override
public WebViewClient createWebViewClient(WebViewClientFlutterApiImpl flutterApi) {
webViewClient = (WebViewClientCompatImpl) super.createWebViewClient(flutterApi);
return webViewClient;
}
};
hostApiImpl =
new WebViewClientHostApiImpl(instanceManager, webViewClientCreator, mockFlutterApi);
hostApiImpl.create(1L);
}
@After
public void tearDown() {
instanceManager.close();
}
@Test
public void onPageStarted() {
webViewClient.onPageStarted(mockWebView, "https://www.google.com", null);
verify(mockFlutterApi)
.onPageStarted(eq(webViewClient), eq(mockWebView), eq("https://www.google.com"), any());
}
@Test
public void onReceivedError() {
webViewClient.onReceivedError(mockWebView, 32, "description", "https://www.google.com");
verify(mockFlutterApi)
.onReceivedError(
eq(webViewClient),
eq(mockWebView),
eq(32L),
eq("description"),
eq("https://www.google.com"),
any());
}
@Test
public void urlLoading() {
webViewClient.shouldOverrideUrlLoading(mockWebView, "https://www.google.com");
verify(mockFlutterApi)
.urlLoading(eq(webViewClient), eq(mockWebView), eq("https://www.google.com"), any());
}
@Test
public void convertWebResourceRequestWithNullHeaders() {
final Uri mockUri = mock(Uri.class);
when(mockUri.toString()).thenReturn("");
final WebResourceRequest mockRequest = mock(WebResourceRequest.class);
when(mockRequest.getMethod()).thenReturn("method");
when(mockRequest.getUrl()).thenReturn(mockUri);
when(mockRequest.isForMainFrame()).thenReturn(true);
when(mockRequest.getRequestHeaders()).thenReturn(null);
final GeneratedAndroidWebView.WebResourceRequestData data =
WebViewClientFlutterApiImpl.createWebResourceRequestData(mockRequest);
assertEquals(data.getRequestHeaders(), new HashMap<String, String>());
}
@Test
public void setReturnValueForShouldOverrideUrlLoading() {
final WebViewClientHostApiImpl webViewClientHostApi =
new WebViewClientHostApiImpl(
instanceManager,
new WebViewClientCreator() {
@Override
public WebViewClient createWebViewClient(WebViewClientFlutterApiImpl flutterApi) {
return mockWebViewClient;
}
},
mockFlutterApi);
instanceManager.addDartCreatedInstance(mockWebViewClient, 0);
webViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading(0L, false);
verify(mockWebViewClient).setReturnValueForShouldOverrideUrlLoading(false);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java",
"repo_id": "plugins",
"token_count": 1611
} | 1,182 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This test is run using `flutter drive` by the CI (see /script/tool/README.md
// in this repository for details on driving that tooling manually), but can
// also be run using `flutter test` directly during development.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:webview_flutter_android/src/android_webview.dart' as android;
import 'package:webview_flutter_android/src/android_webview_api_impls.dart';
import 'package:webview_flutter_android/src/instance_manager.dart';
import 'package:webview_flutter_android/src/weak_reference_utils.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
Future<void> main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0);
server.forEach((HttpRequest request) {
if (request.uri.path == '/hello.txt') {
request.response.writeln('Hello, world.');
} else if (request.uri.path == '/secondary.txt') {
request.response.writeln('How are you today?');
} else if (request.uri.path == '/headers') {
request.response.writeln('${request.headers}');
} else if (request.uri.path == '/favicon.ico') {
request.response.statusCode = HttpStatus.notFound;
} else {
fail('unexpected request: ${request.method} ${request.uri}');
}
request.response.close();
});
final String prefixUrl = 'http://${server.address.address}:${server.port}';
final String primaryUrl = '$prefixUrl/hello.txt';
final String secondaryUrl = '$prefixUrl/secondary.txt';
final String headersUrl = '$prefixUrl/headers';
testWidgets('loadRequest', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageFinished.complete()),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageFinished.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets(
'withWeakRefenceTo allows encapsulating class to be garbage collected',
(WidgetTester tester) async {
final Completer<int> gcCompleter = Completer<int>();
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: gcCompleter.complete,
);
ClassWithCallbackClass? instance = ClassWithCallbackClass();
instanceManager.addHostCreatedInstance(instance.callbackClass, 0);
instance = null;
// Force garbage collection.
await IntegrationTestWidgetsFlutterBinding.instance
.watchPerformance(() async {
await tester.pumpAndSettle();
});
final int gcIdentifier = await gcCompleter.future;
expect(gcIdentifier, 0);
}, timeout: const Timeout(Duration(seconds: 10)));
testWidgets(
'WebView is released by garbage collection',
(WidgetTester tester) async {
final Completer<void> webViewGCCompleter = Completer<void>();
late final InstanceManager instanceManager;
instanceManager =
InstanceManager(onWeakReferenceRemoved: (int identifier) {
final Copyable instance =
instanceManager.getInstanceWithWeakReference(identifier)!;
if (instance is android.WebView && !webViewGCCompleter.isCompleted) {
webViewGCCompleter.complete();
}
});
android.WebView.api = WebViewHostApiImpl(
instanceManager: instanceManager,
);
android.WebSettings.api = WebSettingsHostApiImpl(
instanceManager: instanceManager,
);
android.WebChromeClient.api = WebChromeClientHostApiImpl(
instanceManager: instanceManager,
);
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
AndroidWebViewWidgetCreationParams(
instanceManager: instanceManager,
controller: PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
),
),
).build(context);
},
),
);
await tester.pumpAndSettle();
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
AndroidWebViewWidgetCreationParams(
instanceManager: instanceManager,
controller: PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
),
),
).build(context);
},
),
);
await tester.pumpAndSettle();
// Force garbage collection.
await IntegrationTestWidgetsFlutterBinding.instance
.watchPerformance(() async {
await tester.pumpAndSettle();
});
await tester.pumpAndSettle();
await expectLater(webViewGCCompleter.future, completes);
android.WebView.api = WebViewHostApiImpl();
android.WebSettings.api = WebSettingsHostApiImpl();
android.WebChromeClient.api = WebChromeClientHostApiImpl();
},
timeout: const Timeout(Duration(seconds: 10)),
);
testWidgets('runJavaScriptReturningResult', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageFinished.complete()),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageFinished.future;
await expectLater(
controller.runJavaScriptReturningResult('1 + 1'),
completion(2),
);
});
testWidgets('loadRequest with headers', (WidgetTester tester) async {
final Map<String, String> headers = <String, String>{
'test_header': 'flutter_test_header'
};
final StreamController<String> pageLoads = StreamController<String>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((String url) => pageLoads.add(url)),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(headersUrl),
headers: headers,
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoads.stream.firstWhere((String url) => url == headersUrl);
final String content = await controller.runJavaScriptReturningResult(
'document.documentElement.innerText',
) as String;
expect(content.contains('flutter_test_header'), isTrue);
});
testWidgets('JavascriptChannel', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageFinished.complete()),
);
final Completer<String> channelCompleter = Completer<String>();
await controller.addJavaScriptChannel(
JavaScriptChannelParams(
name: 'Echo',
onMessageReceived: (JavaScriptMessage message) {
channelCompleter.complete(message.message);
},
),
);
await controller.loadHtmlString(
'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageFinished.future;
await controller.runJavaScript('Echo.postMessage("hello");');
await expectLater(channelCompleter.future, completion('hello'));
});
testWidgets('resize webview', (WidgetTester tester) async {
final Completer<void> initialResizeCompleter = Completer<void>();
final Completer<void> buttonTapResizeCompleter = Completer<void>();
final Completer<void> onPageFinished = Completer<void>();
bool resizeButtonTapped = false;
await tester.pumpWidget(ResizableWebView(
onResize: () {
if (resizeButtonTapped) {
buttonTapResizeCompleter.complete();
} else {
initialResizeCompleter.complete();
}
},
onPageFinished: () => onPageFinished.complete(),
));
await onPageFinished.future;
// Wait for a potential call to resize after page is loaded.
await initialResizeCompleter.future.timeout(
const Duration(seconds: 3),
onTimeout: () => null,
);
resizeButtonTapped = true;
await tester.tap(find.byKey(const ValueKey<String>('resizeButton')));
await tester.pumpAndSettle();
await expectLater(buttonTapResizeCompleter.future, completes);
});
testWidgets('set custom userAgent', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageFinished.complete()),
)
..setUserAgent('Custom_User_Agent1')
..loadRequest(LoadRequestParams(uri: Uri.parse('about:blank')));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageFinished.future;
final String customUserAgent = await _getUserAgent(controller);
expect(customUserAgent, 'Custom_User_Agent1');
});
group('Video playback policy', () {
late String videoTestBase64;
setUpAll(() async {
final ByteData videoData =
await rootBundle.load('assets/sample_video.mp4');
final String base64VideoData =
base64Encode(Uint8List.view(videoData.buffer));
final String videoTest = '''
<!DOCTYPE html><html>
<head><title>Video auto play</title>
<script type="text/javascript">
function play() {
var video = document.getElementById("video");
video.play();
video.addEventListener('timeupdate', videoTimeUpdateHandler, false);
}
function videoTimeUpdateHandler(e) {
var video = document.getElementById("video");
VideoTestTime.postMessage(video.currentTime);
}
function isPaused() {
var video = document.getElementById("video");
return video.paused;
}
function isFullScreen() {
var video = document.getElementById("video");
return video.webkitDisplayingFullscreen;
}
</script>
</head>
<body onload="play();">
<video controls playsinline autoplay id="video">
<source src="data:video/mp4;charset=utf-8;base64,$base64VideoData">
</video>
</body>
</html>
''';
videoTestBase64 = base64Encode(const Utf8Encoder().convert(videoTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
PlatformWebViewController controller = AndroidWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
AndroidNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..setMediaPlaybackRequiresUserGesture(false)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
bool isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, false);
pageLoaded = Completer<void>();
controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, true);
});
testWidgets('Video plays inline', (WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final Completer<void> videoPlaying = Completer<void>();
final PlatformWebViewController controller = AndroidWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
AndroidNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..addJavaScriptChannel(
JavaScriptChannelParams(
name: 'VideoTestTime',
onMessageReceived: (JavaScriptMessage message) {
final double currentTime = double.parse(message.message);
// Let it play for at least 1 second to make sure the related video's properties are set.
if (currentTime > 1 && !videoPlaying.isCompleted) {
videoPlaying.complete(null);
}
},
),
)
..setMediaPlaybackRequiresUserGesture(false)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
// Makes sure we get the correct event that indicates the video is actually playing.
await videoPlaying.future;
final bool fullScreen = await controller
.runJavaScriptReturningResult('isFullScreen();') as bool;
expect(fullScreen, false);
});
});
group('Audio playback policy', () {
late String audioTestBase64;
setUpAll(() async {
final ByteData audioData =
await rootBundle.load('assets/sample_audio.ogg');
final String base64AudioData =
base64Encode(Uint8List.view(audioData.buffer));
final String audioTest = '''
<!DOCTYPE html><html>
<head><title>Audio auto play</title>
<script type="text/javascript">
function play() {
var audio = document.getElementById("audio");
audio.play();
}
function isPaused() {
var audio = document.getElementById("audio");
return audio.paused;
}
</script>
</head>
<body onload="play();">
<audio controls id="audio">
<source src="data:audio/ogg;charset=utf-8;base64,$base64AudioData">
</audio>
</body>
</html>
''';
audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
PlatformWebViewController controller = AndroidWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
AndroidNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..setMediaPlaybackRequiresUserGesture(false)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$audioTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
bool isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, false);
pageLoaded = Completer<void>();
controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$audioTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, true);
});
});
testWidgets('getTitle', (WidgetTester tester) async {
const String getTitleTest = '''
<!DOCTYPE html><html>
<head><title>Some title</title>
</head>
<body>
</body>
</html>
''';
final String getTitleTestBase64 =
base64Encode(const Utf8Encoder().convert(getTitleTest));
final Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$getTitleTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
// On at least iOS, it does not appear to be guaranteed that the native
// code has the title when the page load completes. Execute some JavaScript
// before checking the title to ensure that the page has been fully parsed
// and processed.
await controller.runJavaScript('1;');
final String? title = await controller.getTitle();
expect(title, 'Some title');
});
group('Programmatic Scroll', () {
testWidgets('setAndGetScrollPosition', (WidgetTester tester) async {
const String scrollTestPage = '''
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 100%;
width: 100%;
}
#container{
width:5000px;
height:5000px;
}
</style>
</head>
<body>
<div id="container"/>
</body>
</html>
''';
final String scrollTestPageBase64 =
base64Encode(const Utf8Encoder().convert(scrollTestPage));
final Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$scrollTestPageBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
await tester.pumpAndSettle(const Duration(seconds: 3));
Offset scrollPos = await controller.getScrollPosition();
// Check scrollTo()
const int X_SCROLL = 123;
const int Y_SCROLL = 321;
// Get the initial position; this ensures that scrollTo is actually
// changing something, but also gives the native view's scroll position
// time to settle.
expect(scrollPos.dx, isNot(X_SCROLL));
expect(scrollPos.dy, isNot(Y_SCROLL));
await controller.scrollTo(X_SCROLL, Y_SCROLL);
scrollPos = await controller.getScrollPosition();
expect(scrollPos.dx, X_SCROLL);
expect(scrollPos.dy, Y_SCROLL);
// Check scrollBy() (on top of scrollTo())
await controller.scrollBy(X_SCROLL, Y_SCROLL);
scrollPos = await controller.getScrollPosition();
expect(scrollPos.dx, X_SCROLL * 2);
expect(scrollPos.dy, Y_SCROLL * 2);
});
});
group('NavigationDelegate', () {
const String blankPage = '<!DOCTYPE html><head></head><body></body></html>';
final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,'
'${base64Encode(const Utf8Encoder().convert(blankPage))}';
testWidgets('can allow requests', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageLoaded.complete())
..setOnNavigationRequest((NavigationRequest navigationRequest) {
return (navigationRequest.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
}),
)
..loadRequest(
LoadRequestParams(uri: Uri.parse(blankPageEncoded)),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller.runJavaScript('location.href = "$secondaryUrl"');
await pageLoaded.future; // Wait for the next page load.
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
testWidgets('onWebResourceError', (WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnWebResourceError((WebResourceError error) {
errorCompleter.complete(error);
}),
)
..loadRequest(
LoadRequestParams(uri: Uri.parse('https://www.notawebsite..com')),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
final WebResourceError error = await errorCompleter.future;
expect(error, isNotNull);
expect(error.errorType, isNotNull);
expect(
(error as AndroidWebResourceError)
.failingUrl
?.startsWith('https://www.notawebsite..com'),
isTrue,
);
});
testWidgets('onWebResourceError is not called with valid url',
(WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final Completer<void> pageFinishCompleter = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageFinishCompleter.complete())
..setOnWebResourceError((WebResourceError error) {
errorCompleter.complete(error);
}),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
expect(errorCompleter.future, doesNotComplete);
await pageFinishCompleter.future;
});
testWidgets('can block requests', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageLoaded.complete())
..setOnNavigationRequest((NavigationRequest navigationRequest) {
return (navigationRequest.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
}),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(blankPageEncoded)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller
.runJavaScript('location.href = "https://www.youtube.com/"');
// There should never be any second page load, since our new URL is
// blocked. Still wait for a potential page change for some time in order
// to give the test a chance to fail.
await pageLoaded.future
.timeout(const Duration(milliseconds: 500), onTimeout: () => false);
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, isNot(contains('youtube.com')));
});
testWidgets('supports asynchronous decisions', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)
..setOnPageFinished((_) => pageLoaded.complete())
..setOnNavigationRequest(
(NavigationRequest navigationRequest) async {
NavigationDecision decision = NavigationDecision.prevent;
decision = await Future<NavigationDecision>.delayed(
const Duration(milliseconds: 10),
() => NavigationDecision.navigate);
return decision;
}),
)
..loadRequest(LoadRequestParams(uri: Uri.parse(blankPageEncoded)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller.runJavaScript('location.href = "$secondaryUrl"');
await pageLoaded.future; // Wait for second page to load.
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
});
testWidgets('target _blank opens in same window',
(WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await controller.runJavaScript('window.open("$primaryUrl", "_blank")');
await pageLoaded.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets(
'can open new window and go back',
(WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()))
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
expect(controller.currentUrl(), completion(primaryUrl));
await pageLoaded.future;
pageLoaded = Completer<void>();
await controller.runJavaScript('window.open("$secondaryUrl")');
await pageLoaded.future;
pageLoaded = Completer<void>();
expect(controller.currentUrl(), completion(secondaryUrl));
expect(controller.canGoBack(), completion(true));
await controller.goBack();
await pageLoaded.future;
await expectLater(controller.currentUrl(), completion(primaryUrl));
},
);
testWidgets(
'JavaScript does not run in parent window',
(WidgetTester tester) async {
const String iframe = '''
<!DOCTYPE html>
<script>
window.onload = () => {
window.open(`javascript:
var elem = document.createElement("p");
elem.innerHTML = "<b>Executed JS in parent origin: " + window.location.origin + "</b>";
document.body.append(elem);
`);
};
</script>
''';
final String iframeTestBase64 =
base64Encode(const Utf8Encoder().convert(iframe));
final String openWindowTest = '''
<!DOCTYPE html>
<html>
<head>
<title>XSS test</title>
</head>
<body>
<iframe
onload="window.iframeLoaded = true;"
src="data:text/html;charset=utf-8;base64,$iframeTestBase64"></iframe>
</body>
</html>
''';
final String openWindowTestBase64 =
base64Encode(const Utf8Encoder().convert(openWindowTest));
final Completer<void> pageLoadCompleter = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoadCompleter.complete()))
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,$openWindowTestBase64',
),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoadCompleter.future;
final bool iframeLoaded =
await controller.runJavaScriptReturningResult('iframeLoaded') as bool;
expect(iframeLoaded, true);
final String elementText = await controller.runJavaScriptReturningResult(
'document.querySelector("p") && document.querySelector("p").textContent',
) as String;
expect(elementText, 'null');
},
);
testWidgets(
'`AndroidWebViewController` can be reused with a new `AndroidWebViewWidget`',
(WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setPlatformNavigationDelegate(PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => pageLoaded.complete()))
..loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl)));
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
await pageLoaded.future;
await tester.pumpWidget(Container());
await tester.pumpAndSettle();
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
},
));
pageLoaded = Completer<void>();
await controller.loadRequest(
LoadRequestParams(uri: Uri.parse(primaryUrl)),
);
await expectLater(
pageLoaded.future,
completes,
);
},
);
}
/// Returns the value used for the HTTP User-Agent: request header in subsequent HTTP requests.
Future<String> _getUserAgent(PlatformWebViewController controller) async {
return _runJavaScriptReturningResult(controller, 'navigator.userAgent;');
}
Future<String> _runJavaScriptReturningResult(
PlatformWebViewController controller,
String js,
) async {
return jsonDecode(await controller.runJavaScriptReturningResult(js) as String)
as String;
}
class ResizableWebView extends StatefulWidget {
const ResizableWebView({
Key? key,
required this.onResize,
required this.onPageFinished,
}) : super(key: key);
final VoidCallback onResize;
final VoidCallback onPageFinished;
@override
State<StatefulWidget> createState() => ResizableWebViewState();
}
class ResizableWebViewState extends State<ResizableWebView> {
late final PlatformWebViewController controller = PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)..setOnPageFinished((_) => widget.onPageFinished()),
)
..addJavaScriptChannel(
JavaScriptChannelParams(
name: 'Resize',
onMessageReceived: (_) {
widget.onResize();
},
),
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse(
'data:text/html;charset=utf-8;base64,${base64Encode(const Utf8Encoder().convert(resizePage))}',
),
),
);
double webViewWidth = 200;
double webViewHeight = 200;
static const String resizePage = '''
<!DOCTYPE html><html>
<head><title>Resize test</title>
<script type="text/javascript">
function onResize() {
Resize.postMessage("resize");
}
function onLoad() {
window.onresize = onResize;
}
</script>
</head>
<body onload="onLoad();" bgColor="blue">
</body>
</html>
''';
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
SizedBox(
width: webViewWidth,
height: webViewHeight,
child: PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context),
),
TextButton(
key: const Key('resizeButton'),
onPressed: () {
setState(() {
webViewWidth += 100.0;
webViewHeight += 100.0;
});
},
child: const Text('ResizeButton'),
),
],
),
);
}
}
class CopyableObjectWithCallback with Copyable {
CopyableObjectWithCallback(this.callback);
final VoidCallback callback;
@override
CopyableObjectWithCallback copy() {
return CopyableObjectWithCallback(callback);
}
}
class ClassWithCallbackClass {
ClassWithCallbackClass() {
callbackClass = CopyableObjectWithCallback(
withWeakReferenceTo(
this,
(WeakReference<ClassWithCallbackClass> weakReference) {
return () {
// Weak reference to `this` in callback.
// ignore: unnecessary_statements
weakReference;
};
},
),
);
}
late final CopyableObjectWithCallback callbackClass;
}
| plugins/packages/webview_flutter/webview_flutter_android/example/integration_test/webview_flutter_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/integration_test/webview_flutter_test.dart",
"repo_id": "plugins",
"token_count": 17333
} | 1,183 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore: implementation_imports
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import '../android_webview.dart' as android_webview;
/// Handles all cookie operations for the current platform.
class WebViewAndroidCookieManager extends WebViewCookieManagerPlatform {
@override
Future<bool> clearCookies() =>
android_webview.CookieManager.instance.clearCookies();
@override
Future<void> setCookie(WebViewCookie cookie) {
if (!_isValidPath(cookie.path)) {
throw ArgumentError(
'The path property for the provided cookie was not given a legal value.');
}
return android_webview.CookieManager.instance.setCookie(
cookie.domain,
'${Uri.encodeComponent(cookie.name)}=${Uri.encodeComponent(cookie.value)}; path=${cookie.path}',
);
}
bool _isValidPath(String path) {
// Permitted ranges based on RFC6265bis: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1
for (final int char in path.codeUnits) {
if ((char < 0x20 || char > 0x3A) && (char < 0x3C || char > 0x7E)) {
return false;
}
}
return true;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_cookie_manager.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_cookie_manager.dart",
"repo_id": "plugins",
"token_count": 482
} | 1,184 |
// 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:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
void main() {
final Map<String, String> log = <String, String>{};
final Set<JavascriptChannel> channels = <JavascriptChannel>{
JavascriptChannel(
name: 'js_channel_1',
onMessageReceived: (JavascriptMessage message) =>
log['js_channel_1'] = message.message,
),
JavascriptChannel(
name: 'js_channel_2',
onMessageReceived: (JavascriptMessage message) =>
log['js_channel_2'] = message.message,
),
JavascriptChannel(
name: 'js_channel_3',
onMessageReceived: (JavascriptMessage message) =>
log['js_channel_3'] = message.message,
),
};
tearDown(() {
log.clear();
});
test('ctor should initialize with channels.', () {
final JavascriptChannelRegistry registry =
JavascriptChannelRegistry(channels);
expect(registry.channels.length, 3);
for (final JavascriptChannel channel in channels) {
expect(registry.channels[channel.name], channel);
}
});
test('onJavascriptChannelMessage should forward message on correct channel.',
() {
final JavascriptChannelRegistry registry =
JavascriptChannelRegistry(channels);
registry.onJavascriptChannelMessage(
'js_channel_2',
'test message on channel 2',
);
expect(
log,
containsPair(
'js_channel_2',
'test message on channel 2',
));
});
test(
'onJavascriptChannelMessage should throw ArgumentError when message arrives on non-existing channel.',
() {
final JavascriptChannelRegistry registry =
JavascriptChannelRegistry(channels);
expect(
() => registry.onJavascriptChannelMessage(
'js_channel_4',
'test message on channel 2',
),
throwsA(
isA<ArgumentError>().having((ArgumentError error) => error.message,
'message', 'No channel registered with name js_channel_4.'),
));
});
test(
'updateJavascriptChannelsFromSet should clear all channels when null is supplied.',
() {
final JavascriptChannelRegistry registry =
JavascriptChannelRegistry(channels);
expect(registry.channels.length, 3);
registry.updateJavascriptChannelsFromSet(null);
expect(registry.channels, isEmpty);
});
test('updateJavascriptChannelsFromSet should update registry with new set.',
() {
final JavascriptChannelRegistry registry =
JavascriptChannelRegistry(channels);
expect(registry.channels.length, 3);
final Set<JavascriptChannel> newChannels = <JavascriptChannel>{
JavascriptChannel(
name: 'new_js_channel_1',
onMessageReceived: (JavascriptMessage message) =>
log['new_js_channel_1'] = message.message,
),
JavascriptChannel(
name: 'new_js_channel_2',
onMessageReceived: (JavascriptMessage message) =>
log['new_js_channel_2'] = message.message,
),
};
registry.updateJavascriptChannelsFromSet(newChannels);
expect(registry.channels.length, 2);
for (final JavascriptChannel channel in newChannels) {
expect(registry.channels[channel.name], channel);
}
});
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/javascript_channel_registry_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/platform_interface/javascript_channel_registry_test.dart",
"repo_id": "plugins",
"token_count": 1306
} | 1,185 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html';
/// Factory class for creating [HttpRequest] instances.
class HttpRequestFactory {
/// Creates a [HttpRequestFactory].
const HttpRequestFactory();
/// Creates and sends a URL request for the specified [url].
///
/// By default `request` will perform an HTTP GET request, but a different
/// method (`POST`, `PUT`, `DELETE`, etc) can be used by specifying the
/// [method] parameter. (See also [HttpRequest.postFormData] for `POST`
/// requests only.
///
/// The Future is completed when the response is available.
///
/// If specified, `sendData` will send data in the form of a [ByteBuffer],
/// [Blob], [Document], [String], or [FormData] along with the HttpRequest.
///
/// If specified, [responseType] sets the desired response format for the
/// request. By default it is [String], but can also be 'arraybuffer', 'blob',
/// 'document', 'json', or 'text'. See also [HttpRequest.responseType]
/// for more information.
///
/// The [withCredentials] parameter specified that credentials such as a cookie
/// (already) set in the header or
/// [authorization headers](http://tools.ietf.org/html/rfc1945#section-10.2)
/// should be specified for the request. Details to keep in mind when using
/// credentials:
///
/// /// Using credentials is only useful for cross-origin requests.
/// /// The `Access-Control-Allow-Origin` header of `url` cannot contain a wildcard (///).
/// /// The `Access-Control-Allow-Credentials` header of `url` must be set to true.
/// /// If `Access-Control-Expose-Headers` has not been set to true, only a subset of all the response headers will be returned when calling [getAllResponseHeaders].
///
/// The following is equivalent to the [getString] sample above:
///
/// var name = Uri.encodeQueryComponent('John');
/// var id = Uri.encodeQueryComponent('42');
/// HttpRequest.request('users.json?name=$name&id=$id')
/// .then((HttpRequest resp) {
/// // Do something with the response.
/// });
///
/// Here's an example of submitting an entire form with [FormData].
///
/// var myForm = querySelector('form#myForm');
/// var data = new FormData(myForm);
/// HttpRequest.request('/submit', method: 'POST', sendData: data)
/// .then((HttpRequest resp) {
/// // Do something with the response.
/// });
///
/// Note that requests for file:// URIs are only supported by Chrome extensions
/// with appropriate permissions in their manifest. Requests to file:// URIs
/// will also never fail- the Future will always complete successfully, even
/// when the file cannot be found.
///
/// See also: [authorization headers](http://en.wikipedia.org/wiki/Basic_access_authentication).
Future<HttpRequest> request(String url,
{String? method,
bool? withCredentials,
String? responseType,
String? mimeType,
Map<String, String>? requestHeaders,
dynamic sendData,
void Function(ProgressEvent e)? onProgress}) {
return HttpRequest.request(url,
method: method,
withCredentials: withCredentials,
responseType: responseType,
mimeType: mimeType,
requestHeaders: requestHeaders,
sendData: sendData,
onProgress: onProgress);
}
}
| plugins/packages/webview_flutter/webview_flutter_web/lib/src/http_request_factory.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_web/lib/src/http_request_factory.dart",
"repo_id": "plugins",
"token_count": 1093
} | 1,186 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFDataConvertersTests : XCTestCase
@end
@implementation FWFDataConvertersTests
- (void)testFWFNSURLRequestFromRequestData {
NSURLRequest *request = FWFNSURLRequestFromRequestData([FWFNSUrlRequestData
makeWithUrl:@"https://flutter.dev"
httpMethod:@"post"
httpBody:[FlutterStandardTypedData typedDataWithBytes:[NSData data]]
allHttpHeaderFields:@{@"a" : @"header"}]);
XCTAssertEqualObjects(request.URL, [NSURL URLWithString:@"https://flutter.dev"]);
XCTAssertEqualObjects(request.HTTPMethod, @"POST");
XCTAssertEqualObjects(request.HTTPBody, [NSData data]);
XCTAssertEqualObjects(request.allHTTPHeaderFields, @{@"a" : @"header"});
}
- (void)testFWFNSURLRequestFromRequestDataDoesNotOverrideDefaultValuesWithNull {
NSURLRequest *request =
FWFNSURLRequestFromRequestData([FWFNSUrlRequestData makeWithUrl:@"https://flutter.dev"
httpMethod:nil
httpBody:nil
allHttpHeaderFields:@{}]);
XCTAssertEqualObjects(request.HTTPMethod, @"GET");
}
- (void)testFWFNSHTTPCookieFromCookieData {
NSHTTPCookie *cookie = FWFNSHTTPCookieFromCookieData([FWFNSHttpCookieData
makeWithPropertyKeys:@[ [FWFNSHttpCookiePropertyKeyEnumData
makeWithValue:FWFNSHttpCookiePropertyKeyEnumName] ]
propertyValues:@[ @"cookieName" ]]);
XCTAssertEqualObjects(cookie,
[NSHTTPCookie cookieWithProperties:@{NSHTTPCookieName : @"cookieName"}]);
}
- (void)testFWFWKUserScriptFromScriptData {
WKUserScript *userScript = FWFWKUserScriptFromScriptData([FWFWKUserScriptData
makeWithSource:@"mySource"
injectionTime:[FWFWKUserScriptInjectionTimeEnumData
makeWithValue:FWFWKUserScriptInjectionTimeEnumAtDocumentStart]
isMainFrameOnly:@NO]);
XCTAssertEqualObjects(userScript.source, @"mySource");
XCTAssertEqual(userScript.injectionTime, WKUserScriptInjectionTimeAtDocumentStart);
XCTAssertEqual(userScript.isForMainFrameOnly, NO);
}
- (void)testFWFWKNavigationActionDataFromNavigationAction {
WKNavigationAction *mockNavigationAction = OCMClassMock([WKNavigationAction class]);
OCMStub([mockNavigationAction navigationType]).andReturn(WKNavigationTypeReload);
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.flutter.dev/"]];
OCMStub([mockNavigationAction request]).andReturn(request);
WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]);
OCMStub([mockFrameInfo isMainFrame]).andReturn(YES);
OCMStub([mockNavigationAction targetFrame]).andReturn(mockFrameInfo);
FWFWKNavigationActionData *data =
FWFWKNavigationActionDataFromNavigationAction(mockNavigationAction);
XCTAssertNotNil(data);
XCTAssertEqual(data.navigationType, FWFWKNavigationTypeReload);
}
- (void)testFWFNSUrlRequestDataFromNSURLRequest {
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.flutter.dev/"]];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"aString" dataUsingEncoding:NSUTF8StringEncoding];
request.allHTTPHeaderFields = @{@"a" : @"field"};
FWFNSUrlRequestData *data = FWFNSUrlRequestDataFromNSURLRequest(request);
XCTAssertEqualObjects(data.url, @"https://www.flutter.dev/");
XCTAssertEqualObjects(data.httpMethod, @"POST");
XCTAssertEqualObjects(data.httpBody.data, [@"aString" dataUsingEncoding:NSUTF8StringEncoding]);
XCTAssertEqualObjects(data.allHttpHeaderFields, @{@"a" : @"field"});
}
- (void)testFWFWKFrameInfoDataFromWKFrameInfo {
WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]);
OCMStub([mockFrameInfo isMainFrame]).andReturn(YES);
FWFWKFrameInfoData *targetFrameData = FWFWKFrameInfoDataFromWKFrameInfo(mockFrameInfo);
XCTAssertEqualObjects(targetFrameData.isMainFrame, @YES);
}
- (void)testFWFNSErrorDataFromNSError {
NSError *error = [NSError errorWithDomain:@"domain"
code:23
userInfo:@{NSLocalizedDescriptionKey : @"description"}];
FWFNSErrorData *data = FWFNSErrorDataFromNSError(error);
XCTAssertEqualObjects(data.code, @23);
XCTAssertEqualObjects(data.domain, @"domain");
XCTAssertEqualObjects(data.localizedDescription, @"description");
}
- (void)testFWFWKScriptMessageDataFromWKScriptMessage {
WKScriptMessage *mockScriptMessage = OCMClassMock([WKScriptMessage class]);
OCMStub([mockScriptMessage name]).andReturn(@"name");
OCMStub([mockScriptMessage body]).andReturn(@"message");
FWFWKScriptMessageData *data = FWFWKScriptMessageDataFromWKScriptMessage(mockScriptMessage);
XCTAssertEqualObjects(data.name, @"name");
XCTAssertEqualObjects(data.body, @"message");
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFDataConvertersTests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFDataConvertersTests.m",
"repo_id": "plugins",
"token_count": 2093
} | 1,187 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFHTTPCookieStoreHostApi.h"
#import "FWFDataConverters.h"
#import "FWFWebsiteDataStoreHostApi.h"
@interface FWFHTTPCookieStoreHostApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFHTTPCookieStoreHostApiImpl
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (WKHTTPCookieStore *)HTTPCookieStoreForIdentifier:(NSNumber *)identifier
API_AVAILABLE(ios(11.0)) {
return (WKHTTPCookieStore *)[self.instanceManager instanceForIdentifier:identifier.longValue];
}
- (void)createFromWebsiteDataStoreWithIdentifier:(nonnull NSNumber *)identifier
dataStoreIdentifier:(nonnull NSNumber *)websiteDataStoreIdentifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
if (@available(iOS 11.0, *)) {
WKWebsiteDataStore *dataStore = (WKWebsiteDataStore *)[self.instanceManager
instanceForIdentifier:websiteDataStoreIdentifier.longValue];
[self.instanceManager addDartCreatedInstance:dataStore.httpCookieStore
withIdentifier:identifier.longValue];
} else {
*error = [FlutterError
errorWithCode:@"FWFUnsupportedVersionError"
message:@"WKWebsiteDataStore.httpCookieStore is only supported on versions 11+."
details:nil];
}
}
- (void)setCookieForStoreWithIdentifier:(nonnull NSNumber *)identifier
cookie:(nonnull FWFNSHttpCookieData *)cookie
completion:(nonnull void (^)(FlutterError *_Nullable))completion {
NSHTTPCookie *nsCookie = FWFNSHTTPCookieFromCookieData(cookie);
if (@available(iOS 11.0, *)) {
[[self HTTPCookieStoreForIdentifier:identifier] setCookie:nsCookie
completionHandler:^{
completion(nil);
}];
} else {
completion([FlutterError errorWithCode:@"FWFUnsupportedVersionError"
message:@"setCookie is only supported on versions 11+."
details:nil]);
}
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFHTTPCookieStoreHostApi.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFHTTPCookieStoreHostApi.m",
"repo_id": "plugins",
"token_count": 1145
} | 1,188 |
// Mocks generated by Mockito 5.3.2 from annotations
// in webview_flutter_wkwebview/test/webkit_navigation_delegate_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'dart:ui' as _i6;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'
as _i5;
import 'package:webview_flutter_wkwebview/src/ui_kit/ui_kit.dart' as _i3;
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeWKWebViewConfiguration_0 extends _i1.SmartFake
implements _i2.WKWebViewConfiguration {
_FakeWKWebViewConfiguration_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeUIScrollView_1 extends _i1.SmartFake implements _i3.UIScrollView {
_FakeUIScrollView_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWKWebView_2 extends _i1.SmartFake implements _i2.WKWebView {
_FakeWKWebView_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [WKWebView].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockWKWebView extends _i1.Mock implements _i2.WKWebView {
MockWKWebView() {
_i1.throwOnMissingStub(this);
}
@override
_i2.WKWebViewConfiguration get configuration => (super.noSuchMethod(
Invocation.getter(#configuration),
returnValue: _FakeWKWebViewConfiguration_0(
this,
Invocation.getter(#configuration),
),
) as _i2.WKWebViewConfiguration);
@override
_i3.UIScrollView get scrollView => (super.noSuchMethod(
Invocation.getter(#scrollView),
returnValue: _FakeUIScrollView_1(
this,
Invocation.getter(#scrollView),
),
) as _i3.UIScrollView);
@override
_i4.Future<void> setUIDelegate(_i2.WKUIDelegate? delegate) =>
(super.noSuchMethod(
Invocation.method(
#setUIDelegate,
[delegate],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setNavigationDelegate(_i2.WKNavigationDelegate? delegate) =>
(super.noSuchMethod(
Invocation.method(
#setNavigationDelegate,
[delegate],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<String?> getUrl() => (super.noSuchMethod(
Invocation.method(
#getUrl,
[],
),
returnValue: _i4.Future<String?>.value(),
) as _i4.Future<String?>);
@override
_i4.Future<double> getEstimatedProgress() => (super.noSuchMethod(
Invocation.method(
#getEstimatedProgress,
[],
),
returnValue: _i4.Future<double>.value(0.0),
) as _i4.Future<double>);
@override
_i4.Future<void> loadRequest(_i5.NSUrlRequest? request) =>
(super.noSuchMethod(
Invocation.method(
#loadRequest,
[request],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> loadHtmlString(
String? string, {
String? baseUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadHtmlString,
[string],
{#baseUrl: baseUrl},
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> loadFileUrl(
String? url, {
required String? readAccessUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadFileUrl,
[url],
{#readAccessUrl: readAccessUrl},
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod(
Invocation.method(
#loadFlutterAsset,
[key],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<bool> canGoBack() => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[],
),
returnValue: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> canGoForward() => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[],
),
returnValue: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<void> goBack() => (super.noSuchMethod(
Invocation.method(
#goBack,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> goForward() => (super.noSuchMethod(
Invocation.method(
#goForward,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<String?> getTitle() => (super.noSuchMethod(
Invocation.method(
#getTitle,
[],
),
returnValue: _i4.Future<String?>.value(),
) as _i4.Future<String?>);
@override
_i4.Future<void> setAllowsBackForwardNavigationGestures(bool? allow) =>
(super.noSuchMethod(
Invocation.method(
#setAllowsBackForwardNavigationGestures,
[allow],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setCustomUserAgent(String? userAgent) => (super.noSuchMethod(
Invocation.method(
#setCustomUserAgent,
[userAgent],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<Object?> evaluateJavaScript(String? javaScriptString) =>
(super.noSuchMethod(
Invocation.method(
#evaluateJavaScript,
[javaScriptString],
),
returnValue: _i4.Future<Object?>.value(),
) as _i4.Future<Object?>);
@override
_i2.WKWebView copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWKWebView_2(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WKWebView);
@override
_i4.Future<void> setBackgroundColor(_i6.Color? color) => (super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[color],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setOpaque(bool? opaque) => (super.noSuchMethod(
Invocation.method(
#setOpaque,
[opaque],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> addObserver(
_i5.NSObject? observer, {
required String? keyPath,
required Set<_i5.NSKeyValueObservingOptions>? options,
}) =>
(super.noSuchMethod(
Invocation.method(
#addObserver,
[observer],
{
#keyPath: keyPath,
#options: options,
},
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> removeObserver(
_i5.NSObject? observer, {
required String? keyPath,
}) =>
(super.noSuchMethod(
Invocation.method(
#removeObserver,
[observer],
{#keyPath: keyPath},
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.mocks.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.mocks.dart",
"repo_id": "plugins",
"token_count": 4378
} | 1,189 |
name: flutter_plugin_tools
description: Productivity utils for flutter/plugins and flutter/packages
repository: https://github.com/flutter/plugins/tree/main/script/tool
version: 0.13.4+2
publish_to: none # See README.md
dependencies:
args: ^2.1.0
async: ^2.6.1
collection: ^1.15.0
colorize: ^3.0.0
file: ^6.1.0
# Pin git to 2.0.x until dart >=2.18 is legacy
git: '>=2.0.0 <2.1.0'
http: ^0.13.3
http_multi_server: ^3.0.1
meta: ^1.3.0
path: ^1.8.0
platform: ^3.0.0
pub_semver: ^2.0.0
pubspec_parse: ^1.0.0
quiver: ^3.0.1
test: ^1.17.3
uuid: ^3.0.4
yaml: ^3.1.0
yaml_edit: ^2.0.2
dev_dependencies:
build_runner: ^2.0.3
matcher: ^0.12.10
mockito: ^5.0.7
environment:
sdk: '>=2.12.0 <3.0.0'
| plugins/script/tool/pubspec.yaml/0 | {
"file_path": "plugins/script/tool/pubspec.yaml",
"repo_id": "plugins",
"token_count": 367
} | 1,190 |
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 31
defaultConfig {
applicationId "dev.flutter.example.androidView"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.vectordrawable:vectordrawable:1.1.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.2'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.2'
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation project(path: ':flutter')
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
} | samples/add_to_app/android_view/android_view/app/build.gradle/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/build.gradle",
"repo_id": "samples",
"token_count": 720
} | 1,191 |
#Wed Mar 10 09:46:16 PST 2021
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
| samples/add_to_app/android_view/android_view/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "samples/add_to_app/android_view/android_view/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "samples",
"token_count": 83
} | 1,192 |
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 31
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "dev.flutter.example.books"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
profile {
initWith debug
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig debug.signingConfig
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.squareup.okhttp3:okhttp:4.7.2"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation "androidx.activity:activity-ktx:1.1.0"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation project(path: ':flutter')
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
} | samples/add_to_app/books/android_books/app/build.gradle/0 | {
"file_path": "samples/add_to_app/books/android_books/app/build.gradle",
"repo_id": "samples",
"token_count": 701
} | 1,193 |
include ':app'
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir,
'../flutter_module_books/.android/include_flutter.groovy'
))
rootProject.name = "Android Books"
| samples/add_to_app/books/android_books/settings.gradle/0 | {
"file_path": "samples/add_to_app/books/android_books/settings.gradle",
"repo_id": "samples",
"token_count": 64
} | 1,194 |
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:IosBooks.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
| samples/add_to_app/books/ios_books/IosBooks.xcworkspace/contents.xcworkspacedata/0 | {
"file_path": "samples/add_to_app/books/ios_books/IosBooks.xcworkspace/contents.xcworkspacedata",
"repo_id": "samples",
"token_count": 105
} | 1,195 |
# fullscreen
Embeds a full screen instance of Flutter into an existing iOS or Android app.
## Description
These apps showcase a relatively straightforward integration of
`flutter_module`:
* The Flutter module is built along with the app when the app is built.
* The Flutter engine is warmed up at app launch.
* The Flutter view is presented with a full-screen Activity or
UIViewController.
* The Flutter view is a navigational leaf node; it does not launch any new,
native Activities or UIViewControllers in response to user actions.
If you are new to Flutter's add-to-app APIs, these projects are a great place
to begin learning how to use them.
## tl;dr
If you're just looking to get up and running quickly, these bash commands will
fetch packages and set up dependencies (note that the above commands assume
you're building for both iOS and Android, with both toolchains installed):
```bash
#!/bin/bash
set -e
cd flutter_module/
flutter pub get
# For Android builds:
open -a "Android Studio" ../android_fullscreen # macOS only
# Or open the ../android_fullscreen folder in Android Studio for other platforms.
# For iOS builds:
cd ../ios_fullscreen
pod install
open IOSFullScreen.xcworkspace
```
## Requirements
* Flutter
* Android
* Android Studio
* iOS
* Xcode
* Cocoapods
## Questions/issues
See [add_to_app/README.md](../README.md) for further help.
| samples/add_to_app/fullscreen/README.md/0 | {
"file_path": "samples/add_to_app/fullscreen/README.md",
"repo_id": "samples",
"token_count": 395
} | 1,196 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
| samples/add_to_app/fullscreen/android_fullscreen/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "samples",
"token_count": 71
} | 1,197 |
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:layout_marginRight="260dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toEndOf="@+id/countLabel"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/countLabel"
android:layout_width="58dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Count:"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:onClick="onClickNext"
android:text="Next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:onClick="onClickAdd"
android:text="Add"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout> | samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/layout/activity_main.xml/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/layout/activity_main.xml",
"repo_id": "samples",
"token_count": 866
} | 1,198 |
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MultipleFlutters" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources> | samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/values/themes.xml/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/values/themes.xml",
"repo_id": "samples",
"token_count": 316
} | 1,199 |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
void main() => runApp(const MyApp(color: Colors.blue));
@pragma('vm:entry-point')
void topMain() => runApp(const MyApp(color: Colors.green));
@pragma('vm:entry-point')
void bottomMain() => runApp(const MyApp(color: Colors.purple));
class MyApp extends StatelessWidget {
const MyApp({super.key, required this.color});
final MaterialColor color;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorSchemeSeed: color,
appBarTheme: AppBarTheme(
backgroundColor: color,
foregroundColor: Colors.white,
elevation: 8,
),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int? _counter = 0;
late MethodChannel _channel;
@override
void initState() {
super.initState();
_channel = const MethodChannel('multiple-flutters');
_channel.setMethodCallHandler((call) async {
if (call.method == "setCount") {
// A notification that the host platform's data model has been updated.
setState(() {
_counter = call.arguments as int?;
});
} else {
throw Exception('not implemented ${call.method}');
}
});
}
void _incrementCounter() {
// Mutations to the data model are forwarded to the host platform.
_channel.invokeMethod<void>("incrementCount", _counter);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
TextButton(
onPressed: _incrementCounter,
child: const Text('Add'),
),
TextButton(
onPressed: () {
_channel.invokeMethod<void>("next", _counter);
},
child: const Text('Next'),
),
ElevatedButton(
onPressed: () async {
// Use the url_launcher plugin to open the Flutter docs in
// a browser.
final url = Uri.parse('https://flutter.dev/docs');
if (await launcher.canLaunchUrl(url)) {
await launcher.launchUrl(url);
}
},
child: const Text('Open Flutter Docs'),
),
],
),
),
);
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_module/lib/main.dart/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_module/lib/main.dart",
"repo_id": "samples",
"token_count": 1413
} | 1,200 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
| samples/add_to_app/prebuilt_module/android_using_prebuilt_module/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "samples/add_to_app/prebuilt_module/android_using_prebuilt_module/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "samples",
"token_count": 71
} | 1,201 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import UIKit
import Flutter
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var flutterEngine : FlutterEngine?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Instantiate Flutter engine
self.flutterEngine = FlutterEngine(name: "io.flutter", project: nil)
self.flutterEngine?.run(withEntrypoint: nil)
return true
}
}
| samples/add_to_app/prebuilt_module/ios_using_prebuilt_module/IOSUsingPrebuiltModule/AppDelegate.swift/0 | {
"file_path": "samples/add_to_app/prebuilt_module/ios_using_prebuilt_module/IOSUsingPrebuiltModule/AppDelegate.swift",
"repo_id": "samples",
"token_count": 223
} | 1,202 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| samples/animations/android/gradle.properties/0 | {
"file_path": "samples/animations/android/gradle.properties",
"repo_id": "samples",
"token_count": 30
} | 1,203 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class CurvedAnimationDemo extends StatefulWidget {
const CurvedAnimationDemo({super.key});
static const String routeName = 'misc/curved_animation';
@override
State<CurvedAnimationDemo> createState() => _CurvedAnimationDemoState();
}
class CurveChoice {
final Curve curve;
final String name;
const CurveChoice({required this.curve, required this.name});
}
class _CurvedAnimationDemoState extends State<CurvedAnimationDemo>
with SingleTickerProviderStateMixin {
late final AnimationController controller;
late final Animation<double> animationRotation;
late final Animation<Offset> animationTranslation;
static const _duration = Duration(seconds: 4);
List<CurveChoice> curves = const [
CurveChoice(curve: Curves.bounceIn, name: 'Bounce In'),
CurveChoice(curve: Curves.bounceOut, name: 'Bounce Out'),
CurveChoice(curve: Curves.easeInCubic, name: 'Ease In Cubic'),
CurveChoice(curve: Curves.easeOutCubic, name: 'Ease Out Cubic'),
CurveChoice(curve: Curves.easeInExpo, name: 'Ease In Expo'),
CurveChoice(curve: Curves.easeOutExpo, name: 'Ease Out Expo'),
CurveChoice(curve: Curves.elasticIn, name: 'Elastic In'),
CurveChoice(curve: Curves.elasticOut, name: 'Elastic Out'),
CurveChoice(curve: Curves.easeInQuart, name: 'Ease In Quart'),
CurveChoice(curve: Curves.easeOutQuart, name: 'Ease Out Quart'),
CurveChoice(curve: Curves.easeInCirc, name: 'Ease In Circle'),
CurveChoice(curve: Curves.easeOutCirc, name: 'Ease Out Circle'),
];
late CurveChoice selectedForwardCurve, selectedReverseCurve;
late final CurvedAnimation curvedAnimation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: _duration,
vsync: this,
);
selectedForwardCurve = curves[0];
selectedReverseCurve = curves[0];
curvedAnimation = CurvedAnimation(
parent: controller,
curve: selectedForwardCurve.curve,
reverseCurve: selectedReverseCurve.curve,
);
animationRotation = Tween<double>(
begin: 0,
end: 2 * math.pi,
).animate(curvedAnimation)
..addListener(() {
setState(() {});
})
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
controller.reverse();
}
});
animationTranslation = Tween<Offset>(
begin: const Offset(-1, 0),
end: const Offset(1, 0),
).animate(curvedAnimation)
..addListener(() {
setState(() {});
})
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
controller.reverse();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Curved Animation'),
),
body: Column(
children: [
const SizedBox(height: 20.0),
Text(
'Select Curve for forward motion',
style: Theme.of(context).textTheme.titleLarge,
),
DropdownButton<CurveChoice>(
items: curves.map((curve) {
return DropdownMenuItem<CurveChoice>(
value: curve, child: Text(curve.name));
}).toList(),
onChanged: (newCurve) {
if (newCurve != null) {
setState(() {
selectedForwardCurve = newCurve;
curvedAnimation.curve = selectedForwardCurve.curve;
});
}
},
value: selectedForwardCurve,
),
const SizedBox(height: 15.0),
Text(
'Select Curve for reverse motion',
style: Theme.of(context).textTheme.titleLarge,
),
DropdownButton<CurveChoice>(
items: curves.map((curve) {
return DropdownMenuItem<CurveChoice>(
value: curve, child: Text(curve.name));
}).toList(),
onChanged: (newCurve) {
if (newCurve != null) {
setState(() {
selectedReverseCurve = newCurve;
curvedAnimation.reverseCurve = selectedReverseCurve.curve;
});
}
},
value: selectedReverseCurve,
),
const SizedBox(height: 35.0),
Transform.rotate(
angle: animationRotation.value,
child: const Center(
child: FlutterLogo(
size: 100,
),
),
),
const SizedBox(height: 35.0),
FractionalTranslation(
translation: animationTranslation.value,
child: const FlutterLogo(
size: 100,
),
),
const SizedBox(height: 25.0),
ElevatedButton(
onPressed: () {
controller.forward();
},
child: const Text('Animate'),
),
],
),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
| samples/animations/lib/src/misc/curved_animation.dart/0 | {
"file_path": "samples/animations/lib/src/misc/curved_animation.dart",
"repo_id": "samples",
"token_count": 2382
} | 1,204 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:animations/src/misc/animated_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Widget createAnimatedListDemoScreen() => const MaterialApp(
home: AnimatedListDemo(),
);
void main() {
group('Animated List Tests', () {
testWidgets('Initial length of list', (tester) async {
await tester.pumpWidget(createAnimatedListDemoScreen());
// Get the initial length of list.
var initialLength = tester.widgetList(find.byType(ListTile)).length;
// Initial length of list should be equal to 5.
expect(
initialLength,
equals(5),
);
});
testWidgets('Length of list increases on Add Icon Button tap',
(tester) async {
await tester.pumpWidget(createAnimatedListDemoScreen());
// Get the initial length of list.
var initialLength = tester.widgetList(find.byType(ListTile)).length;
// Tap on the Add Icon Button.
await tester.tap(find.byIcon(Icons.add));
await tester.pumpAndSettle();
// Get the new length of list.
var newLength = tester.widgetList(find.byType(ListTile)).length;
// New length should be greater than initial length by one.
expect(
newLength,
equals(initialLength + 1),
);
});
testWidgets(
'Length of list decreases on Delete Icon Button tap at middle index',
(tester) async {
await tester.pumpWidget(createAnimatedListDemoScreen());
// Get the initial length of list.
var initialLength = tester.widgetList(find.byType(ListTile)).length;
// Tap on the Delete Icon Button at middle index.
await tester.tap(find.byIcon(Icons.delete).at(initialLength ~/ 2));
await tester.pumpAndSettle();
// Get the new length of list.
var newLength = tester.widgetList(find.byType(ListTile)).length;
// New length should be less than initial length by one.
expect(
newLength,
equals(initialLength - 1),
);
});
testWidgets(
'Length of list decreases on Delete Icon Button tap at start index',
(tester) async {
await tester.pumpWidget(createAnimatedListDemoScreen());
// Get the initial length of list.
var initialLength = tester.widgetList(find.byType(ListTile)).length;
// Tap on the Delete Icon Button at start index.
await tester.tap(find.byIcon(Icons.delete).at(0));
await tester.pumpAndSettle();
// Get the new length of list.
var newLength = tester.widgetList(find.byType(ListTile)).length;
// New length should be less than initial length by one.
expect(
newLength,
equals(initialLength - 1),
);
});
testWidgets(
'Length of list decreases on Delete Icon Button tap at end index',
(tester) async {
await tester.pumpWidget(createAnimatedListDemoScreen());
// Get the initial length of list.
var initialLength = tester.widgetList(find.byType(ListTile)).length;
// Tap on the Delete Icon Button at end index.
await tester.tap(find.byIcon(Icons.delete).at(initialLength - 1));
await tester.pumpAndSettle();
// Get the new length of list.
var newLength = tester.widgetList(find.byType(ListTile)).length;
// New Length should be less than initial length by one.
expect(
newLength,
equals(initialLength - 1),
);
});
testWidgets('All ListTiles deleted', (tester) async {
await tester.pumpWidget(createAnimatedListDemoScreen());
// Get the initial length of list.
var initialLength = tester.widgetList(find.byType(ListTile)).length;
// Iterating over all the Delete Icon Buttons.
for (var i = 0; i < initialLength; i++) {
// Tap on the Delete Icon
await tester.tap(find.byIcon(Icons.delete).first);
await tester.pumpAndSettle();
}
// Get the final length of list.
var finalLength = tester.widgetList(find.byType(ListTile)).length;
// New length should be zero.
expect(
finalLength,
equals(0),
);
});
});
}
| samples/animations/test/misc/animated_list_test.dart/0 | {
"file_path": "samples/animations/test/misc/animated_list_test.dart",
"repo_id": "samples",
"token_count": 1640
} | 1,205 |
package com.example.client
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/code_sharing/client/android/app/src/main/kotlin/com/example/client/MainActivity.kt/0 | {
"file_path": "samples/code_sharing/client/android/app/src/main/kotlin/com/example/client/MainActivity.kt",
"repo_id": "samples",
"token_count": 36
} | 1,206 |
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'is_valid_email.dart';
import 'platform_selector.dart';
class EmailButtonPage extends StatelessWidget {
EmailButtonPage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'email-button';
static const String title = 'Email Button';
static const String subtitle = 'A selection-aware email button';
static const String url = '$kCodeUrl/email_button_page.dart';
final PlatformCallback onChangedPlatform;
final TextEditingController _controller = TextEditingController(
text: 'Select the email address and open the menu: [email protected]',
);
DialogRoute _showDialog(BuildContext context) {
return DialogRoute<void>(
context: context,
builder: (context) =>
const AlertDialog(title: Text('You clicked send email!')),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(EmailButtonPage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: Center(
child: SizedBox(
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 20.0),
const Text(
'This example shows how to add a special button to the context menu depending on the current selection.',
),
const SizedBox(height: 40.0),
TextField(
maxLines: 2,
controller: _controller,
contextMenuBuilder: (context, editableTextState) {
final TextEditingValue value =
editableTextState.textEditingValue;
final List<ContextMenuButtonItem> buttonItems =
editableTextState.contextMenuButtonItems;
if (isValidEmail(value.selection.textInside(value.text))) {
buttonItems.insert(
0,
ContextMenuButtonItem(
label: 'Send email',
onPressed: () {
ContextMenuController.removeAny();
Navigator.of(context).push(_showDialog(context));
},
));
}
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: editableTextState.contextMenuAnchors,
buttonItems: buttonItems,
);
},
),
],
),
),
),
);
}
}
| samples/context_menus/lib/email_button_page.dart/0 | {
"file_path": "samples/context_menus/lib/email_button_page.dart",
"repo_id": "samples",
"token_count": 1509
} | 1,207 |
package com.example.deeplink_store_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/deeplink_store_example/android/app/src/main/kotlin/com/example/deeplink_store_example/MainActivity.kt/0 | {
"file_path": "samples/deeplink_store_example/android/app/src/main/kotlin/com/example/deeplink_store_example/MainActivity.kt",
"repo_id": "samples",
"token_count": 43
} | 1,208 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import '../serializers.dart';
part 'links.g.dart';
abstract class Links implements Built<Links, LinksBuilder> {
factory Links([void Function(LinksBuilder)? updates]) = _$Links;
Links._();
@BuiltValueField(wireName: 'self')
String? get self;
@BuiltValueField(wireName: 'html')
String? get html;
@BuiltValueField(wireName: 'download')
String? get download;
@BuiltValueField(wireName: 'download_location')
String? get downloadLocation;
String toJson() {
return json.encode(serializers.serializeWith(Links.serializer, this));
}
static Links? fromJson(String jsonString) {
return serializers.deserializeWith(
Links.serializer, json.decode(jsonString));
}
static Serializer<Links> get serializer => _$linksSerializer;
}
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/links.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/links.dart",
"repo_id": "samples",
"token_count": 332
} | 1,209 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<User> _$userSerializer = new _$UserSerializer();
class _$UserSerializer implements StructuredSerializer<User> {
@override
final Iterable<Type> types = const [User, _$User];
@override
final String wireName = 'User';
@override
Iterable<Object?> serialize(Serializers serializers, User object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'id',
serializers.serialize(object.id, specifiedType: const FullType(String)),
'username',
serializers.serialize(object.username,
specifiedType: const FullType(String)),
'name',
serializers.serialize(object.name, specifiedType: const FullType(String)),
];
Object? value;
value = object.updatedAt;
if (value != null) {
result
..add('updated_at')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.portfolioUrl;
if (value != null) {
result
..add('portfolio_url')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.bio;
if (value != null) {
result
..add('bio')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.location;
if (value != null) {
result
..add('location')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.totalLikes;
if (value != null) {
result
..add('total_likes')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.totalPhotos;
if (value != null) {
result
..add('total_photos')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.totalCollections;
if (value != null) {
result
..add('total_collections')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.links;
if (value != null) {
result
..add('links')
..add(
serializers.serialize(value, specifiedType: const FullType(Links)));
}
return result;
}
@override
User deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new UserBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'id':
result.id = serializers.deserialize(value,
specifiedType: const FullType(String))! as String;
break;
case 'updated_at':
result.updatedAt = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'username':
result.username = serializers.deserialize(value,
specifiedType: const FullType(String))! as String;
break;
case 'name':
result.name = serializers.deserialize(value,
specifiedType: const FullType(String))! as String;
break;
case 'portfolio_url':
result.portfolioUrl = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'bio':
result.bio = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'location':
result.location = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'total_likes':
result.totalLikes = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'total_photos':
result.totalPhotos = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'total_collections':
result.totalCollections = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'links':
result.links.replace(serializers.deserialize(value,
specifiedType: const FullType(Links))! as Links);
break;
}
}
return result.build();
}
}
class _$User extends User {
@override
final String id;
@override
final String? updatedAt;
@override
final String username;
@override
final String name;
@override
final String? portfolioUrl;
@override
final String? bio;
@override
final String? location;
@override
final int? totalLikes;
@override
final int? totalPhotos;
@override
final int? totalCollections;
@override
final Links? links;
factory _$User([void Function(UserBuilder)? updates]) =>
(new UserBuilder()..update(updates))._build();
_$User._(
{required this.id,
this.updatedAt,
required this.username,
required this.name,
this.portfolioUrl,
this.bio,
this.location,
this.totalLikes,
this.totalPhotos,
this.totalCollections,
this.links})
: super._() {
BuiltValueNullFieldError.checkNotNull(id, r'User', 'id');
BuiltValueNullFieldError.checkNotNull(username, r'User', 'username');
BuiltValueNullFieldError.checkNotNull(name, r'User', 'name');
}
@override
User rebuild(void Function(UserBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
UserBuilder toBuilder() => new UserBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is User &&
id == other.id &&
updatedAt == other.updatedAt &&
username == other.username &&
name == other.name &&
portfolioUrl == other.portfolioUrl &&
bio == other.bio &&
location == other.location &&
totalLikes == other.totalLikes &&
totalPhotos == other.totalPhotos &&
totalCollections == other.totalCollections &&
links == other.links;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, id.hashCode);
_$hash = $jc(_$hash, updatedAt.hashCode);
_$hash = $jc(_$hash, username.hashCode);
_$hash = $jc(_$hash, name.hashCode);
_$hash = $jc(_$hash, portfolioUrl.hashCode);
_$hash = $jc(_$hash, bio.hashCode);
_$hash = $jc(_$hash, location.hashCode);
_$hash = $jc(_$hash, totalLikes.hashCode);
_$hash = $jc(_$hash, totalPhotos.hashCode);
_$hash = $jc(_$hash, totalCollections.hashCode);
_$hash = $jc(_$hash, links.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'User')
..add('id', id)
..add('updatedAt', updatedAt)
..add('username', username)
..add('name', name)
..add('portfolioUrl', portfolioUrl)
..add('bio', bio)
..add('location', location)
..add('totalLikes', totalLikes)
..add('totalPhotos', totalPhotos)
..add('totalCollections', totalCollections)
..add('links', links))
.toString();
}
}
class UserBuilder implements Builder<User, UserBuilder> {
_$User? _$v;
String? _id;
String? get id => _$this._id;
set id(String? id) => _$this._id = id;
String? _updatedAt;
String? get updatedAt => _$this._updatedAt;
set updatedAt(String? updatedAt) => _$this._updatedAt = updatedAt;
String? _username;
String? get username => _$this._username;
set username(String? username) => _$this._username = username;
String? _name;
String? get name => _$this._name;
set name(String? name) => _$this._name = name;
String? _portfolioUrl;
String? get portfolioUrl => _$this._portfolioUrl;
set portfolioUrl(String? portfolioUrl) => _$this._portfolioUrl = portfolioUrl;
String? _bio;
String? get bio => _$this._bio;
set bio(String? bio) => _$this._bio = bio;
String? _location;
String? get location => _$this._location;
set location(String? location) => _$this._location = location;
int? _totalLikes;
int? get totalLikes => _$this._totalLikes;
set totalLikes(int? totalLikes) => _$this._totalLikes = totalLikes;
int? _totalPhotos;
int? get totalPhotos => _$this._totalPhotos;
set totalPhotos(int? totalPhotos) => _$this._totalPhotos = totalPhotos;
int? _totalCollections;
int? get totalCollections => _$this._totalCollections;
set totalCollections(int? totalCollections) =>
_$this._totalCollections = totalCollections;
LinksBuilder? _links;
LinksBuilder get links => _$this._links ??= new LinksBuilder();
set links(LinksBuilder? links) => _$this._links = links;
UserBuilder();
UserBuilder get _$this {
final $v = _$v;
if ($v != null) {
_id = $v.id;
_updatedAt = $v.updatedAt;
_username = $v.username;
_name = $v.name;
_portfolioUrl = $v.portfolioUrl;
_bio = $v.bio;
_location = $v.location;
_totalLikes = $v.totalLikes;
_totalPhotos = $v.totalPhotos;
_totalCollections = $v.totalCollections;
_links = $v.links?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(User other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$User;
}
@override
void update(void Function(UserBuilder)? updates) {
if (updates != null) updates(this);
}
@override
User build() => _build();
_$User _build() {
_$User _$result;
try {
_$result = _$v ??
new _$User._(
id: BuiltValueNullFieldError.checkNotNull(id, r'User', 'id'),
updatedAt: updatedAt,
username: BuiltValueNullFieldError.checkNotNull(
username, r'User', 'username'),
name:
BuiltValueNullFieldError.checkNotNull(name, r'User', 'name'),
portfolioUrl: portfolioUrl,
bio: bio,
location: location,
totalLikes: totalLikes,
totalPhotos: totalPhotos,
totalCollections: totalCollections,
links: _links?.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'links';
_links?.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'User', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/user.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/user.g.dart",
"repo_id": "samples",
"token_count": 4603
} | 1,210 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:desktop_photo_search/src/model/photo_search_model.dart';
import 'package:desktop_photo_search/src/unsplash/photo.dart';
import 'package:desktop_photo_search/src/unsplash/search_photos_response.dart';
import 'package:desktop_photo_search/src/unsplash/unsplash.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
class FakeUnsplash implements Unsplash {
static const searchPhotosResponse = '''
{
"total": 133,
"total_pages": 7,
"results": [
{
"id": "eOLpJytrbsQ",
"created_at": "2014-11-18T14:35:36-05:00",
"width": 4000,
"height": 3000,
"color": "#A7A2A1",
"likes": 286,
"liked_by_user": false,
"description": "A man drinking a coffee.",
"user": {
"id": "Ul0QVz12Goo",
"username": "ugmonk",
"name": "Jeff Sheldon",
"first_name": "Jeff",
"last_name": "Sheldon",
"instagram_username": "instantgrammer",
"twitter_username": "ugmonk",
"portfolio_url": "http://ugmonk.com/",
"profile_image": {
"small": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=7cfe3b93750cb0c93e2f7caec08b5a41",
"medium": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64&s=5a9dc749c43ce5bd60870b129a40902f",
"large": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128&s=32085a077889586df88bfbe406692202"
},
"links": {
"self": "https://api.unsplash.com/users/ugmonk",
"html": "http://unsplash.com/@ugmonk",
"photos": "https://api.unsplash.com/users/ugmonk/photos",
"likes": "https://api.unsplash.com/users/ugmonk/likes"
}
},
"current_user_collections": [],
"urls": {
"raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
"full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
"regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
"small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
"thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
},
"links": {
"self": "https://api.unsplash.com/photos/eOLpJytrbsQ",
"html": "http://unsplash.com/photos/eOLpJytrbsQ",
"download": "http://unsplash.com/photos/eOLpJytrbsQ/download"
}
}
]
}
''';
@override
Future<SearchPhotosResponse?> searchPhotos(
{String? query,
num page = 1,
num perPage = 10,
List<num> collections = const [],
SearchPhotosOrientation? orientation}) async {
return SearchPhotosResponse.fromJson(searchPhotosResponse);
}
@override
Future<Uint8List> download(Photo photo) {
throw UnimplementedError();
}
}
const fabKey = Key('fab');
class PhotoSearchModelTester extends StatelessWidget {
const PhotoSearchModelTester({required this.query, super.key});
final String query;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TextButton(
key: fabKey,
onPressed: () async {
await Provider.of<PhotoSearchModel>(
context,
listen: false,
).addSearch(query);
},
child: const Text('Search for a Photo'),
),
);
}
}
void main() {
group('search_list', () {
testWidgets('starts empty', (tester) async {
final unsplashSearches = PhotoSearchModel(FakeUnsplash());
final testWidget = ChangeNotifierProvider<PhotoSearchModel>(
create: (context) => unsplashSearches,
child: const PhotoSearchModelTester(query: 'clouds'),
);
await tester.pumpWidget(testWidget);
expect(unsplashSearches.entries.length, 0);
});
testWidgets('addSearch adds searches', (tester) async {
final unsplashSearches = PhotoSearchModel(FakeUnsplash());
final testWidget = ChangeNotifierProvider<PhotoSearchModel>(
create: (context) => unsplashSearches,
child: const PhotoSearchModelTester(query: 'clouds'),
);
await tester.pumpWidget(testWidget);
await tester.tap(find.byKey(fabKey));
await tester.tap(find.byKey(fabKey));
await tester.pumpAndSettle();
expect(unsplashSearches.entries.length, 2);
});
});
}
| samples/desktop_photo_search/fluent_ui/test/widget_test.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/test/widget_test.dart",
"repo_id": "samples",
"token_count": 2318
} | 1,211 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Flutter
import UIKit
public class SwiftFederatedPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "battery", binaryMessenger: registrar.messenger())
let instance = SwiftFederatedPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
guard call.method == "getBatteryLevel" else {
result(FlutterMethodNotImplemented)
return
}
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState == UIDevice.BatteryState.unknown {
result(FlutterError(code: "STATUS_UNAVAILABLE", message: "Not able to determine battery level", details: nil))
}
result(Int(device.batteryLevel * 100))
}
}
| samples/experimental/federated_plugin/federated_plugin/ios/Classes/SwiftFederatedPlugin.swift/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/ios/Classes/SwiftFederatedPlugin.swift",
"repo_id": "samples",
"token_count": 346
} | 1,212 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:federated_plugin_platform_interface/federated_plugin_platform_interface.dart';
import 'package:flutter/services.dart';
/// Implements [FederatedPluginInterface] using [MethodChannel] to fetch
/// battery level from platform.
class BatteryMethodChannel extends FederatedPluginInterface {
static const MethodChannel _methodChannel = MethodChannel('battery');
@override
Future<int> getBatteryLevel() async {
return await _methodChannel.invokeMethod<int>('getBatteryLevel') as int;
}
}
| samples/experimental/federated_plugin/federated_plugin_platform_interface/lib/battery_method_channel.dart/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_platform_interface/lib/battery_method_channel.dart",
"repo_id": "samples",
"token_count": 182
} | 1,213 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class RulesProfileAdapter extends TypeAdapter<RulesProfile> {
@override
final int typeId = 1;
@override
RulesProfile read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return RulesProfile(
name: fields[0] as String,
rules: (fields[1] as List).cast<Rule>(),
);
}
@override
void write(BinaryWriter writer, RulesProfile obj) {
writer
..writeByte(2)
..writeByte(0)
..write(obj.name)
..writeByte(1)
..write(obj.rules);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is RulesProfileAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| samples/experimental/linting_tool/lib/model/profile.g.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/model/profile.g.dart",
"repo_id": "samples",
"token_count": 391
} | 1,214 |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show SystemUiOverlayStyle;
import 'package:linting_tool/layout/adaptive.dart';
import 'package:linting_tool/pages/default_lints_page.dart';
import 'package:linting_tool/pages/home_page.dart';
import 'package:linting_tool/pages/saved_lints_page.dart';
import 'package:linting_tool/theme/colors.dart';
final navKey = GlobalKey<NavigatorState>();
class AdaptiveNav extends StatefulWidget {
const AdaptiveNav({super.key});
@override
State<AdaptiveNav> createState() => _AdaptiveNavState();
}
class _AdaptiveNavState extends State<AdaptiveNav> {
@override
Widget build(BuildContext context) {
final isDesktop = isDisplayLarge(context);
const navigationDestinations = <_Destination>[
_Destination(
textLabel: 'Home',
icon: Icons.home_outlined,
selectedIcon: Icons.home,
destination: HomePage(),
),
_Destination(
textLabel: 'Saved Profiles',
icon: Icons.save_outlined,
selectedIcon: Icons.save,
destination: SavedLintsPage(),
),
_Destination(
textLabel: 'Default Profiles',
icon: Icons.featured_play_list_outlined,
selectedIcon: Icons.featured_play_list,
destination: DefaultLintsPage(),
),
];
const trailing = <String, IconData>{
'About': Icons.info_outline,
};
return _NavView(
extended: isDesktop,
destinations: navigationDestinations,
trailing: trailing,
);
}
}
class _NavView extends StatefulWidget {
const _NavView({
required this.extended,
required this.destinations,
this.trailing = const {},
});
final bool extended;
final List<_Destination> destinations;
final Map<String, IconData> trailing;
@override
_NavViewState createState() => _NavViewState();
}
class _NavViewState extends State<_NavView> {
late final ValueNotifier<bool> _isExtended;
var _selectedIndex = 0;
@override
void initState() {
super.initState();
_isExtended = ValueNotifier<bool>(widget.extended);
}
void _onDestinationSelected(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(
title: Text(
'Flutter Linting Tool',
style: textTheme.titleSmall!.copyWith(
color: textTheme.bodyLarge!.color,
),
),
toolbarHeight: 38.0,
backgroundColor: Colors.white,
systemOverlayStyle: SystemUiOverlayStyle.dark,
),
body: Row(
children: [
LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: constraints.maxHeight,
),
child: IntrinsicHeight(
child: ValueListenableBuilder<bool>(
valueListenable: _isExtended,
builder: (context, value, child) {
var isSmallDisplay = isDisplaySmall(context);
return NavigationRail(
destinations: [
for (var destination in widget.destinations)
NavigationRailDestination(
icon: Icon(destination.icon),
selectedIcon: destination.selectedIcon != null
? Icon(destination.selectedIcon)
: null,
label: Text(destination.textLabel),
),
],
extended: _isExtended.value && !isSmallDisplay,
labelType: NavigationRailLabelType.none,
leading: _NavigationRailHeader(
extended: _isExtended,
),
trailing: _NavigationRailTrailingSection(
trailingDestinations: widget.trailing,
),
selectedIndex: _selectedIndex,
onDestinationSelected: _onDestinationSelected,
);
},
),
),
),
);
},
),
const VerticalDivider(thickness: 1, width: 1),
Expanded(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 1340),
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
switchOutCurve: Curves.easeOut,
switchInCurve: Curves.easeIn,
child: widget.destinations[_selectedIndex].destination,
),
),
),
),
],
),
);
}
}
class _NavigationRailHeader extends StatelessWidget {
const _NavigationRailHeader({
required this.extended,
});
final ValueNotifier<bool?> extended;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
final animation = NavigationRail.extendedAnimation(context);
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Align(
alignment: AlignmentDirectional.centerStart,
widthFactor: animation.value,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 56,
child: Row(
children: [
const SizedBox(width: 6),
InkWell(
borderRadius: const BorderRadius.all(Radius.circular(16)),
onTap: () {
extended.value = !extended.value!;
},
child: Row(
children: [
Transform.rotate(
angle: animation.value * math.pi,
child: const Icon(
Icons.arrow_left,
color: AppColors.white50,
size: 16,
),
),
const FlutterLogo(),
const SizedBox(width: 10),
Align(
alignment: AlignmentDirectional.centerStart,
widthFactor: animation.value,
child: Opacity(
opacity: animation.value,
child: Text(
'Linting Tool',
style: textTheme.bodyLarge!.copyWith(
color: AppColors.white50,
),
),
),
),
SizedBox(width: 18 * animation.value),
],
),
),
],
),
),
const SizedBox(height: 8),
],
),
);
},
);
}
}
class _NavigationRailTrailingSection extends StatelessWidget {
const _NavigationRailTrailingSection({
required this.trailingDestinations,
});
final Map<String, IconData> trailingDestinations;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final textTheme = theme.textTheme;
final navigationRailTheme = theme.navigationRailTheme;
final animation = NavigationRail.extendedAnimation(context);
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Visibility(
maintainAnimation: true,
maintainState: true,
visible: animation.value > 0,
child: Opacity(
opacity: animation.value,
child: Align(
widthFactor: animation.value,
alignment: AlignmentDirectional.centerStart,
child: SizedBox(
height: 485,
width: 256,
child: ListView(
padding: const EdgeInsets.all(12),
physics: const NeverScrollableScrollPhysics(),
children: [
const Divider(
color: AppColors.blue200,
thickness: 0.4,
indent: 14,
endIndent: 16,
),
const SizedBox(height: 8),
for (var item in trailingDestinations.keys)
InkWell(
borderRadius: const BorderRadius.all(
Radius.circular(36),
),
onTap: () => _onTapped(context, item),
child: Column(
children: [
Row(
children: [
const SizedBox(width: 12),
Icon(
trailingDestinations[item],
color: AppColors.blue300,
),
const SizedBox(width: 24),
Text(
item,
style: textTheme.bodyLarge!.copyWith(
color: navigationRailTheme
.unselectedLabelTextStyle!.color,
),
),
const SizedBox(height: 72),
],
),
],
),
),
],
),
),
),
),
);
},
);
}
void _onTapped(BuildContext context, String key) {
switch (key) {
case 'About':
showAboutDialog(
context: context,
applicationIcon: const FlutterLogo(),
children: [
const Text(
'A tool that helps you manage linter rules for your Flutter projects.',
),
],
);
default:
break;
}
}
}
class _Destination {
const _Destination({
required this.destination,
required this.textLabel,
required this.icon,
this.selectedIcon,
});
final String textLabel;
final IconData icon;
final IconData? selectedIcon;
final Widget destination;
}
| samples/experimental/linting_tool/lib/widgets/adaptive_nav.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/widgets/adaptive_nav.dart",
"repo_id": "samples",
"token_count": 6254
} | 1,215 |
# Run with `flutter pub run ffigen --config ffigen.yaml`.
name: PedometerBindings
description: "Bindings for CM pedometers"
language: objc
output: "lib/pedometer_bindings_generated.dart"
compiler-opts:
- "-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks"
- "-mios-version-min=13.0"
exclude-all-by-default: true
functions:
include:
- "wrapCallback"
objc-interfaces:
include:
- "CMPedometer"
- "NSDate"
- "NSDateFormatter"
headers:
entry-points:
- "src/pedometerHelper.h"
# To use this API, you must include the NSMotionUsageDescription key in your app’s Info.plist file
# and provide a usage description string for this key.
# The usage description appears in the prompt that the user must accept the first time the system asks the user to access motion data for your app.
| samples/experimental/pedometer/ffigen.yaml/0 | {
"file_path": "samples/experimental/pedometer/ffigen.yaml",
"repo_id": "samples",
"token_count": 291
} | 1,216 |
// Copyright 2023 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../page_content/pages_flow.dart';
import '../styles.dart';
class LightboxedPanel extends StatefulWidget {
final PageConfig pageConfig;
final List<Widget> content;
final double width = 300;
final Function? onDismiss;
final bool fadeOnDismiss;
final int? autoDismissAfter;
final bool buildButton;
final Color lightBoxBgColor;
final Color cardBgColor;
const LightboxedPanel({
super.key,
required this.pageConfig,
required this.content,
this.onDismiss,
this.fadeOnDismiss = true,
this.autoDismissAfter,
this.buildButton = true,
this.lightBoxBgColor = const Color.fromARGB(200, 255, 255, 255),
this.cardBgColor = Colors.white,
});
@override
State<LightboxedPanel> createState() => _LightboxedPanelState();
}
class _LightboxedPanelState extends State<LightboxedPanel> {
bool _fading = false;
bool _show = true;
late int _fadeOutDur = 200;
@override
void initState() {
_fadeOutDur = widget.fadeOnDismiss ? _fadeOutDur : 0;
if (null != widget.autoDismissAfter) {
_fadeOutDur = 0;
Future.delayed(
Duration(milliseconds: widget.autoDismissAfter!),
handleDismiss,
);
}
super.initState();
}
void handleDismiss() {
if (widget.fadeOnDismiss) {
setState(() {
_fading = true;
});
}
Future.delayed(Duration(milliseconds: _fadeOutDur), () {
setState(() {
if (widget.fadeOnDismiss) {
_show = false;
}
if (null != widget.onDismiss) {
widget.onDismiss!();
}
});
});
}
List<Widget> buttonComponents() {
return [
Column(
children: [
const SizedBox(
height: 8,
),
TextButton(
onPressed: handleDismiss,
style: ButtonStyles.style(),
child: Text(
'OK',
style: TextStyles.bodyStyle()
.copyWith(color: Colors.white, height: 1.2),
),
),
],
),
];
}
@override
Widget build(BuildContext context) {
if (_show) {
return AnimatedOpacity(
opacity: _fading ? 0 : 1,
curve: Curves.easeOut,
duration: Duration(milliseconds: _fadeOutDur),
child: DecoratedBox(
decoration: BoxDecoration(color: widget.lightBoxBgColor),
child: Center(
child: SizedBox(
width: widget.width,
child: DecoratedBox(
decoration: BoxDecoration(
color: widget.cardBgColor,
border: Border.all(
color: const Color.fromARGB(255, 200, 200, 200),
width: 1.0,
),
boxShadow: const [
BoxShadow(
color: Color.fromARGB(30, 0, 0, 0),
offset: Offset.zero,
blurRadius: 4.0,
spreadRadius: 2.0),
],
borderRadius: const BorderRadius.all(Radius.circular(10.0)),
),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: widget.content +
(widget.buildButton ? buttonComponents() : []),
),
),
),
),
),
),
);
}
return const SizedBox(
width: 0,
height: 0,
);
}
}
| samples/experimental/varfont_shader_puzzle/lib/components/lightboxed_panel.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/components/lightboxed_panel.dart",
"repo_id": "samples",
"token_count": 1947
} | 1,217 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../api/api.dart';
import '../app.dart';
import '../widgets/category_chart.dart';
class DashboardPage extends StatelessWidget {
const DashboardPage({super.key});
@override
Widget build(BuildContext context) {
var appState = Provider.of<AppState>(context);
return FutureBuilder<List<Category>>(
future: appState.api!.categories.list(),
builder: (context, futureSnapshot) {
if (!futureSnapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
return StreamBuilder<List<Category>>(
initialData: futureSnapshot.data,
stream: appState.api!.categories.subscribe(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Dashboard(snapshot.data);
},
);
},
);
}
}
class Dashboard extends StatelessWidget {
final List<Category>? categories;
const Dashboard(this.categories, {super.key});
@override
Widget build(BuildContext context) {
var api = Provider.of<AppState>(context).api;
return Scrollbar(
child: GridView(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
childAspectRatio: 2,
maxCrossAxisExtent: 500,
),
children: [
...categories!.map(
(category) => Card(
child: CategoryChart(
category: category,
api: api,
),
),
)
],
),
);
}
}
| samples/experimental/web_dashboard/lib/src/pages/dashboard.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/pages/dashboard.dart",
"repo_id": "samples",
"token_count": 846
} | 1,218 |
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "<YOUR_PROJECT_ID>",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
| samples/experimental/web_dashboard/web/firebase_init.js/0 | {
"file_path": "samples/experimental/web_dashboard/web/firebase_init.js",
"repo_id": "samples",
"token_count": 109
} | 1,219 |
package dev.flutter.formApp.form_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/form_app/android/app/src/main/kotlin/dev/flutter/formApp/form_app/MainActivity.kt/0 | {
"file_path": "samples/form_app/android/app/src/main/kotlin/dev/flutter/formApp/form_app/MainActivity.kt",
"repo_id": "samples",
"token_count": 42
} | 1,220 |
// File normally generated by FlutterFire CLI. This is a stand-in.
// See README.md for details.
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
class DefaultFirebaseOptions {
@Deprecated('Run `flutterfire configure` to re-generate this file')
static FirebaseOptions get currentPlatform {
throw UnimplementedError(
'Generate this file by running `flutterfire configure`. '
'See README.md for details.');
}
}
| samples/game_template/lib/firebase_options.dart/0 | {
"file_path": "samples/game_template/lib/firebase_options.dart",
"repo_id": "samples",
"token_count": 146
} | 1,221 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../audio/audio_controller.dart';
import '../audio/sounds.dart';
import '../games_services/games_services.dart';
import '../settings/settings.dart';
import '../style/palette.dart';
import '../style/responsive_screen.dart';
class MainMenuScreen extends StatelessWidget {
const MainMenuScreen({super.key});
@override
Widget build(BuildContext context) {
final palette = context.watch<Palette>();
final gamesServicesController = context.watch<GamesServicesController?>();
final settingsController = context.watch<SettingsController>();
final audioController = context.watch<AudioController>();
return Scaffold(
backgroundColor: palette.backgroundMain,
body: ResponsiveScreen(
mainAreaProminence: 0.45,
squarishMainArea: Center(
child: Transform.rotate(
angle: -0.1,
child: const Text(
'Flutter Game Template!',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Permanent Marker',
fontSize: 55,
height: 1,
),
),
),
),
rectangularMenuArea: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FilledButton(
onPressed: () {
audioController.playSfx(SfxType.buttonTap);
GoRouter.of(context).go('/play');
},
child: const Text('Play'),
),
_gap,
if (gamesServicesController != null) ...[
_hideUntilReady(
ready: gamesServicesController.signedIn,
child: FilledButton(
onPressed: () => gamesServicesController.showAchievements(),
child: const Text('Achievements'),
),
),
_gap,
_hideUntilReady(
ready: gamesServicesController.signedIn,
child: FilledButton(
onPressed: () => gamesServicesController.showLeaderboard(),
child: const Text('Leaderboard'),
),
),
_gap,
],
FilledButton(
onPressed: () => GoRouter.of(context).push('/settings'),
child: const Text('Settings'),
),
_gap,
Padding(
padding: const EdgeInsets.only(top: 32),
child: ValueListenableBuilder<bool>(
valueListenable: settingsController.muted,
builder: (context, muted, child) {
return IconButton(
onPressed: () => settingsController.toggleMuted(),
icon: Icon(muted ? Icons.volume_off : Icons.volume_up),
);
},
),
),
_gap,
const Text('Music by Mr Smith'),
_gap,
],
),
),
);
}
/// Prevents the game from showing game-services-related menu items
/// until we're sure the player is signed in.
///
/// This normally happens immediately after game start, so players will not
/// see any flash. The exception is folks who decline to use Game Center
/// or Google Play Game Services, or who haven't yet set it up.
Widget _hideUntilReady({required Widget child, required Future<bool> ready}) {
return FutureBuilder<bool>(
future: ready,
builder: (context, snapshot) {
// Use Visibility here so that we have the space for the buttons
// ready.
return Visibility(
visible: snapshot.data ?? false,
maintainState: true,
maintainSize: true,
maintainAnimation: true,
child: child,
);
},
);
}
static const _gap = SizedBox(height: 10);
}
| samples/game_template/lib/src/main_menu/main_menu_screen.dart/0 | {
"file_path": "samples/game_template/lib/src/main_menu/main_menu_screen.dart",
"repo_id": "samples",
"token_count": 1932
} | 1,222 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
/// Shows [message] in a snack bar as long as a [ScaffoldMessengerState]
/// with global key [scaffoldMessengerKey] is anywhere in the widget tree.
void showSnackBar(String message) {
final messenger = scaffoldMessengerKey.currentState;
messenger?.showSnackBar(
SnackBar(content: Text(message)),
);
}
/// Use this when creating [MaterialApp] if you want [showSnackBar] to work.
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
GlobalKey(debugLabel: 'scaffoldMessengerKey');
| samples/game_template/lib/src/style/snack_bar.dart/0 | {
"file_path": "samples/game_template/lib/src/style/snack_bar.dart",
"repo_id": "samples",
"token_count": 222
} | 1,223 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/game_template/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/game_template/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,224 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
import 'item.dart';
import 'page.dart';
const catalogLength = 200;
/// This function emulates a REST API call. You can imagine replacing its
/// contents with an actual network call, keeping the signature the same.
///
/// It will fetch a page of items from [startingIndex].
Future<ItemPage> fetchPage(int startingIndex) async {
// We're emulating the delay inherent to making a network call.
await Future<void>.delayed(const Duration(milliseconds: 500));
// If the [startingIndex] is beyond the bounds of the catalog, an
// empty page will be returned.
if (startingIndex > catalogLength) {
return ItemPage(
items: [],
startingIndex: startingIndex,
hasNext: false,
);
}
// The page of items is generated here.
return ItemPage(
items: List.generate(
min(itemsPerPage, catalogLength - startingIndex),
(index) => Item(
color: Colors.primaries[index % Colors.primaries.length],
name: 'Color #${startingIndex + index}',
price: 50 + (index * 42) % 200,
)),
startingIndex: startingIndex,
// Returns `false` if we've reached the [catalogLength].
hasNext: startingIndex + itemsPerPage < catalogLength,
);
}
| samples/infinite_list/lib/src/api/fetch.dart/0 | {
"file_path": "samples/infinite_list/lib/src/api/fetch.dart",
"repo_id": "samples",
"token_count": 482
} | 1,225 |
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import '../data.dart';
class BookList extends StatelessWidget {
final List<Book> books;
final ValueChanged<Book>? onTap;
const BookList({
required this.books,
this.onTap,
super.key,
});
@override
Widget build(BuildContext context) => ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) => ListTile(
title: Text(
books[index].title,
),
subtitle: Text(
books[index].author.name,
),
onTap: onTap != null ? () => onTap!(books[index]) : null,
),
);
}
| samples/navigation_and_routing/lib/src/widgets/book_list.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/widgets/book_list.dart",
"repo_id": "samples",
"token_count": 335
} | 1,226 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/navigation_and_routing/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/navigation_and_routing/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,227 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let flutterViewController = window.rootViewController as! FlutterViewController
FlutterMethodChannel(name: "methodChannelDemo", binaryMessenger: flutterViewController.binaryMessenger).setMethodCallHandler({
(call: FlutterMethodCall, result: FlutterResult) -> Void in
guard let count = (call.arguments as? NSDictionary)?["count"] as? Int else {
result(FlutterError(code: "INVALID_ARGUMENT", message: "Value of count cannot be null", details: nil))
return
}
switch call.method {
case "increment":
result(count + 1)
case "decrement":
result(count - 1)
default:
result(FlutterMethodNotImplemented)
}
})
FlutterBasicMessageChannel(name: "platformImageDemo", binaryMessenger: flutterViewController.binaryMessenger, codec: FlutterStandardMessageCodec.sharedInstance()).setMessageHandler{
(message: Any?, reply: FlutterReply) -> Void in
if(message as! String == "getImage") {
guard let image = UIImage(named: "eat_new_orleans.jpg") else {
reply(nil)
return
}
reply(FlutterStandardTypedData(bytes: image.jpegData(compressionQuality: 1)!))
}
}
FlutterEventChannel(name: "eventChannelDemo", binaryMessenger: flutterViewController.binaryMessenger).setStreamHandler(AccelerometerStreamHandler())
var petList : [[String:String]] = []
// A FlutterBasicMessageChannel for sending petList to Dart.
let stringCodecChannel = FlutterBasicMessageChannel(name: "stringCodecDemo", binaryMessenger: flutterViewController.binaryMessenger, codec: FlutterStringCodec.sharedInstance())
// Registers a MessageHandler for FlutterBasicMessageChannel to receive pet details.
FlutterBasicMessageChannel(name: "jsonMessageCodecDemo", binaryMessenger: flutterViewController.binaryMessenger, codec: FlutterJSONMessageCodec.sharedInstance())
.setMessageHandler{(message: Any?, reply: FlutterReply) -> Void in
petList.insert(message! as! [String: String], at: 0)
stringCodecChannel.sendMessage(self.convertPetListToJson(petList: petList))
}
// Registers a MessageHandler for FlutterBasicMessageHandler to receive indices of detail records to remove from the petList.
FlutterBasicMessageChannel(name: "binaryCodecDemo", binaryMessenger: flutterViewController.binaryMessenger, codec: FlutterBinaryCodec.sharedInstance()).setMessageHandler{
(message: Any?, reply: FlutterReply) -> Void in
guard let index = Int.init(String.init(data: message! as! Data, encoding: String.Encoding.utf8)!) else {
reply(nil)
return
}
if (index >= 0 && index < petList.count) {
petList.remove(at: index)
reply("Removed Successfully".data(using: .utf8)!)
stringCodecChannel.sendMessage(self.convertPetListToJson(petList: petList))
} else {
reply(nil)
}
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
// Function to convert petList to json string.
func convertPetListToJson(petList: [[String: String]]) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: ["petList": petList], options: .prettyPrinted) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
}
| samples/platform_channels/ios/Runner/AppDelegate.swift/0 | {
"file_path": "samples/platform_channels/ios/Runner/AppDelegate.swift",
"repo_id": "samples",
"token_count": 1814
} | 1,228 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:platform_channels/src/pet_list_message_channel.dart';
/// Demonstrates how to use [BasicMessageChannel] to send a message to platform.
///
/// The widget uses [TextField] and [RadioListTile] to take the [PetDetails.breed] and
/// [PetDetails.petType] from the user respectively.
class AddPetDetails extends StatefulWidget {
const AddPetDetails({super.key});
@override
State<AddPetDetails> createState() => _AddPetDetailsState();
}
class _AddPetDetailsState extends State<AddPetDetails> {
final breedTextController = TextEditingController();
String petType = 'Dog';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add Pet Details'),
actions: [
IconButton(
icon: const Icon(Icons.add),
onPressed: () {
PetListMessageChannel.addPetDetails(
PetDetails(
petType: petType,
breed: breedTextController.text,
),
);
context.pop();
},
)
],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
const SizedBox(
height: 8,
),
TextField(
controller: breedTextController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
filled: true,
hintText: 'Breed of pet',
labelText: 'Breed',
),
),
const SizedBox(
height: 8,
),
RadioListTile<String>(
title: const Text('Dog'),
value: 'Dog',
groupValue: petType,
onChanged: (value) {
setState(() {
petType = value!;
});
},
),
RadioListTile<String>(
title: const Text('Cat'),
value: 'Cat',
groupValue: petType,
onChanged: (value) {
setState(() {
petType = value!;
});
},
),
],
),
),
);
}
}
| samples/platform_channels/lib/src/add_pet_details.dart/0 | {
"file_path": "samples/platform_channels/lib/src/add_pet_details.dart",
"repo_id": "samples",
"token_count": 1285
} | 1,229 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lorem/flutter_lorem.dart';
import 'utils.dart';
import 'widgets.dart';
class NewsTab extends StatefulWidget {
static const title = 'News';
static const androidIcon = Icon(Icons.library_books);
static const iosIcon = Icon(CupertinoIcons.news);
const NewsTab({super.key});
@override
State<NewsTab> createState() => _NewsTabState();
}
class _NewsTabState extends State<NewsTab> {
static const _itemsLength = 20;
late final List<Color> colors;
late final List<String> titles;
late final List<String> contents;
@override
void initState() {
colors = getRandomColors(_itemsLength);
titles = List.generate(_itemsLength, (index) => generateRandomHeadline());
contents =
List.generate(_itemsLength, (index) => lorem(paragraphs: 1, words: 24));
super.initState();
}
Widget _listBuilder(BuildContext context, int index) {
return SafeArea(
top: false,
bottom: false,
child: Card(
elevation: 1.5,
margin: const EdgeInsets.fromLTRB(6, 12, 6, 0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),
child: InkWell(
// Make it splash on Android. It would happen automatically if this
// was a real card but this is just a demo. Skip the splash on iOS.
onTap: defaultTargetPlatform == TargetPlatform.iOS ? null : () {},
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircleAvatar(
backgroundColor: colors[index],
child: Text(
titles[index].substring(0, 1),
style: const TextStyle(color: Colors.white),
),
),
const Padding(padding: EdgeInsets.only(left: 16)),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
titles[index],
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
),
),
const Padding(padding: EdgeInsets.only(top: 8)),
Text(
contents[index],
),
],
),
),
],
),
),
),
),
);
}
// ===========================================================================
// Non-shared code below because this tab uses different scaffolds.
// ===========================================================================
Widget _buildAndroid(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(NewsTab.title),
),
body: ListView.builder(
itemCount: _itemsLength,
itemBuilder: _listBuilder,
),
);
}
Widget _buildIos(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(),
child: ListView.builder(
itemCount: _itemsLength,
itemBuilder: _listBuilder,
),
);
}
@override
Widget build(context) {
return PlatformWidget(
androidBuilder: _buildAndroid,
iosBuilder: _buildIos,
);
}
}
| samples/platform_design/lib/news_tab.dart/0 | {
"file_path": "samples/platform_design/lib/news_tab.dart",
"repo_id": "samples",
"token_count": 1728
} | 1,230 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/provider_counter/android/gradle.properties/0 | {
"file_path": "samples/provider_counter/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,231 |
include: package:analysis_defaults/flutter.yaml
| samples/provider_shopper/analysis_options.yaml/0 | {
"file_path": "samples/provider_shopper/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,232 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:provider_shopper/common/theme.dart';
import 'package:provider_shopper/models/cart.dart';
import 'package:provider_shopper/models/catalog.dart';
import 'package:provider_shopper/screens/cart.dart';
import 'package:provider_shopper/screens/catalog.dart';
import 'package:provider_shopper/screens/login.dart';
import 'package:window_size/window_size.dart';
void main() {
setupWindow();
runApp(const MyApp());
}
const double windowWidth = 400;
const double windowHeight = 800;
void setupWindow() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
WidgetsFlutterBinding.ensureInitialized();
setWindowTitle('Provider Demo');
setWindowMinSize(const Size(windowWidth, windowHeight));
setWindowMaxSize(const Size(windowWidth, windowHeight));
getCurrentScreen().then((screen) {
setWindowFrame(Rect.fromCenter(
center: screen!.frame.center,
width: windowWidth,
height: windowHeight,
));
});
}
}
GoRouter router() {
return GoRouter(
initialLocation: '/login',
routes: [
GoRoute(
path: '/login',
builder: (context, state) => const MyLogin(),
),
GoRoute(
path: '/catalog',
builder: (context, state) => const MyCatalog(),
routes: [
GoRoute(
path: 'cart',
builder: (context, state) => const MyCart(),
),
],
),
],
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// Using MultiProvider is convenient when providing multiple objects.
return MultiProvider(
providers: [
// In this sample app, CatalogModel never changes, so a simple Provider
// is sufficient.
Provider(create: (context) => CatalogModel()),
// CartModel is implemented as a ChangeNotifier, which calls for the use
// of ChangeNotifierProvider. Moreover, CartModel depends
// on CatalogModel, so a ProxyProvider is needed.
ChangeNotifierProxyProvider<CatalogModel, CartModel>(
create: (context) => CartModel(),
update: (context, catalog, cart) {
if (cart == null) throw ArgumentError.notNull('cart');
cart.catalog = catalog;
return cart;
},
),
],
child: MaterialApp.router(
title: 'Provider Demo',
theme: appTheme,
routerConfig: router(),
),
);
}
}
| samples/provider_shopper/lib/main.dart/0 | {
"file_path": "samples/provider_shopper/lib/main.dart",
"repo_id": "samples",
"token_count": 1104
} | 1,233 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider_shopper/main.dart';
void main() {
testWidgets('smoke test', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Navigating through login page.
await tester.tap(find.text('ENTER'));
await tester.pumpAndSettle();
// Check that shopping cart is empty at start.
await tester.tap(find.byIcon(Icons.shopping_cart));
await tester.pumpAndSettle();
expect(find.text('\$0'), findsOneWidget);
// Buy an item.
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.text('ADD').first);
// Check that the shopping cart is not empty anymore.
await tester.tap(find.byIcon(Icons.shopping_cart));
await tester.pumpAndSettle();
expect(find.text('\$0'), findsNothing);
});
}
| samples/provider_shopper/test/widget_test.dart/0 | {
"file_path": "samples/provider_shopper/test/widget_test.dart",
"repo_id": "samples",
"token_count": 380
} | 1,234 |
#version 460 core
#include <flutter/runtime_effect.glsl>
precision mediump float;
uniform vec2 resolution;
out vec4 fragColor;
vec3 flutterBlue = vec3(5, 83, 177) / 255;
vec3 flutterNavy = vec3(4, 43, 89) / 255;
vec3 flutterSky = vec3(2, 125, 253) / 255;
void main() {
vec2 st = FlutterFragCoord().xy / resolution.xy;
vec3 color = vec3(0.0);
vec3 percent = vec3((st.x + st.y) / 2);
color =
mix(mix(flutterSky, flutterBlue, percent * 2),
mix(flutterBlue, flutterNavy, percent * 2 - 1), step(0.5, percent));
fragColor = vec4(color, 1);
}
| samples/simple_shader/shaders/simple.frag/0 | {
"file_path": "samples/simple_shader/shaders/simple.frag",
"repo_id": "samples",
"token_count": 234
} | 1,235 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/simplistic_editor/android/gradle.properties/0 | {
"file_path": "samples/simplistic_editor/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,236 |
import 'dart:math' as math;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
/// Signature for the generator function that produces an [InlineSpan] for replacement
/// in a [TextEditingInlineSpanReplacement].
///
/// This function takes a String which is the matched substring to be replaced and a [TextRange]
/// representing the range in the full string the matched substring originated from.
///
/// This used in [ReplacementTextEditingController] to generate [InlineSpan]s when
/// a match is found for replacement.
typedef InlineSpanGenerator = InlineSpan Function(String, TextRange);
/// Represents one "replacement" to check for, consisting of a [TextRange] to
/// match and a generator [InlineSpanGenerator] function that creates an
/// [InlineSpan] from a matched string.
///
/// The generator function is called for every match of the range found.
///
/// Typically, the generator should return a custom [TextSpan] with unique styling.
///
/// {@tool snippet}
/// In this simple example, the text in the range of 0 to 5 is styled in blue.
///
/// ```dart
/// TextEditingInlineSpanReplacement(
/// TextRange(start: 0, end: 5),
/// (String value, TextRange range) {
/// return TextSpan(text: value, style: TextStyle(color: Colors.blue));
/// },
/// )
/// ```
///
/// See also:
///
/// * [ReplacementTextEditingController], which uses this class to create
/// rich text fields.
/// {@end-tool}
class TextEditingInlineSpanReplacement {
/// Constructs a replacement that replaces matches of the [TextRange] with the
/// output of the [generator].
TextEditingInlineSpanReplacement(this.range, this.generator, this.expand);
/// The [TextRange] to replace.
///
/// Matched ranges are replaced with the output of the [generator] callback.
TextRange range;
/// Function that returns an [InlineSpan] instance for each match of
/// [TextRange].
InlineSpanGenerator generator;
bool expand;
TextEditingInlineSpanReplacement? onDelete(TextEditingDeltaDeletion delta) {
final TextRange deletedRange = delta.deletedRange;
final int deletedLength = delta.textDeleted.length;
if (range.start >= deletedRange.start &&
(range.start < deletedRange.end && range.end > deletedRange.end)) {
return copy(
range: TextRange(
start: deletedRange.end - deletedLength,
end: range.end - deletedLength,
),
);
} else if ((range.start < deletedRange.start &&
range.end > deletedRange.start) &&
range.end <= deletedRange.end) {
return copy(
range: TextRange(
start: range.start,
end: deletedRange.start,
),
);
} else if (range.start < deletedRange.start &&
range.end > deletedRange.end) {
return copy(
range: TextRange(
start: range.start,
end: range.end - deletedLength,
),
);
} else if (range.start >= deletedRange.start &&
range.end <= deletedRange.end) {
return null;
} else if (range.start > deletedRange.start &&
range.start >= deletedRange.end) {
return copy(
range: TextRange(
start: range.start - deletedLength,
end: range.end - deletedLength,
),
);
} else if (range.end <= deletedRange.start &&
range.end < deletedRange.end) {
return copy(
range: TextRange(
start: range.start,
end: range.end,
),
);
}
return null;
}
TextEditingInlineSpanReplacement? onInsertion(
TextEditingDeltaInsertion delta) {
final int insertionOffset = delta.insertionOffset;
final int insertedLength = delta.textInserted.length;
if (range.end == insertionOffset) {
if (expand) {
return copy(
range: TextRange(
start: range.start,
end: range.end + insertedLength,
),
);
} else {
return copy(
range: TextRange(
start: range.start,
end: range.end,
),
);
}
}
if (range.start < insertionOffset && range.end < insertionOffset) {
return copy(
range: TextRange(
start: range.start,
end: range.end,
),
);
} else if (range.start >= insertionOffset && range.end > insertionOffset) {
return copy(
range: TextRange(
start: range.start + insertedLength,
end: range.end + insertedLength,
),
);
} else if (range.start < insertionOffset && range.end > insertionOffset) {
return copy(
range: TextRange(
start: range.start,
end: range.end + insertedLength,
),
);
}
return null;
}
List<TextEditingInlineSpanReplacement>? onReplacement(
TextEditingDeltaReplacement delta) {
final TextRange replacedRange = delta.replacedRange;
final bool replacementShortenedText =
delta.replacementText.length < delta.textReplaced.length;
final bool replacementLengthenedText =
delta.replacementText.length > delta.textReplaced.length;
final bool replacementEqualLength =
delta.replacementText.length == delta.textReplaced.length;
final int changedOffset = replacementShortenedText
? delta.textReplaced.length - delta.replacementText.length
: delta.replacementText.length - delta.textReplaced.length;
if (range.start >= replacedRange.start &&
(range.start < replacedRange.end && range.end > replacedRange.end)) {
if (replacementShortenedText) {
return [
copy(
range: TextRange(
start: replacedRange.end - changedOffset,
end: range.end - changedOffset,
),
),
];
} else if (replacementLengthenedText) {
return [
copy(
range: TextRange(
start: replacedRange.end + changedOffset,
end: range.end + changedOffset,
),
),
];
} else if (replacementEqualLength) {
return [
copy(
range: TextRange(
start: replacedRange.end,
end: range.end,
),
),
];
}
} else if ((range.start < replacedRange.start &&
range.end > replacedRange.start) &&
range.end <= replacedRange.end) {
return [
copy(
range: TextRange(
start: range.start,
end: replacedRange.start,
),
),
];
} else if (range.start < replacedRange.start &&
range.end > replacedRange.end) {
if (replacementShortenedText) {
return [
copy(
range: TextRange(
start: range.start,
end: replacedRange.start,
),
),
copy(
range: TextRange(
start: replacedRange.end - changedOffset,
end: range.end - changedOffset,
),
),
];
} else if (replacementLengthenedText) {
return [
copy(
range: TextRange(
start: range.start,
end: replacedRange.start,
),
),
copy(
range: TextRange(
start: replacedRange.end + changedOffset,
end: range.end + changedOffset,
),
),
];
} else if (replacementEqualLength) {
return [
copy(
range: TextRange(
start: range.start,
end: replacedRange.start,
),
),
copy(
range: TextRange(
start: replacedRange.end,
end: range.end,
),
),
];
}
} else if (range.start >= replacedRange.start &&
range.end <= replacedRange.end) {
// remove attribute.
return null;
} else if (range.start > replacedRange.start &&
range.start >= replacedRange.end) {
if (replacementShortenedText) {
return [
copy(
range: TextRange(
start: range.start - changedOffset,
end: range.end - changedOffset,
),
),
];
} else if (replacementLengthenedText) {
return [
copy(
range: TextRange(
start: range.start + changedOffset,
end: range.end + changedOffset,
),
),
];
} else if (replacementEqualLength) {
return [this];
}
} else if (range.end <= replacedRange.start &&
range.end < replacedRange.end) {
return [
copy(
range: TextRange(
start: range.start,
end: range.end,
),
),
];
}
return null;
}
TextEditingInlineSpanReplacement? onNonTextUpdate(
TextEditingDeltaNonTextUpdate delta) {
if (range.isCollapsed) {
if (range.start != delta.selection.start &&
range.end != delta.selection.end) {
return null;
}
}
return this;
}
List<TextEditingInlineSpanReplacement>? removeRange(TextRange removalRange) {
if (range.start >= removalRange.start &&
(range.start < removalRange.end && range.end > removalRange.end)) {
return [
copy(
range: TextRange(
start: removalRange.end,
end: range.end,
),
),
];
} else if ((range.start < removalRange.start &&
range.end > removalRange.start) &&
range.end <= removalRange.end) {
return [
copy(
range: TextRange(
start: range.start,
end: removalRange.start,
),
),
];
} else if (range.start < removalRange.start &&
range.end > removalRange.end) {
return [
copy(
range: TextRange(
start: range.start,
end: removalRange.start,
),
expand: removalRange.isCollapsed ? false : expand,
),
copy(
range: TextRange(
start: removalRange.end,
end: range.end,
),
),
];
} else if (range.start >= removalRange.start &&
range.end <= removalRange.end) {
return null;
} else if (range.start > removalRange.start &&
range.start >= removalRange.end) {
return [this];
} else if (range.end <= removalRange.start &&
range.end < removalRange.end) {
return [this];
} else if (removalRange.isCollapsed && range.end == removalRange.start) {
return [this];
}
return null;
}
/// Creates a new replacement with all properties copied except for range, which
/// is updated to the specified value.
TextEditingInlineSpanReplacement copy({TextRange? range, bool? expand}) {
return TextEditingInlineSpanReplacement(
range ?? this.range, generator, expand ?? this.expand);
}
@override
String toString() {
return 'TextEditingInlineSpanReplacement { range: $range, generator: $generator }';
}
}
/// A [TextEditingController] that contains a list of [TextEditingInlineSpanReplacement]s that
/// insert custom [InlineSpan]s in place of matched [TextRange]s.
///
/// This controller must be passed [TextEditingInlineSpanReplacement], each of which contains
/// a [TextRange] to match with and a generator function to generate an [InlineSpan] to replace
/// the matched [TextRange]s with based on the matched string.
///
/// See [TextEditingInlineSpanReplacement] for example replacements to provide this class with.
class ReplacementTextEditingController extends TextEditingController {
/// Constructs a controller with optional text that handles the provided list of replacements.
ReplacementTextEditingController({
super.text,
List<TextEditingInlineSpanReplacement>? replacements,
this.composingRegionReplaceable = true,
}) : replacements = replacements ?? [];
/// Creates a controller for an editable text field from an initial [TextEditingValue].
///
/// This constructor treats a null [value] argument as if it were [TextEditingValue.empty].
ReplacementTextEditingController.fromValue(super.value,
{List<TextEditingInlineSpanReplacement>? replacements,
this.composingRegionReplaceable = true})
: super.fromValue();
/// The [TextEditingInlineSpanReplacement]s that are evaluated on the editing value.
///
/// Each replacement is evaluated in order from first to last. If multiple replacement
/// [TextRange]s match against the same range of text,
List<TextEditingInlineSpanReplacement>? replacements;
/// If composing regions should be matched against for replacements.
///
/// When false, composing regions are invalidated from being matched against.
///
/// When true, composing regions are attempted to be applied after ranges are
/// matched and replacements made. This means that composing region may sometimes
/// fail to display if the text in the composing region matches against of the
/// replacement ranges.
final bool composingRegionReplaceable;
void applyReplacement(TextEditingInlineSpanReplacement replacement) {
if (replacements == null) {
replacements = [];
replacements!.add(replacement);
} else {
replacements!.add(replacement);
}
}
/// Update replacement ranges based on [TextEditingDelta]'s coming from a
/// [DeltaTextInputClient]'s.
///
/// On a insertion, the replacements that ranges fall inclusively
/// within the range of the insertion, should be updated to take into account
/// the insertion that happened within the replacement range. i.e. we expand
/// the range.
///
/// On a insertion, the replacements that ranges fall after the
/// range of the insertion, should be updated to take into account the insertion
/// that occurred and the offset it created as a result.
///
/// On a insertion, the replacements that ranges fall before
/// the range of the insertion, should be skipped and not updated as their values
/// are not offset by the insertion.
///
/// On a insertion, if a replacement range front edge is touched by
/// the insertion, the range should be updated with the insertion offset. i.e.
/// the replacement range is pushed forward.
///
/// On a insertion, if a replacement range back edge is touched by
/// the insertion offset, nothing should be done. i.e. do not expand the range.
///
/// On a deletion, the replacements that ranges fall inclusively
/// within the range of the deletion, should be updated to take into account
/// the deletion that happened within the replacement range. i.e. we contract the range.
///
/// On a deletion, the replacement ranges that fall after the
/// ranges of deletion, should be updated to take into account the deletion
/// that occurred and the offset it created as a result.
///
/// On a deletion, the replacement ranges that fall before the
/// ranges of deletion, should be skipped and not updated as their values are
/// not offset by the deletion.
///
/// On a replacement, the replacements that ranges fall inclusively
/// within the range of the replaced range, should be updated to take into account
/// that the replaced range should be un-styled. i.e. we split the replacement ranges
/// into two.
///
/// On a replacement, the replacement ranges that fall after the
/// ranges of the replacement, should be updated to take into account the replacement
/// that occurred and the offset it created as a result.
///
/// On a replacement, the replacement ranges that fall before the
/// ranges of replacement, should be skipped and not updated as their values are
/// not offset by the replacement.
void syncReplacementRanges(TextEditingDelta delta) {
if (replacements == null) return;
if (text.isEmpty) replacements!.clear();
List<TextEditingInlineSpanReplacement> toRemove = [];
List<TextEditingInlineSpanReplacement> toAdd = [];
for (int i = 0; i < replacements!.length; i++) {
late final TextEditingInlineSpanReplacement? mutatedReplacement;
if (delta is TextEditingDeltaInsertion) {
mutatedReplacement = replacements![i].onInsertion(delta);
} else if (delta is TextEditingDeltaDeletion) {
mutatedReplacement = replacements![i].onDelete(delta);
} else if (delta is TextEditingDeltaReplacement) {
List<TextEditingInlineSpanReplacement>? newReplacements;
newReplacements = replacements![i].onReplacement(delta);
if (newReplacements != null) {
if (newReplacements.length == 1) {
mutatedReplacement = newReplacements[0];
} else {
mutatedReplacement = null;
toAdd.addAll(newReplacements);
}
} else {
mutatedReplacement = null;
}
} else if (delta is TextEditingDeltaNonTextUpdate) {
mutatedReplacement = replacements![i].onNonTextUpdate(delta);
}
if (mutatedReplacement == null) {
toRemove.add(replacements![i]);
} else {
replacements![i] = mutatedReplacement;
}
}
for (final TextEditingInlineSpanReplacement replacementToRemove
in toRemove) {
replacements!.remove(replacementToRemove);
}
replacements!.addAll(toAdd);
}
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
required bool withComposing,
}) {
assert(!value.composing.isValid ||
!withComposing ||
value.isComposingRangeValid);
// Keep a mapping of TextRanges to the InlineSpan to replace it with.
final Map<TextRange, InlineSpan> rangeSpanMapping =
<TextRange, InlineSpan>{};
// Iterate through TextEditingInlineSpanReplacements, handling overlapping
// replacements and mapping them towards a generated InlineSpan.
if (replacements != null) {
for (final TextEditingInlineSpanReplacement replacement
in replacements!) {
_addToMappingWithOverlaps(
replacement.generator,
TextRange(start: replacement.range.start, end: replacement.range.end),
rangeSpanMapping,
value.text,
);
}
}
// If the composing range is out of range for the current text, ignore it to
// preserve the tree integrity, otherwise in release mode a RangeError will
// be thrown and this EditableText will be built with a broken subtree.
//
// Add composing region as a replacement to a TextSpan with underline.
if (composingRegionReplaceable &&
value.isComposingRangeValid &&
withComposing) {
_addToMappingWithOverlaps((value, range) {
final TextStyle composingStyle = style != null
? style.merge(const TextStyle(decoration: TextDecoration.underline))
: const TextStyle(decoration: TextDecoration.underline);
return TextSpan(
style: composingStyle,
text: value,
);
}, value.composing, rangeSpanMapping, value.text);
}
// Sort the matches by start index. Since no overlapping exists, this is safe.
final List<TextRange> sortedRanges = rangeSpanMapping.keys.toList();
sortedRanges.sort((a, b) => a.start.compareTo(b.start));
// Create TextSpans for non-replaced text ranges and insert the replacements spans
// for any ranges that are marked to be replaced.
final List<InlineSpan> spans = <InlineSpan>[];
int previousEndIndex = 0;
for (final TextRange range in sortedRanges) {
if (range.start > previousEndIndex) {
spans.add(TextSpan(
text: value.text.substring(previousEndIndex, range.start)));
}
spans.add(rangeSpanMapping[range]!);
previousEndIndex = range.end;
}
// Add any trailing text as a regular TextSpan.
if (previousEndIndex < value.text.length) {
spans.add(TextSpan(
text: value.text.substring(previousEndIndex, value.text.length)));
}
return TextSpan(
style: style,
children: spans,
);
}
static void _addToMappingWithOverlaps(
InlineSpanGenerator generator,
TextRange matchedRange,
Map<TextRange, InlineSpan> rangeSpanMapping,
String text) {
// In some cases we should allow for overlap.
// For example in the case of two TextSpans matching the same range for replacement,
// we should try to merge the styles into one TextStyle and build a new TextSpan.
bool overlap = false;
List<TextRange> overlapRanges = <TextRange>[];
for (final TextRange range in rangeSpanMapping.keys) {
if (math.max(matchedRange.start, range.start) <=
math.min(matchedRange.end, range.end)) {
overlap = true;
overlapRanges.add(range);
}
}
final List<List<dynamic>> overlappingTriples = <List<dynamic>>[];
if (overlap) {
overlappingTriples.add(<dynamic>[
matchedRange.start,
matchedRange.end,
generator(matchedRange.textInside(text), matchedRange).style
]);
for (final TextRange overlappingRange in overlapRanges) {
overlappingTriples.add(<dynamic>[
overlappingRange.start,
overlappingRange.end,
rangeSpanMapping[overlappingRange]!.style
]);
rangeSpanMapping.remove(overlappingRange);
}
final List<dynamic> toRemoveRangesThatHaveBeenMerged = <dynamic>[];
final List<dynamic> toAddRangesThatHaveBeenMerged = <dynamic>[];
for (int i = 0; i < overlappingTriples.length; i++) {
bool didOverlap = false;
List<dynamic> tripleA = overlappingTriples[i];
if (toRemoveRangesThatHaveBeenMerged.contains(tripleA)) continue;
for (int j = i + 1; j < overlappingTriples.length; j++) {
final List<dynamic> tripleB = overlappingTriples[j];
if (math.max(tripleA[0] as int, tripleB[0] as int) <=
math.min(tripleA[1] as int, tripleB[1] as int) &&
tripleA[2] == tripleB[2]) {
toRemoveRangesThatHaveBeenMerged
.addAll(<dynamic>[tripleA, tripleB]);
tripleA = <dynamic>[
math.min(tripleA[0] as int, tripleB[0] as int),
math.max(tripleA[1] as int, tripleB[1] as int),
tripleA[2],
];
didOverlap = true;
}
}
if (didOverlap &&
!toAddRangesThatHaveBeenMerged.contains(tripleA) &&
!toRemoveRangesThatHaveBeenMerged.contains(tripleA)) {
toAddRangesThatHaveBeenMerged.add(tripleA);
}
}
for (var tripleToRemove in toRemoveRangesThatHaveBeenMerged) {
overlappingTriples.remove(tripleToRemove);
}
for (var tripleToAdd in toAddRangesThatHaveBeenMerged) {
overlappingTriples.add(tripleToAdd as List<dynamic>);
}
List<int> endPoints = <int>[];
for (List<dynamic> triple in overlappingTriples) {
Set<int> ends = <int>{};
ends.add(triple[0] as int);
ends.add(triple[1] as int);
endPoints.addAll(ends.toList());
}
endPoints.sort();
Map<int, Set<TextStyle>> start = <int, Set<TextStyle>>{};
Map<int, Set<TextStyle>> end = <int, Set<TextStyle>>{};
for (final int e in endPoints) {
start[e] = <TextStyle>{};
end[e] = <TextStyle>{};
}
for (List<dynamic> triple in overlappingTriples) {
start[triple[0]]!.add(triple[2] as TextStyle);
end[triple[1]]!.add(triple[2] as TextStyle);
}
Set<TextStyle> styles = <TextStyle>{};
List<int> otherEndPoints =
endPoints.getRange(1, endPoints.length).toList();
for (int i = 0; i < endPoints.length - 1; i++) {
styles = styles.difference(end[endPoints[i]]!);
styles.addAll(start[endPoints[i]]!);
TextStyle? mergedStyles;
final TextRange uniqueRange =
TextRange(start: endPoints[i], end: otherEndPoints[i]);
for (final TextStyle style in styles) {
if (mergedStyles == null) {
mergedStyles = style;
} else {
mergedStyles = mergedStyles.merge(style);
}
}
rangeSpanMapping[uniqueRange] =
TextSpan(text: uniqueRange.textInside(text), style: mergedStyles);
}
}
if (!overlap) {
rangeSpanMapping[matchedRange] =
generator(matchedRange.textInside(text), matchedRange);
}
// Clean up collapsed ranges that we don't need to style.
final List<TextRange> toRemove = <TextRange>[];
for (final TextRange range in rangeSpanMapping.keys) {
if (range.isCollapsed) toRemove.add(range);
}
for (final TextRange range in toRemove) {
rangeSpanMapping.remove(range);
}
}
void disableExpand(TextStyle style) {
final List<TextEditingInlineSpanReplacement> toRemove = [];
final List<TextEditingInlineSpanReplacement> toAdd = [];
for (final TextEditingInlineSpanReplacement replacement in replacements!) {
if (replacement.range.end == selection.start) {
TextStyle? replacementStyle = (replacement.generator(
'', const TextRange.collapsed(0)) as TextSpan)
.style;
if (replacementStyle! == style) {
toRemove.add(replacement);
toAdd.add(replacement.copy(expand: false));
}
}
}
for (final TextEditingInlineSpanReplacement replacementToRemove
in toRemove) {
replacements!.remove(replacementToRemove);
}
for (final TextEditingInlineSpanReplacement replacementWithExpandDisabled
in toAdd) {
replacements!.add(replacementWithExpandDisabled);
}
}
List<TextStyle> getReplacementsAtSelection(TextSelection selection) {
// [left replacement]|[right replacement], only left replacement should be
// reported.
//
// Selection of a range of replacements should only enable the replacements
// common to the selection. If there are no common replacements then none
// should be enabled.
final List<TextStyle> stylesAtSelection = <TextStyle>[];
for (final TextEditingInlineSpanReplacement replacement in replacements!) {
if (selection.isCollapsed) {
if (math.max(replacement.range.start, selection.start) <=
math.min(replacement.range.end, selection.end)) {
if (selection.end != replacement.range.start) {
if (selection.start == replacement.range.end) {
if (replacement.expand) {
stylesAtSelection
.add(replacement.generator('', replacement.range).style!);
}
} else {
stylesAtSelection
.add(replacement.generator('', replacement.range).style!);
}
}
}
} else {
if (math.max(replacement.range.start, selection.start) <=
math.min(replacement.range.end, selection.end)) {
if (replacement.range.start <= selection.start &&
replacement.range.end >= selection.end) {
stylesAtSelection
.add(replacement.generator('', replacement.range).style!);
}
}
}
}
return stylesAtSelection;
}
void removeReplacementsAtRange(TextRange removalRange, TextStyle? attribute) {
final List<TextEditingInlineSpanReplacement> toRemove = [];
final List<TextEditingInlineSpanReplacement> toAdd = [];
for (int i = 0; i < replacements!.length; i++) {
TextEditingInlineSpanReplacement replacement = replacements![i];
InlineSpan replacementSpan =
replacement.generator('', const TextRange.collapsed(0));
TextStyle? replacementStyle = replacementSpan.style;
late final TextEditingInlineSpanReplacement? mutatedReplacement;
if ((math.max(replacement.range.start, removalRange.start) <=
math.min(replacement.range.end, removalRange.end)) &&
replacementStyle != null) {
if (replacementStyle == attribute!) {
List<TextEditingInlineSpanReplacement>? newReplacements =
replacement.removeRange(removalRange);
if (newReplacements != null) {
if (newReplacements.length == 1) {
mutatedReplacement = newReplacements[0];
} else {
mutatedReplacement = null;
toAdd.addAll(newReplacements);
}
} else {
mutatedReplacement = null;
}
if (mutatedReplacement == null) {
toRemove.add(replacements![i]);
} else {
replacements![i] = mutatedReplacement;
}
}
}
}
for (TextEditingInlineSpanReplacement replacementToAdd in toAdd) {
replacements!.add(replacementToAdd);
}
for (TextEditingInlineSpanReplacement replacementToRemove in toRemove) {
replacements!.remove(replacementToRemove);
}
}
}
| samples/simplistic_editor/lib/replacements.dart/0 | {
"file_path": "samples/simplistic_editor/lib/replacements.dart",
"repo_id": "samples",
"token_count": 11583
} | 1,237 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/simplistic_editor/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/simplistic_editor/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,238 |
name: testing_app
description: A sample that shows testing in Flutter.
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.3
provider: ^6.0.2
go_router: ">=10.0.0 <14.0.0"
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
test: ^1.16.8
flutter:
uses-material-design: true
| samples/testing_app/pubspec.yaml/0 | {
"file_path": "samples/testing_app/pubspec.yaml",
"repo_id": "samples",
"token_count": 190
} | 1,239 |
function ci_projects () {
local channel="$1"
shift
local arr=("$@")
for PROJECT_NAME in "${arr[@]}"
do
echo "== Testing '${PROJECT_NAME}' on Flutter's $channel channel =="
pushd "${PROJECT_NAME}"
# Grab packages.
flutter pub get
# Run the analyzer to find any static analysis issues.
dart analyze --fatal-infos --fatal-warnings
# Run the formatter on all the dart files to make sure everything's linted.
dart format --output none --set-exit-if-changed .
# Run the actual tests.
if [ -d "test" ]
then
if grep -q "flutter:" "pubspec.yaml"; then
flutter test
else
# If the project is not a Flutter project, use the Dart CLI.
dart test
fi
fi
popd
done
}
| samples/tool/flutter_ci_script_shared.sh/0 | {
"file_path": "samples/tool/flutter_ci_script_shared.sh",
"repo_id": "samples",
"token_count": 405
} | 1,240 |
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:veggieseasons/data/veggie.dart';
class LocalVeggieProvider {
static List<Veggie> veggies = [
Veggie(
id: 1,
name: 'Apples',
imageAssetPath: 'assets/images/apple.jpg',
category: VeggieCategory.fruit,
shortDescription: 'Green or red, they\'re generally round and tasty.',
accentColor: const Color(0x40de8c66),
seasons: [Season.winter, Season.spring, Season.summer, Season.autumn],
vitaminAPercentage: 2,
vitaminCPercentage: 8,
servingSize: 'One large apple',
caloriesPerServing: 130,
trivia: const [
Trivia(
'A peck of apples (that\'s a real unit of mesaurement!) weighs approximately how many pounds?',
[
'10 pounds',
'20 pounds',
'30 pounds',
],
0,
),
Trivia(
'Which of these is an actual variety of apples?',
[
'Dancing Turkey',
'Winter Banana',
'Red Sloth',
],
1,
),
Trivia(
'In Greek mythology, Paris gives a golden apple marked "To the Fairest" to a goddess. Which one?',
[
'Hera',
'Athena',
'Aphrodite',
],
2,
),
Trivia(
'Apples in the supermarket can be up to how old?',
[
'1 week',
'1 month',
'1 year',
],
2,
),
Trivia(
'How long does it take a typical apple tree to produce its first fruit?',
[
'One to two years',
'Four or five years',
'Eight to ten years',
],
1,
),
Trivia(
'Archaeological evidence of humans eating apples dates back how far?',
[
'500 C.E.',
'2000 B.C.E.',
'6500 B.C.E.',
],
2,
),
Trivia(
'What are the seed pockets inside an apple called?',
[
'Tarsals',
'Carpels',
'Sacs',
],
1,
),
],
),
Veggie(
id: 2,
name: 'Artichokes',
imageAssetPath: 'assets/images/artichoke.jpg',
category: VeggieCategory.flower,
shortDescription: 'The armadillo of vegetables.',
accentColor: const Color(0x408ea26d),
seasons: [Season.spring, Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 25,
servingSize: '1 medium artichoke',
caloriesPerServing: 60,
trivia: const [
Trivia(
'Artichokes are which part of the plant?',
[
'Flower bud',
'Root',
'Seed',
],
0,
),
Trivia(
'"Jerusalem artichoke" is another term for which vegetable?',
[
'Potato',
'Cabbage',
'Sunchoke',
],
2,
),
Trivia(
'Which city claims to be The Artichoke Capital of the World?',
[
'Castroville, California',
'Galveston, Texas',
'London, England',
],
0,
),
Trivia(
'Artichokes are technically which type of plant?',
[
'Thistle',
'Azalea',
'Tulip',
],
0,
),
],
),
Veggie(
id: 3,
name: 'Asparagus',
imageAssetPath: 'assets/images/asparagus.jpg',
category: VeggieCategory.fern,
shortDescription: 'It\'s been used a food and medicine for millenia.',
accentColor: const Color(0x408cb437),
seasons: [Season.spring],
vitaminAPercentage: 10,
vitaminCPercentage: 15,
servingSize: '5 spears',
caloriesPerServing: 20,
trivia: const [
Trivia(
'The nodules at the tip of an asparagus spear are actually which part of the plant?',
[
'Seeds',
'Leaves',
'Potective scales',
],
1,
),
Trivia(
'How is white asparagus made?',
[
'It\'s watered with milk',
'It\'s a different species',
'It\'s grown in the shade',
],
2,
),
Trivia(
'Asapragus spears have been observed growing how many inches in a single day?',
[
'1',
'3',
'6',
],
2,
),
Trivia(
'To which flower is asparagus related?',
[
'Lily',
'Rose',
'Whole wheat',
],
0,
),
],
),
Veggie(
id: 4,
name: 'Avocado',
imageAssetPath: 'assets/images/avocado.jpg',
category: VeggieCategory.stealthFruit,
shortDescription: 'One of the oiliest, richest fruits money can buy.',
accentColor: const Color(0x40b0ba59),
seasons: [Season.winter, Season.spring, Season.summer],
vitaminAPercentage: 0,
vitaminCPercentage: 4,
servingSize: '1/5 medium avocado',
caloriesPerServing: 50,
trivia: const [
Trivia(
'What\'s the most popular variety of avocado?',
[
'Stevenson',
'Hass',
'Juicy Lucy',
],
1,
),
Trivia(
'The word avocado derives from "ahuacatl," found in which civilization?',
[
'Aztec',
'Incan',
'Sumerian',
],
0,
),
Trivia(
'What percentage of an avocado is nutritional fat?',
[
'10',
'25',
'50',
],
1,
),
Trivia(
'The first evidence of avocado consumption by humans dates back to what year?',
[
'2,000 B.C.',
'6,000 B.C.',
'10,000 B.C.',
],
2,
),
],
),
Veggie(
id: 5,
name: 'Blackberries',
imageAssetPath: 'assets/images/blackberry.jpg',
category: VeggieCategory.berry,
shortDescription: 'Find them on backroads and fences in the Northwest.',
accentColor: const Color(0x409d5adb),
seasons: [Season.summer],
vitaminAPercentage: 6,
vitaminCPercentage: 4,
servingSize: '1 cup',
caloriesPerServing: 62,
trivia: const [
Trivia(
'What color are unripe blackberries?',
[
'Red',
'White',
'Brown',
],
0,
),
Trivia(
'The blackberry is the official fruit of which American state?',
[
'Washington',
'Colorado',
'Alabama',
],
2,
),
Trivia(
'How many varieties of blackberries are known to exist?',
[
'500',
'1000',
'2000',
],
2,
),
],
),
Veggie(
id: 6,
name: 'Cantaloupe',
imageAssetPath: 'assets/images/cantaloupe.jpg',
category: VeggieCategory.melon,
shortDescription: 'A fruit so tasty there\'s a utensil just for it.',
accentColor: const Color(0x40f6bd56),
seasons: [Season.summer],
vitaminAPercentage: 120,
vitaminCPercentage: 80,
servingSize: '1/4 medium cantaloupe',
caloriesPerServing: 50,
trivia: const [
Trivia(
'Which of these is another name for cantaloupe?',
[
'Muskmelon',
'Crenshaw melon',
'Rindfruit',
],
0,
),
Trivia(
'The word "cantaloupe" is a reference to what?',
[
'The Latin word for a ring of seeds',
'The gardens of a castle in Italy',
'An aphid species that feeds on cantaloupe leaves',
],
1,
),
Trivia(
'Cantaloupes grow on what kind of plant?',
[
'Tree',
'Shrub',
'Vine',
],
2,
),
Trivia(
'The most expensive melons in Japan can sell for up to how much?',
[
'\$100',
'\$1,000',
'\$10,000',
],
2,
),
],
),
Veggie(
id: 7,
name: 'Cauliflower',
imageAssetPath: 'assets/images/cauliflower.jpg',
category: VeggieCategory.cruciferous,
shortDescription: 'Looks like white broccoli and explodes when cut.',
accentColor: const Color(0x40c891a8),
seasons: [Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 100,
servingSize: '1/6 medium head',
caloriesPerServing: 25,
trivia: const [
Trivia(
'The quote "Cauliflower is nothing but cabbage with a college education" is attributed to whom?',
[
'Cesar Romero',
'Mark Twain',
'Lucille Ball',
],
1,
),
Trivia(
'The edible head of a cauliflower plant is sometimes called what?',
[
'The curd',
'The cow',
'The cudgel',
],
0,
),
Trivia(
'Cauliflower is related closest to which of these other plants?',
[
'Mustard greens',
'Apples',
'Potatoes',
],
0,
),
Trivia(
'Cauliflower\'s green spiral-shaped cousin is known as what?',
[
'Romesco',
'Brittany cabbage',
'Muscle sprouts',
],
0,
),
Trivia(
'Green cauliflower is sometimes called what?',
[
'Broccoflower',
'Avocadoflower',
'Gross',
],
0,
),
],
),
Veggie(
id: 8,
name: 'Endive',
imageAssetPath: 'assets/images/endive.jpg',
category: VeggieCategory.leafy,
shortDescription: 'It\'s basically the veal of lettuce.',
accentColor: const Color(0x40c5be53),
seasons: [Season.winter, Season.spring, Season.autumn],
vitaminAPercentage: 10,
vitaminCPercentage: 2,
servingSize: '1/2 cup, chopped',
caloriesPerServing: 4,
trivia: const [
Trivia(
'What\'s another name for Belgian endive?',
[
'Radicchio',
'St. Paul\'s lettuce',
'Witloof chicory',
],
2,
),
Trivia(
'How does endive propagate itself?',
[
'By seed',
'By rhizome',
'By packing up and moving to Des Moines',
],
0,
),
Trivia(
'Some farmers cover their endive with shade to reduce what?',
[
'Size',
'Toughness',
'Bitterness',
],
2,
),
],
),
Veggie(
id: 9,
name: 'Figs',
imageAssetPath: 'assets/images/fig.jpg',
category: VeggieCategory.fruit,
shortDescription: 'Delicious when sliced and wrapped in prosciutto.',
accentColor: const Color(0x40aa6d7c),
seasons: [Season.summer, Season.autumn],
vitaminAPercentage: 2,
vitaminCPercentage: 2,
servingSize: '1 large fig',
caloriesPerServing: 50,
trivia: const [
Trivia(
'Which of these isn\'t a variety of figs?',
[
'Brown Turkey',
'Green Ischia',
'Red Racer',
],
2,
),
Trivia(
'A fig\'s natural sugar content is around what?',
[
'25%',
'50%',
'75%',
],
1,
),
Trivia(
'How much sun should be used to ripen figs?',
[
'Shade',
'Partial shade',
'Full sun',
],
2,
),
],
),
Veggie(
id: 10,
name: 'Grapes',
imageAssetPath: 'assets/images/grape.jpg',
category: VeggieCategory.berry,
shortDescription: 'Couldn\'t have wine without them.',
accentColor: const Color(0x40ac708a),
seasons: [Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 2,
servingSize: '3/4 cup',
caloriesPerServing: 90,
trivia: const [
Trivia(
'How long ago were grapes introduced to the Americas?',
[
'100 years',
'200 years',
'300 years',
],
2,
),
Trivia(
'Which of these is not an actual color of grapes?',
[
'Pink',
'Yellow',
'Brown',
],
2,
),
Trivia(
'About how many millions of tons of grapes are produced each year?',
[
'40',
'80',
'120',
],
1,
),
Trivia(
'There are about how many known varieties of grapes?',
[
'2,000',
'4,000',
'8,000',
],
2,
),
],
),
Veggie(
id: 11,
name: 'Green Pepper',
imageAssetPath: 'assets/images/green_bell_pepper.jpg',
category: VeggieCategory.stealthFruit,
shortDescription: 'Pleasantly bitter, like a sad movie.',
accentColor: const Color(0x408eb332),
seasons: [Season.summer],
vitaminAPercentage: 4,
vitaminCPercentage: 190,
servingSize: '1 medium pepper',
caloriesPerServing: 25,
trivia: const [
Trivia(
'What\'s the Australian term for a bell pepper?',
[
'Capsicum',
'Ringer',
'John Dobbins',
],
0,
),
Trivia(
'How are green peppers produced?',
[
'They\'re picked before ripening',
'They\'re grown in the shade',
'They\'re a distinct species',
],
0,
),
Trivia(
'How quickly can a green pepper grow from seed to harvest?',
[
'10 weeks',
'20 weeks',
'30 weeks',
],
0,
),
],
),
Veggie(
id: 12,
name: 'Habanero',
imageAssetPath: 'assets/images/habanero.jpg',
category: VeggieCategory.stealthFruit,
shortDescription: 'Delicious... in extremely small quantities.',
accentColor: const Color(0x40ff7a01),
seasons: [Season.summer, Season.autumn],
vitaminAPercentage: 9,
vitaminCPercentage: 100,
servingSize: '1 pepper',
caloriesPerServing: 20,
trivia: const [
Trivia(
'How high can habaneros rate on the Scoville scale?',
[
'200,000 units',
'600,000 units',
'1,000,000 units',
],
1,
),
Trivia(
'Which of these is a pepper known to be hotter than the habanero?',
[
'Serrano pepper',
'Hatch chile',
'Pepper X',
],
2,
),
Trivia(
'Which of these isn\'t a variety of habaneros?',
[
'White giant',
'Condor\'s beak',
'Saucy tyrant',
],
2,
),
],
),
Veggie(
id: 13,
name: 'Kale',
imageAssetPath: 'assets/images/kale.jpg',
category: VeggieCategory.cruciferous,
shortDescription: 'The meanest vegetable. Does not want to be eaten.',
accentColor: const Color(0x40a86bd8),
seasons: [Season.winter, Season.autumn],
vitaminAPercentage: 133,
vitaminCPercentage: 134,
servingSize: '1 cup, chopped',
caloriesPerServing: 33,
trivia: const [
Trivia(
'Kale is sweeter when harvested after what?',
[
'Sundown',
'The first frost',
'Reading it a sad story',
],
1,
),
Trivia(
'Which of these isn\'t a color in which Kale can be found?',
[
'Purple',
'White',
'Orange',
],
2,
),
Trivia(
'One serving of kale provides what percentage of a typical person\'s requirement for vitamin K?',
[
'100%',
'300%',
'900%',
],
2,
),
],
),
Veggie(
id: 14,
name: 'Kiwi',
imageAssetPath: 'assets/images/kiwi.jpg',
category: VeggieCategory.berry,
shortDescription: 'Also known as Chinese gooseberry.',
accentColor: const Color(0x40b47b37),
seasons: [Season.summer],
vitaminAPercentage: 2,
vitaminCPercentage: 240,
servingSize: '2 medium kiwis',
caloriesPerServing: 90,
trivia: const [
Trivia(
'Europeans sometimes refer to kiwi as what?',
[
'Chinese gooseberry',
'Gem berries',
'Bulbfruit',
],
0,
),
Trivia(
'On what type of plant do kiwi grow?',
[
'Tree',
'Shrub',
'Vine',
],
2,
),
Trivia(
'Compared to oranges, kiwi typically contain how much vitamin C?',
[
'Half as much',
'About the same',
'Twice as much',
],
2,
),
],
),
Veggie(
id: 15,
name: 'Lemons',
imageAssetPath: 'assets/images/lemon.jpg',
category: VeggieCategory.citrus,
shortDescription: 'Similar to limes, only yellow.',
accentColor: const Color(0x40e2a500),
seasons: [Season.winter],
vitaminAPercentage: 0,
vitaminCPercentage: 40,
servingSize: '1 medium lemon',
caloriesPerServing: 15,
trivia: const [
Trivia(
'A lemon tree can produce up to how many pounds of fruit each year?',
[
'100',
'300',
'600',
],
2,
),
Trivia(
'Which of these isn\'t a type of lemon?',
[
'Acid',
'Sarcastic',
'Sweet',
],
1,
),
Trivia(
'What percent of a typical lemon is composed of juice?',
[
'20%',
'40%',
'60%',
],
0,
),
Trivia(
'Which lemon variety is prized for its sweeter-than-averga flavor?',
[
'Hookeye',
'Meyer',
'Minnesota Stomp',
],
1,
),
],
),
Veggie(
id: 16,
name: 'Limes',
imageAssetPath: 'assets/images/lime.jpg',
category: VeggieCategory.citrus,
shortDescription: 'Couldn\'t have ceviche and margaritas without them.',
accentColor: const Color(0x4089b733),
seasons: [Season.winter],
vitaminAPercentage: 0,
vitaminCPercentage: 35,
servingSize: '1 medium lime',
caloriesPerServing: 20,
trivia: const [
Trivia(
'Which American state is famous for its Key Lime Pie?',
[
'Pennsylvania',
'Arizona',
'Florida',
],
2,
),
Trivia(
'Dried limes are a particularly popular soup ingredient in which part of the world?',
[
'Middle East',
'Africa',
'Australia',
],
0,
),
Trivia(
'Sailors once carried limes on their ships to help against which condition?',
[
'Influenza',
'Scurvy',
'Boredom',
],
1,
),
],
),
Veggie(
id: 17,
name: 'Mangos',
imageAssetPath: 'assets/images/mango.jpg',
category: VeggieCategory.tropical,
shortDescription: 'A fun orange fruit popular with smoothie enthusiasts.',
accentColor: const Color(0x40fcc93c),
seasons: [Season.summer, Season.autumn],
vitaminAPercentage: 72,
vitaminCPercentage: 203,
servingSize: '1 fruit',
caloriesPerServing: 201,
trivia: const [
Trivia(
'In Mexico, mangos are frequently dusted with what spices before being eaten as a snack?',
[
'Black pepper and sugar',
'Chile pepper and lime juice',
'Cumin and salt',
],
1,
),
Trivia(
'To which nut is the mango closely related?',
[
'Cashew',
'Peanut',
'Walnut',
],
0,
),
Trivia(
'In which country did mangos originate?',
[
'India',
'Madagascar',
'Belize',
],
0,
),
],
),
Veggie(
id: 18,
name: 'Mushrooms',
imageAssetPath: 'assets/images/mushroom.jpg',
category: VeggieCategory.fungus,
shortDescription: 'They\'re not truffles, but they\'re still tasty.',
accentColor: const Color(0x40ba754b),
seasons: [Season.spring, Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 2,
servingSize: '5 medium \'shrooms',
caloriesPerServing: 20,
trivia: const [
Trivia(
'Someone who loves eating mushrooms is called what?',
[
'A mycophagist',
'A philologist',
'A phlebotomist',
],
0,
),
Trivia(
'Morel mushrooms are particulary prized by cooks of which style of cuisine?',
[
'French',
'Italian',
'Japanese',
],
0,
),
Trivia(
'The largest living organism ever identified is what type of mushroom?',
[
'Shiitake mushroom',
'Honey mushroom',
'Glory mushroom',
],
1,
),
Trivia(
'One mushroom cousin is the truffle. Which color truffle is the most prized?',
[
'White',
'Black',
'Brown',
],
0,
),
],
),
Veggie(
id: 19,
name: 'Nectarines',
imageAssetPath: 'assets/images/nectarine.jpg',
category: VeggieCategory.stoneFruit,
shortDescription: 'Tiny, bald peaches.',
accentColor: const Color(0x40e45b3b),
seasons: [Season.summer],
vitaminAPercentage: 8,
vitaminCPercentage: 15,
servingSize: '1 medium nectarine',
caloriesPerServing: 60,
trivia: const [
Trivia(
'Nectarines are technically a variety of which other fruit?',
[
'Peach',
'Plum',
'Cherry',
],
0,
),
Trivia(
'Nectarines are sometimes called what?',
[
'Neckless geese',
'Giant grapes',
'Shaved peaches',
],
2,
),
Trivia(
'Nectarines are thought to have originated in which country?',
[
'China',
'Italy',
'Ethiopia',
],
0,
),
],
),
Veggie(
id: 20,
name: 'Persimmons',
imageAssetPath: 'assets/images/persimmon.jpg',
category: VeggieCategory.fruit,
shortDescription: 'It\'s like a plum and an apple had a baby together.',
accentColor: const Color(0x40979852),
seasons: [Season.winter, Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 27,
servingSize: '1 fruit',
caloriesPerServing: 32,
trivia: const [
Trivia(
'What\'s the most commonly grown variety of persimmon?',
[
'Sugar',
'Yellowbird',
'Kaki',
],
2,
),
Trivia(
'The word "persimmon" is derived from which language?',
[
'Latin',
'Indo-European',
'Powhatan',
],
2,
),
Trivia(
'Which of these is an alternate variety of persimmon?',
[
'Black Sapote',
'Green Troubador',
'Red Captain',
],
0,
),
],
),
Veggie(
id: 21,
name: 'Plums',
imageAssetPath: 'assets/images/plum.jpg',
category: VeggieCategory.stoneFruit,
shortDescription: 'Popular in fruit salads and children\'s tales.',
accentColor: const Color(0x40e48b47),
seasons: [Season.summer],
vitaminAPercentage: 8,
vitaminCPercentage: 10,
servingSize: '2 medium plums',
caloriesPerServing: 70,
trivia: const [
Trivia(
'Plums should be handled with care because...?',
[
'They\'re particularly sticky',
'They bruise easily',
'It\'s easy to hurt their feelings',
],
1,
),
Trivia(
'A dried plum is known as what?',
[
'A prune',
'An apricot',
'A raisin',
],
0,
),
Trivia(
'A sugar plum typically contains how much plum juice?',
[
'0%',
'25%',
'50%',
],
0,
),
],
),
Veggie(
id: 22,
name: 'Potatoes',
imageAssetPath: 'assets/images/potato.jpg',
category: VeggieCategory.tuber,
shortDescription: 'King of starches and giver of french fries.',
accentColor: const Color(0x40c65c63),
seasons: [Season.winter, Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 45,
servingSize: '1 medium spud',
caloriesPerServing: 110,
trivia: const [
Trivia(
'Which country consumes the most fried potatoes per capita?',
[
'United States',
'Belgium',
'Ireland',
],
1,
),
Trivia(
'Who is credited with introducing French Fries to the United States?',
[
'Thomas Jefferson',
'Betsy Ross',
'Alexander Hamilton',
],
0,
),
Trivia(
'The world record for loongest curly fry stands at how many inches?',
[
'38',
'58',
'78',
],
0,
),
],
),
Veggie(
id: 23,
name: 'Radicchio',
imageAssetPath: 'assets/images/radicchio.jpg',
category: VeggieCategory.leafy,
shortDescription: 'It\'s that bitter taste in the salad you\'re eating.',
accentColor: const Color(0x40d75875),
seasons: [Season.spring, Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 10,
servingSize: '2 cups shredded',
caloriesPerServing: 20,
trivia: const [
Trivia(
'Radicchio is a particuarly good source of which mineral?',
[
'Manganese',
'Mercury',
'Molybdenum',
],
0,
),
Trivia(
'Radicchio should be stored at what temperature?',
[
'Room temperature',
'Refrigerator temperature',
'Freezer temperature',
],
1,
),
Trivia(
'What happens to the taste of radicchio once the plant flowers?',
[
'It becomes bitter',
'It becomes sweeter',
'Nothing. It just looks nicer!',
],
0,
),
],
),
Veggie(
id: 24,
name: 'Radishes',
imageAssetPath: 'assets/images/radish.jpg',
category: VeggieCategory.root,
shortDescription: 'Try roasting them in addition to slicing them up raw.',
accentColor: const Color(0x40819e4e),
seasons: [Season.spring, Season.autumn],
vitaminAPercentage: 0,
vitaminCPercentage: 30,
servingSize: '7 radishes',
caloriesPerServing: 10,
trivia: const [
Trivia(
'Which ancient civilization is known to have used radish oil?',
[
'Egyptian',
'Sumerian',
'Incan',
],
0,
),
Trivia(
'What\'s the name of the radish commonly used in Japanese cuisine?',
[
'Daisuki',
'Daijin',
'Daikon',
],
2,
),
Trivia(
'The annual "Night of the Radishes" festival takes place just before Christmas Eve in which country?',
[
'Mexico',
'France',
'South Korea',
],
0,
),
],
),
Veggie(
id: 25,
name: 'Squash',
imageAssetPath: 'assets/images/squash.jpg',
category: VeggieCategory.gourd,
shortDescription: 'Just slather them in butter and pop \'em in the oven.',
accentColor: const Color(0x40dbb721),
seasons: [Season.winter, Season.autumn],
vitaminAPercentage: 297,
vitaminCPercentage: 48,
servingSize: '1 cup diced butternut',
caloriesPerServing: 63,
trivia: const [
Trivia(
'Which of these is not a type of squash?',
[
'Zucchini',
'Spaghetti',
'Martini',
],
2,
),
Trivia(
'Gourds like squash are also handy as what?',
[
'Containers',
'Furniture',
'Musical instruments',
],
0,
),
Trivia(
'Which country is the world\'s largest importer of squashes?',
[
'China',
'United States',
'Russia',
],
1,
),
],
),
Veggie(
id: 26,
name: 'Strawberries',
imageAssetPath: 'assets/images/strawberry.jpg',
category: VeggieCategory.berry,
shortDescription:
'A delicious fruit that keeps its seeds on the outside.',
accentColor: const Color(0x40f06a44),
seasons: [Season.spring, Season.summer],
vitaminAPercentage: 0,
vitaminCPercentage: 160,
servingSize: '8 medium strawberries',
caloriesPerServing: 50,
trivia: const [
Trivia(
'How many seeds are in the average strawberry?',
[
'50',
'100',
'200',
],
2,
),
Trivia(
'Strawberries are closely related to which type of flower?',
[
'The rose',
'The daisy',
'The tulip',
],
0,
),
Trivia(
'Strawberries are unique among fruit for what reason?',
[
'Their seeds are on the outside',
'Their flowers are striped',
'Their plants have a taproot',
],
0,
),
],
),
Veggie(
id: 27,
name: 'Tangelo',
imageAssetPath: 'assets/images/tangelo.jpg',
category: VeggieCategory.citrus,
shortDescription: 'No one\'s sure what they are or where they came from.',
accentColor: const Color(0x40f88c06),
seasons: [Season.winter, Season.autumn],
vitaminAPercentage: 6,
vitaminCPercentage: 181,
servingSize: '1 medium tangelo',
caloriesPerServing: 60,
trivia: const [
Trivia(
'The tangelo is thought to be a cross between oranges and which other fruit?',
[
'Peach',
'Plum',
'Pummelo',
],
2,
),
Trivia(
'Which of these is a variety of tangelo?',
[
'Orlando',
'Bluebonnet',
'Creakey Pete',
],
0,
),
Trivia(
'A typical tangelo is about what size?',
[
'Golf ball',
'Baseball',
'Bowling ball',
],
1,
),
],
),
Veggie(
id: 28,
name: 'Tomatoes',
imageAssetPath: 'assets/images/tomato.jpg',
category: VeggieCategory.stealthFruit,
shortDescription: 'A new world food with old world tradition.',
accentColor: const Color(0x40ea3628),
seasons: [Season.summer],
vitaminAPercentage: 20,
vitaminCPercentage: 40,
servingSize: '1 medium tomato',
caloriesPerServing: 25,
trivia: const [
Trivia(
'French speakers sometimes refer to tomatoes with which name?',
[
'Piet de terre',
'Mille-feuille',
'Pomme d\'amour',
],
2,
),
Trivia(
'The largest tomato known to have been grown weighed in at how many pounds?',
[
'8',
'10',
'12',
],
0,
),
Trivia(
'Which country is the world\'s largest producer of tomatoes?',
[
'China',
'Italy',
'Ecuador',
],
0,
),
],
),
Veggie(
id: 29,
name: 'Watermelon',
imageAssetPath: 'assets/images/watermelon.jpg',
category: VeggieCategory.melon,
shortDescription: 'Everyone\'s favorite closing act at the picnic.',
accentColor: const Color(0x40fa8c75),
seasons: [Season.summer],
vitaminAPercentage: 30,
vitaminCPercentage: 25,
servingSize: '2 cups diced',
caloriesPerServing: 80,
trivia: const [
Trivia(
'How much of a watermelon is water?',
[
'50%',
'75%',
'90%',
],
2,
),
Trivia(
'Which nation is famous for growing watermelons in unsual shapes like cubes and hearts?',
[
'Armenia',
'Japan',
'Saudi Arabia',
],
1,
),
Trivia(
'Which U.S. state declared the watermelon to be its state vegetable (that\'s right, vegetable)?',
[
'Kansas',
'Iowa',
'Oklahoma',
],
2,
),
Trivia(
'Early explorers to the Americas used watermelons as which piece of equipment?',
[
'Stools',
'Pillows',
'Canteens',
],
2,
),
],
),
Veggie(
id: 30,
name: 'Orange Bell Pepper',
imageAssetPath: 'assets/images/orange_bell_pepper.jpg',
category: VeggieCategory.stealthFruit,
shortDescription: 'Like green pepper, but nicer.',
accentColor: const Color(0x40fd8e00),
seasons: [Season.summer],
vitaminAPercentage: 4,
vitaminCPercentage: 190,
servingSize: '1 medium pepper',
caloriesPerServing: 25,
trivia: const [
Trivia(
'Which compound (not found in bell peppers) is responsible for many peppers\' spicy taste?',
[
'Alum',
'Capsacin',
'Calcium',
],
1,
),
Trivia(
'In comparison to green peppers, how expensive are their orange cousins?',
[
'Cheaper',
'About the same',
'More expensive',
],
2,
),
Trivia(
'Who is generally credited with giving bell peppers their peppery name?',
[
'Christopher Columbus',
'Benjamin Franklin',
'Eleanor Roosevelt',
],
0,
),
],
),
];
}
| samples/veggieseasons/lib/data/local_veggie_provider.dart/0 | {
"file_path": "samples/veggieseasons/lib/data/local_veggie_provider.dart",
"repo_id": "samples",
"token_count": 19558
} | 1,241 |
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';
import 'package:veggieseasons/data/veggie.dart';
import 'package:veggieseasons/styles.dart';
class FrostyBackground extends StatelessWidget {
const FrostyBackground({
this.color,
this.intensity = 25,
this.child,
super.key,
});
final Color? color;
final double intensity;
final Widget? child;
@override
Widget build(BuildContext context) {
return ClipRect(
child: BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: intensity, sigmaY: intensity),
child: DecoratedBox(
decoration: BoxDecoration(
color: color,
),
child: child,
),
),
);
}
}
/// A Card-like Widget that responds to tap events by animating changes to its
/// elevation and invoking an optional [onPressed] callback.
class PressableCard extends StatefulWidget {
const PressableCard({
required this.child,
this.borderRadius = const BorderRadius.all(Radius.circular(5)),
this.upElevation = 2,
this.downElevation = 0,
this.shadowColor = CupertinoColors.black,
this.duration = const Duration(milliseconds: 100),
this.onPressed,
super.key,
});
final VoidCallback? onPressed;
final Widget child;
final BorderRadius borderRadius;
final double upElevation;
final double downElevation;
final Color shadowColor;
final Duration duration;
@override
State<PressableCard> createState() => _PressableCardState();
}
class _PressableCardState extends State<PressableCard> {
bool cardIsDown = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() => cardIsDown = false);
if (widget.onPressed != null) {
widget.onPressed!();
}
},
onTapDown: (details) => setState(() => cardIsDown = true),
onTapCancel: () => setState(() => cardIsDown = false),
child: AnimatedPhysicalModel(
elevation: cardIsDown ? widget.downElevation : widget.upElevation,
borderRadius: widget.borderRadius,
shape: BoxShape.rectangle,
shadowColor: widget.shadowColor,
duration: widget.duration,
color: CupertinoColors.lightBackgroundGray,
child: ClipRRect(
borderRadius: widget.borderRadius,
child: widget.child,
),
),
);
}
}
class VeggieCard extends StatelessWidget {
const VeggieCard(this.veggie, this.isInSeason, this.isPreferredCategory,
{super.key});
/// Veggie to be displayed by the card.
final Veggie veggie;
/// If the veggie is in season, it's displayed more prominently and the
/// image is fully saturated. Otherwise, it's reduced and de-saturated.
final bool isInSeason;
/// Whether [veggie] falls into one of user's preferred [VeggieCategory]s
final bool isPreferredCategory;
Widget _buildDetails(BuildContext context) {
final themeData = CupertinoTheme.of(context);
return FrostyBackground(
color: const Color(0x90ffffff),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
veggie.name,
style: Styles.cardTitleText(themeData),
),
Text(
veggie.shortDescription,
style: Styles.cardDescriptionText(themeData),
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return PressableCard(
onPressed: () {
// GoRouter does not support relative routes,
// so navigate to the absolute route.
// see https://github.com/flutter/flutter/issues/108177
context.go('/list/details/${veggie.id}');
},
child: Stack(
children: [
Semantics(
label: 'A card background featuring ${veggie.name}',
child: Container(
height: isInSeason ? 300 : 150,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
colorFilter:
isInSeason ? null : Styles.desaturatedColorFilter,
image: AssetImage(
veggie.imageAssetPath,
),
),
),
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: _buildDetails(context),
),
],
),
);
}
}
| samples/veggieseasons/lib/widgets/veggie_card.dart/0 | {
"file_path": "samples/veggieseasons/lib/widgets/veggie_card.dart",
"repo_id": "samples",
"token_count": 2042
} | 1,242 |
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:veggieseasons/data/app_state.dart';
import 'package:veggieseasons/data/veggie.dart';
import 'package:veggieseasons/main.dart';
void main() {
testWidgets('restoration smoke test', (tester) async {
SharedPreferences.setMockInitialValues(<String, Object>{});
AppState.debugCurrentSeason = Season.autumn;
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root',
child: VeggieApp(),
),
);
expect(find.text('In season today'), findsOneWidget);
expect(find.text('Grapes'), findsNothing);
expect(find.text('Figs'), findsNothing);
await tester.scrollUntilVisible(find.text('Grapes'), 100);
expect(find.text('In season today'), findsNothing);
expect(find.text('Figs'), findsOneWidget);
expect(find.text('Grapes'), findsOneWidget);
// Scroll offset of "Home" is restored.
await tester.restartAndRestore();
expect(find.text('In season today'), findsNothing);
expect(find.text('Figs'), findsOneWidget);
expect(find.text('Grapes'), findsOneWidget);
// Open details page for "Figs".
await tester.tap(find.text('Figs'));
await tester.pumpAndSettle();
expect(find.text('Grapes'), findsNothing);
expect(find.text('Figs'), findsOneWidget);
expect(find.text('Serving info'), findsOneWidget);
expect(tester.widget<CupertinoSwitch>(find.byType(CupertinoSwitch)).value,
isFalse);
await tester.tap(find.byType(CupertinoSwitch));
await tester.pumpAndSettle();
expect(tester.widget<CupertinoSwitch>(find.byType(CupertinoSwitch)).value,
isTrue);
// Current details page is restored.
await tester.restartAndRestore();
expect(find.text('Grapes'), findsNothing);
expect(find.text('Figs'), findsOneWidget);
expect(find.text('Serving info'), findsOneWidget);
expect(tester.widget<CupertinoSwitch>(find.byType(CupertinoSwitch)).value,
isTrue);
await tester.tap(find.text('Trivia'));
await tester.pumpAndSettle();
expect(find.text('Serving info'), findsNothing);
expect(
find.text("Which of these isn't a variety of figs?"), findsOneWidget);
// Restores to trivia page.
await tester.restartAndRestore();
expect(find.text('Serving info'), findsNothing);
expect(
find.text("Which of these isn't a variety of figs?"), findsOneWidget);
await tester.tap(find.text('Brown Turkey'));
await tester.pumpAndSettle();
expect(find.text("Which of these isn't a variety of figs?"), findsNothing);
expect(find.text('Next Question'), findsOneWidget);
// Restores trivia state.
await tester.restartAndRestore();
expect(find.text("Which of these isn't a variety of figs?"), findsNothing);
expect(find.text('Next Question'), findsOneWidget);
// Close details page.
tester.state<NavigatorState>(find.byType(Navigator).last).pop();
await tester.pumpAndSettle();
expect(find.text('Trivia'), findsNothing);
// Old scroll offset is still preserved.
expect(find.text('Grapes'), findsOneWidget);
expect(find.text('Figs'), findsOneWidget);
await tester.restartAndRestore();
expect(find.text('Grapes'), findsOneWidget);
expect(find.text('Figs'), findsOneWidget);
// Go to the garden.
await tester.tap(find.text('My Garden'));
await tester.pumpAndSettle();
expect(find.text('My Garden'),
findsNWidgets(2)); // Name of the tap & title of page.
expect(find.text('Grapes'), findsNothing);
expect(find.text('Figs'), findsOneWidget);
// Restores the current selected tab.
await tester.restartAndRestore();
expect(find.text('My Garden'),
findsNWidgets(2)); // Name of the tap & title of page.
expect(find.text('Grapes'), findsNothing);
expect(find.text('Figs'), findsOneWidget);
expect(find.text('Apples'), findsNothing);
// Go to "Search".
await tester.tap(find.text('Search'));
await tester.pumpAndSettle();
expect(find.text('Apples'), findsOneWidget);
expect(find.text('Tangelo'), findsNothing);
await tester.enterText(
find.byType(CupertinoTextField).hitTestable(), 'Tan');
await tester.pumpAndSettle();
expect(find.text('Apples'), findsNothing);
expect(find.text('Tangelo'), findsOneWidget);
expect(find.text('Tan').hitTestable(), findsOneWidget);
// Restores search text and result.
await tester.restartAndRestore();
expect(find.text('Apples'), findsNothing);
expect(find.text('Tangelo'), findsOneWidget);
expect(find.text('Tan').hitTestable(), findsOneWidget); // search text
expect(find.text('Serving info'), findsNothing);
// Open a details page from search
await tester.tap(find.text('Tangelo'));
await tester.pumpAndSettle();
expect(find.text('Tangelo'), findsOneWidget);
expect(find.text('Serving info'), findsOneWidget);
// Restores details page
await tester.restartAndRestore();
expect(find.text('Tangelo'), findsOneWidget);
expect(find.text('Serving info'), findsOneWidget);
// Go back to search page, is also restored
tester.state<NavigatorState>(find.byType(Navigator).last).pop();
await tester.pumpAndSettle();
expect(find.text('Serving info'), findsNothing);
expect(find.text('Apples'), findsNothing);
expect(find.text('Tangelo'), findsOneWidget);
expect(find.text('Tan').hitTestable(), findsOneWidget); // search text
expect(find.text('Calorie Target'), findsNothing);
// Go to "Settings".
await tester.tap(find.text('Settings'));
await tester.pumpAndSettle();
expect(find.text('Calorie Target'), findsOneWidget);
await tester.restartAndRestore();
expect(find.text('Calorie Target'), findsOneWidget);
expect(find.text('AVAILABLE CALORIE LEVELS'), findsNothing);
// Go to calorie target selection.
await tester.tap(find.text('Calorie Target'));
await tester.pumpAndSettle();
expect(find.text('AVAILABLE CALORIE LEVELS'), findsOneWidget);
await tester.restartAndRestore();
expect(find.text('AVAILABLE CALORIE LEVELS'), findsOneWidget);
// Go back to settings main screen.
tester.state<NavigatorState>(find.byType(Navigator).last).pop();
await tester.pumpAndSettle();
expect(find.text('AVAILABLE CALORIE LEVELS'), findsNothing);
expect(find.text('Allium'), findsNothing);
// Go to preferred categories selection.
await tester.tap(find.text('Preferred Categories'));
await tester.pumpAndSettle();
expect(find.text('Calorie Target'), findsNothing);
expect(find.text('Allium'), findsOneWidget);
await tester.restartAndRestore();
expect(find.text('Allium'), findsOneWidget);
// Go back to settings main screen.
tester.state<NavigatorState>(find.byType(Navigator).last).pop();
await tester.pumpAndSettle();
expect(find.text('Allium'), findsNothing);
expect(find.text('Preferred Categories'), findsOneWidget);
expect(find.text('Calorie Target'), findsOneWidget);
});
}
| samples/veggieseasons/test/restoration_test.dart/0 | {
"file_path": "samples/veggieseasons/test/restoration_test.dart",
"repo_id": "samples",
"token_count": 2571
} | 1,243 |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file
import 'dart:io';
import 'package:path/path.dart' as p;
import 'common.dart';
import 'fix_base_tags.dart';
const ignoredDirectories = [
'_tool',
'_packages/web_startup_analyzer',
'_packages/web_startup_analyzer/example',
'samples_index'
];
void main() async {
final packageDirs = [
...listPackageDirs(Directory.current)
.map((path) => p.relative(path, from: Directory.current.path))
.where((path) => !ignoredDirectories.contains(path))
];
print('Building the sample index...');
await _run('samples_index', 'flutter', ['pub', 'get']);
await _run('samples_index', 'flutter', ['pub', 'run', 'grinder', 'deploy']);
// Create the directory each Flutter Web sample lives in
Directory(p.join(Directory.current.path, 'samples_index', 'public', 'web'))
.createSync(recursive: true);
for (var i = 0; i < packageDirs.length; i++) {
var directory = packageDirs[i];
logWrapped(ansiMagenta, '\n$directory (${i + 1} of ${packageDirs.length})');
// Create the target directory
var directoryName = p.basename(directory);
var sourceBuildDir =
p.join(Directory.current.path, directory, 'build', 'web');
var targetDirectory = p.join(Directory.current.path, 'samples_index',
'public', 'web', directoryName);
// Build the sample and copy the files
await _run(directory, 'flutter', ['pub', 'get']);
await _run(directory, 'flutter', ['build', 'web']);
await _run(directory, 'mv', [sourceBuildDir, targetDirectory]);
}
// Update the <base href> tags in each index.html file
await fixBaseTags();
}
// Invokes run() and exits if the sub-process failed.
Future<void> _run(
String workingDir, String commandName, List<String> args) async {
var success = await run(workingDir, commandName, args);
if (!success) {
exit(1);
}
}
| samples/web/_tool/build_ci.dart/0 | {
"file_path": "samples/web/_tool/build_ci.dart",
"repo_id": "samples",
"token_count": 690
} | 1,244 |
# Flutter samples index generator
This tool is used to generate the visual
[samples index for Flutter samples](https://flutter.github.io/samples/).
## Generating the index
We use [grinder](https://pub.dev/packages/grinder) to run the build tasks:
```bash
$ dart pub get
$ dart run grinder generate
```
This will generate the index into `./web`
## Serving the index locally
If you want to serve the index locally, you can use
[webdev](https://pub.dev/packages/webdev):
```bash
$ dart pub global activate grinder
$ webdev serve
```
## Publishing the index
You can build the complete index into a publishable directory using Grinder:
```bash
$ dart run grinder build-release
```
This outputs the completely built index to `./public`.
| samples/web/samples_index/README.md/0 | {
"file_path": "samples/web/samples_index/README.md",
"repo_id": "samples",
"token_count": 216
} | 1,245 |
import 'dart:html';
import 'package:mdc_web/mdc_web.dart';
import 'package:samples_index/src/carousel.dart';
void main() {
querySelectorAll('.mdc-card__primary-action').forEach((el) => MDCRipple(el));
// Initialize carousel
// This carousel will use the div slider-container as the base
// withArrowKeyControl is used to listen for arrow key up events
Carousel.init(withArrowKeyControl: true);
}
| samples/web/samples_index/web/description.dart/0 | {
"file_path": "samples/web/samples_index/web/description.dart",
"repo_id": "samples",
"token_count": 137
} | 1,246 |
# ng-flutter
This Angular project is a simple example of how Angular and Flutter
web apps could be integrated, and have them interop.
## Points of Interest
### Angular
This repository is a quite standard Angular app. The following changes were made
to be able to use (and interop) with a Flutter web application:
* `package.json` has a custom `prebuild` script that builds the
Flutter web app, so Angular can find it later.
* `flutter.js` is added as a `"scripts"` entry in `angular.json`.
Angular takes care of minimizing and injecting it as any other script.
* The rest of the flutter app `flutter/build/web/` is registered
as an `"assets"` entry in `angular.json`, and moved to `/flutter`.
* The `ng-flutter` component takes care of embedding Flutter web, and yielding
control to Angular through an `appLoaded` `EventEmitter`. The object yielded
by this emitter is a state controller exposed by flutter via a JS custom
event!
### Flutter
The embedded Flutter application lives in the `flutter` directory of this repo.
That application is a standard web app, that doesn't need to be aware that it's
going to be embedded in another framework.
* Flutter uses new `@staticInterop` methods to allow certain Dart functions to
be called from JavaScript.
* Look at how `createDartExport` and `broadcastAppEvent` work together to make
the `_state` controller of the Flutter app available to Angular!
## How to build the app
### Requirements
If you want to build and run this demo on your machine, you'll need
a moderately recent version of Angular:
```console
$ ng version
Angular CLI: 17.0.0
Node: 20.9.0
Package Manager: npm 10.1.0
OS: linux x64
```
And Flutter:
```
$ flutter --version
Flutter 3.13.9 • channel stable
Framework • revision d211f42860 (2 weeks ago) • 2023-10-25 13:42:25 -0700
Engine • revision 0545f8705d
Tools • Dart 3.1.5 • DevTools 2.25.0
```
**Ensure `npm`, `ng` and `flutter` are present in your `$PATH`.**
### Building the app
This repository is a moderately standard Angular app. It integrates
Flutter web by making it part of the Angular `assets`.
In order to build this app, first fetch its `npm` dependencies:
```console
$ npm install
added 963 packages, and audited 964 packages in 17s
93 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
```
Then run the `build` script. It'll take care of building Flutter
automatically:
```console
$ npm run build
> [email protected] prebuild
... Flutter web build output ...
Compiling lib/main.dart for the Web...
> [email protected] build
> ng build
... Angular build output ...
✔ Browser application bundle generation complete.
✔ Copying assets complete.
✔ Index html generation complete.
```
### Local Angular development
Once you've reached this point, you should be able to work with
your Angular application normally, for example to run a local web
server:
```console
$ npm run start
> [email protected] start
> ng serve
✔ Browser application bundle generation complete.
Initial Chunk Files | Names | Raw Size
vendor.js | vendor | 4.38 MB |
... Angular build output...
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
✔ Compiled successfully.
```
Navigate to `http://localhost:4200/`. The application will automatically reload
if you change any of its Angular source files.
### Local Flutter web development
The Flutter app lives inside the `flutter` directory, and can be
developed independently. Just do any changes on Flutter web as you'd
normally do. It even includes a small `web/index.html` so you can see
changes to your app without running the whole Angular setup.
> **Note**
> For now, Angular does _not_ auto-detect changes to your Flutter web
app, so once you're happy with your Flutter web app, make sure to
call `npm run build` so everything rebuilds and gets placed into its
correct location.
### Deploying the app
After `npm run build`, you should have a deployable Angular + Flutter
web app in the `dist` directory of this Angular project.
Your built app can can be deployed anywhere, but do check
[Firebase hosting](https://firebase.google.com/docs/hosting) for a
super-easy deployment experience!
## Troubleshooting
### Flutter
Ensure your flutter app is properly rebuilt after any changes.
* Run `npm run build` to re-build the Flutter app.
If you encounter error messages like:
```
Error: Can't resolve 'flutter/build/web/flutter.js' in '/my/checkout/of/ng-flutter'
```
You definitely need to run `npm run build`!
## Reach out to the team(s)!
Have you had any problem not covered in this README? Do you want
to see other embedding examples?
Let us know by [creating an issue](https://github.com/flutter/samples/issues/new) or opening a new pull request.
Thanks!
| samples/web_embedding/ng-flutter/README.md/0 | {
"file_path": "samples/web_embedding/ng-flutter/README.md",
"repo_id": "samples",
"token_count": 1415
} | 1,247 |
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
/* FX */
.fx-resize {
width: 480px !important;
height: 320px !important;
}
.fx-spin { animation: spin 6400ms ease-in-out infinite; }
.fx-shadow { position: relative; overflow: visible !important; }
.fx-shadow::before {
content: "";
position: absolute;
display: block;
width: 100%;
top: calc(100% - 1px);
left: 0;
height: 1px;
background-color: black;
border-radius: 50%;
z-index: -1;
transform: rotateX(80deg);
box-shadow: 0px 0px 60px 38px rgb(0 0 0 / 25%);
}
.fx-mirror {
-webkit-box-reflect: below 0px linear-gradient(to bottom, rgba(0,0,0,0.0), rgba(0,0,0,0.4));
}
@keyframes spin {
0% {
transform: perspective(1000px) rotateY(0deg);
animation-timing-function: ease-in-out;
}
10% {
transform: perspective(1000px) rotateY(0deg);
animation-timing-function: ease-in-out;
}
40% {
transform: perspective(1000px) rotateY(180deg);
animation-timing-function: ease-in-out;
}
60% {
transform: perspective(1000px) rotateY(180deg);
animation-timing-function: ease-in-out;
}
90% {
transform: perspective(1000px) rotateY(359deg);
animation-timing-function: ease-in-out;
}
100% {
transform: perspective(1000px) rotateY(360deg);
animation-timing-function: ease-in-out;
}
} | samples/web_embedding/ng-flutter/src/styles.css/0 | {
"file_path": "samples/web_embedding/ng-flutter/src/styles.css",
"repo_id": "samples",
"token_count": 536
} | 1,248 |
If you would like to contribute to the Flutter project,
we’re happy to have your help! Anyone can contribute, whether you’re new to
the project or you’ve been around a long time, and whether you self-identify
as a developer, an end user, or someone who just can’t stand seeing typos.
If you aren't familiar with how GitHub works, see [Introduction to
GitHub](https://services.github.com/on-demand/intro-to-github/).
We have many [repos in the Flutter project](https://github.com/flutter),
but two of the primary repos are the
[Flutter SDK](https://github.com/flutter/flutter), and this repo, the
[Flutter website](https://github.com/flutter/website).
To contribute a fix to a repo, submit a [pull request
(PR)](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).
For information on contributing code or API docs to the Flutter SDK, see
[Contributing to
Flutter](https://github.com/flutter/flutter/blob/main/CONTRIBUTING.md)
in the [Flutter SDK](https://github.com/flutter/flutter) repo.
We are also happy to accept your PRs to the
[Flutter website](https://github.com/flutter/website/) repo,
even if it's just to fix a typo.
For ways to get involved in the Flutter community or to learn about us,
visit the [Flutter community](https://flutter.dev/community) page.
# Ways to contribute
We encourage you to reach out and join the conversation.
An easy way to send feedback is to "thumbs up" issues important to you
in either the issue tracker for the [Flutter SDK and API docs][issues],
or the [flutter.dev website][doc-issues].
Other ways you can contribute:
* [Ask HOW-TO questions that can be answered with specific solutions][so]
* [Live chat with Flutter engineers and users][chat]
* [Discuss Flutter, best practices, app design, and more on our
mailing list][mailinglist]
* [Report bugs and request features][issues]
* [Report API docs bugs][issues]
* [Submit PRs to the Flutter SDK][PRs]
* [Request docs for flutter.dev][doc-issues]
* [Submit PRs to flutter.dev][doc-PRs]
* [Follow us on Twitter: @flutterdev](https://twitter.com/flutterdev/)
* [Read the Flutter Publication on Medium](https://medium.com/flutter)
* [Sign up to Future UX Studies on Flutter](https://flutter.dev/research-signup)
* [Join the subreddit to keep up with the latest in the Flutter
community][reddit]
* [Join the Discord to connect with other developers
and discuss Flutter][discord]
Happy Fluttering!
[issues]: https://github.com/flutter/flutter/issues
[PRs]: https://github.com/flutter/flutter/pulls
[discord]: https://discord.gg/rflutterdev
[doc-issues]: https://github.com/flutter/website/issues
[doc-PRs]: https://github.com/flutter/website/pulls
[so]: https://stackoverflow.com/tags/flutter
[mailinglist]: https://groups.google.com/d/forum/flutter-dev
[chat]: https://github.com/flutter/flutter/wiki/Chat
[reddit]: https://www.reddit.com/r/FlutterDev
| website/CONTRIBUTING.md/0 | {
"file_path": "website/CONTRIBUTING.md",
"repo_id": "website",
"token_count": 912
} | 1,249 |
import 'package:flutter/material.dart';
void main() => runApp(const LogoApp());
// #docregion LogoWidget
class LogoWidget extends StatelessWidget {
const LogoWidget({super.key});
// Leave out the height and width so it fills the animating parent
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 10),
child: const FlutterLogo(),
);
}
}
// #enddocregion LogoWidget
// #docregion GrowTransition
class GrowTransition extends StatelessWidget {
const GrowTransition(
{required this.child, required this.animation, super.key});
final Widget child;
final Animation<double> animation;
@override
Widget build(BuildContext context) {
return Center(
child: AnimatedBuilder(
animation: animation,
builder: (context, child) {
return SizedBox(
height: animation.value,
width: animation.value,
child: child,
);
},
child: child,
),
);
}
}
// #enddocregion GrowTransition
class LogoApp extends StatefulWidget {
const LogoApp({super.key});
@override
State<LogoApp> createState() => _LogoAppState();
}
// #docregion print-state
class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin {
late Animation<double> animation;
late AnimationController controller;
@override
void initState() {
super.initState();
controller =
AnimationController(duration: const Duration(seconds: 2), vsync: this);
animation = Tween<double>(begin: 0, end: 300).animate(controller);
controller.forward();
}
// #enddocregion print-state
@override
Widget build(BuildContext context) {
return GrowTransition(
animation: animation,
child: const LogoWidget(),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
// #docregion print-state
}
| website/examples/animation/animate4/lib/main.dart/0 | {
"file_path": "website/examples/animation/animate4/lib/main.dart",
"repo_id": "website",
"token_count": 684
} | 1,250 |
import 'package:flutter/material.dart';
// ignore_for_file: prefer_final_fields
// ignore_for_file: unused_field
// #docregion Starter
// The StatefulWidget's job is to take data and create a State class.
// In this case, the widget takes a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
super.key,
required this.title,
});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
// The State class is responsible for two things: holding some data you can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
// Whether the green box should be visible.
bool _visible = true;
@override
Widget build(BuildContext context) {
// The green box goes here with some other Widgets.
return Container();
}
}
// #enddocregion Starter
| website/examples/cookbook/animation/opacity_animation/lib/starter.dart/0 | {
"file_path": "website/examples/cookbook/animation/opacity_animation/lib/starter.dart",
"repo_id": "website",
"token_count": 264
} | 1,251 |
name: drawer
description: Sample code for drawer cookbook recipe.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/design/drawer/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/design/drawer/pubspec.yaml",
"repo_id": "website",
"token_count": 89
} | 1,252 |
import 'package:flutter/material.dart';
// #docregion VisualStates
enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.transitionDuration = const Duration(
milliseconds: 500,
),
});
final DownloadStatus status;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
// TODO: We'll add more to this later.
return const SizedBox();
}
}
// #enddocregion VisualStates
| website/examples/cookbook/effects/download_button/lib/visual_states.dart/0 | {
"file_path": "website/examples/cookbook/effects/download_button/lib/visual_states.dart",
"repo_id": "website",
"token_count": 185
} | 1,253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.