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:html';
/// Create anchor element with download attribute
AnchorElement createAnchorElement(String href, String? suggestedName) {
final AnchorElement element = AnchorElement(href: href);
if (suggestedName == null) {
element.download = 'download';
} else {
element.download = suggestedName;
}
return element;
}
/// Add an element to a container and click it
void addElementToContainerAndClick(Element container, Element element) {
// Add the element and click it
// All previous elements will be removed before adding the new one
container.children.add(element);
element.click();
}
/// Initializes a DOM container where we can host elements.
Element ensureInitialized(String id) {
Element? target = querySelector('#$id');
if (target == null) {
final Element targetElement = Element.tag('flt-x-file')..id = id;
querySelector('body')!.children.add(targetElement);
target = targetElement;
}
return target;
}
| plugins/packages/file_selector/file_selector_platform_interface/lib/src/web_helpers/web_helpers.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_platform_interface/lib/src/web_helpers/web_helpers.dart",
"repo_id": "plugins",
"token_count": 319
} | 1,220 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "test/test_utils.h"
#include <shobjidl.h>
#include <windows.h>
#include <string>
namespace file_selector_windows {
namespace test {
namespace {
// Creates a temp file and returns its path.
std::wstring CreateTempFile() {
wchar_t temp_dir[MAX_PATH];
wchar_t temp_file[MAX_PATH];
wchar_t long_path[MAX_PATH];
::GetTempPath(MAX_PATH, temp_dir);
::GetTempFileName(temp_dir, L"test", 0, temp_file);
// Convert to long form to match what IShellItem queries will return.
::GetLongPathName(temp_file, long_path, MAX_PATH);
return long_path;
}
} // namespace
ScopedTestShellItem::ScopedTestShellItem() {
path_ = CreateTempFile();
::SHCreateItemFromParsingName(path_.c_str(), nullptr, IID_PPV_ARGS(&item_));
}
ScopedTestShellItem::~ScopedTestShellItem() { ::DeleteFile(path_.c_str()); }
ScopedTestFileIdList::ScopedTestFileIdList() {
path_ = CreateTempFile();
item_ = ItemIdListPtr(::ILCreateFromPath(path_.c_str()));
}
ScopedTestFileIdList::~ScopedTestFileIdList() { ::DeleteFile(path_.c_str()); }
} // namespace test
} // namespace file_selector_windows
| plugins/packages/file_selector/file_selector_windows/windows/test/test_utils.cpp/0 | {
"file_path": "plugins/packages/file_selector/file_selector_windows/windows/test/test_utils.cpp",
"repo_id": "plugins",
"token_count": 439
} | 1,221 |
rootProject.name = 'google_maps_flutter_android'
| plugins/packages/google_maps_flutter/google_maps_flutter_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 16
} | 1,222 |
name: google_maps_flutter_android
description: Android implementation of the google_maps_flutter plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/google_maps_flutter/google_maps_flutter_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22
version: 2.4.5
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: google_maps_flutter
platforms:
android:
package: io.flutter.plugins.googlemaps
pluginClass: GoogleMapsPlugin
dartPluginClass: GoogleMapsFlutterAndroid
dependencies:
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.1
google_maps_flutter_platform_interface: ^2.2.1
stream_transform: ^2.0.0
dev_dependencies:
async: ^2.5.0
flutter_test:
sdk: flutter
plugin_platform_interface: ^2.0.0
| plugins/packages/google_maps_flutter/google_maps_flutter_android/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/pubspec.yaml",
"repo_id": "plugins",
"token_count": 357
} | 1,223 |
// 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 "FLTGoogleMapTileOverlayController.h"
#import "FLTGoogleMapJSONConversions.h"
@interface FLTGoogleMapTileOverlayController ()
@property(strong, nonatomic) GMSTileLayer *layer;
@property(weak, nonatomic) GMSMapView *mapView;
@end
@implementation FLTGoogleMapTileOverlayController
- (instancetype)initWithTileLayer:(GMSTileLayer *)tileLayer
mapView:(GMSMapView *)mapView
options:(NSDictionary *)optionsData {
self = [super init];
if (self) {
_layer = tileLayer;
_mapView = mapView;
[self interpretTileOverlayOptions:optionsData];
}
return self;
}
- (void)removeTileOverlay {
self.layer.map = nil;
}
- (void)clearTileCache {
[self.layer clearTileCache];
}
- (NSDictionary *)getTileOverlayInfo {
NSMutableDictionary *info = [[NSMutableDictionary alloc] init];
BOOL visible = self.layer.map != nil;
info[@"visible"] = @(visible);
info[@"fadeIn"] = @(self.layer.fadeIn);
float transparency = 1.0 - self.layer.opacity;
info[@"transparency"] = @(transparency);
info[@"zIndex"] = @(self.layer.zIndex);
return info;
}
- (void)setFadeIn:(BOOL)fadeIn {
self.layer.fadeIn = fadeIn;
}
- (void)setTransparency:(float)transparency {
float opacity = 1.0 - transparency;
self.layer.opacity = opacity;
}
- (void)setVisible:(BOOL)visible {
self.layer.map = visible ? self.mapView : nil;
}
- (void)setZIndex:(int)zIndex {
self.layer.zIndex = zIndex;
}
- (void)setTileSize:(NSInteger)tileSize {
self.layer.tileSize = tileSize;
}
- (void)interpretTileOverlayOptions:(NSDictionary *)data {
if (!data) {
return;
}
NSNumber *visible = data[@"visible"];
if (visible != nil && visible != (id)[NSNull null]) {
[self setVisible:visible.boolValue];
}
NSNumber *transparency = data[@"transparency"];
if (transparency != nil && transparency != (id)[NSNull null]) {
[self setTransparency:transparency.floatValue];
}
NSNumber *zIndex = data[@"zIndex"];
if (zIndex != nil && zIndex != (id)[NSNull null]) {
[self setZIndex:zIndex.intValue];
}
NSNumber *fadeIn = data[@"fadeIn"];
if (fadeIn != nil && fadeIn != (id)[NSNull null]) {
[self setFadeIn:fadeIn.boolValue];
}
NSNumber *tileSize = data[@"tileSize"];
if (tileSize != nil && tileSize != (id)[NSNull null]) {
[self setTileSize:tileSize.integerValue];
}
}
@end
@interface FLTTileProviderController ()
@property(strong, nonatomic) FlutterMethodChannel *methodChannel;
@end
@implementation FLTTileProviderController
- (instancetype)init:(FlutterMethodChannel *)methodChannel
withTileOverlayIdentifier:(NSString *)identifier {
self = [super init];
if (self) {
_methodChannel = methodChannel;
_tileOverlayIdentifier = identifier;
}
return self;
}
#pragma mark - GMSTileLayer method
- (void)requestTileForX:(NSUInteger)x
y:(NSUInteger)y
zoom:(NSUInteger)zoom
receiver:(id<GMSTileReceiver>)receiver {
[self.methodChannel
invokeMethod:@"tileOverlay#getTile"
arguments:@{
@"tileOverlayId" : self.tileOverlayIdentifier,
@"x" : @(x),
@"y" : @(y),
@"zoom" : @(zoom)
}
result:^(id _Nullable result) {
UIImage *tileImage;
if ([result isKindOfClass:[NSDictionary class]]) {
FlutterStandardTypedData *typedData = (FlutterStandardTypedData *)result[@"data"];
if (typedData == nil) {
tileImage = kGMSTileLayerNoTile;
} else {
tileImage = [UIImage imageWithData:typedData.data];
}
} else {
if ([result isKindOfClass:[FlutterError class]]) {
FlutterError *error = (FlutterError *)result;
NSLog(@"Can't get tile: errorCode = %@, errorMessage = %@, details = %@",
[error code], [error message], [error details]);
}
if ([result isKindOfClass:[FlutterMethodNotImplemented class]]) {
NSLog(@"Can't get tile: notImplemented");
}
tileImage = kGMSTileLayerNoTile;
}
[receiver receiveTileWithX:x y:y zoom:zoom image:tileImage];
}];
}
@end
@interface FLTTileOverlaysController ()
@property(strong, nonatomic) NSMutableDictionary *tileOverlayIdentifierToController;
@property(strong, nonatomic) FlutterMethodChannel *methodChannel;
@property(weak, nonatomic) GMSMapView *mapView;
@end
@implementation FLTTileOverlaysController
- (instancetype)init:(FlutterMethodChannel *)methodChannel
mapView:(GMSMapView *)mapView
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
if (self) {
_methodChannel = methodChannel;
_mapView = mapView;
_tileOverlayIdentifierToController = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)addTileOverlays:(NSArray *)tileOverlaysToAdd {
for (NSDictionary *tileOverlay in tileOverlaysToAdd) {
NSString *identifier = [FLTTileOverlaysController identifierForTileOverlay:tileOverlay];
FLTTileProviderController *tileProvider =
[[FLTTileProviderController alloc] init:self.methodChannel
withTileOverlayIdentifier:identifier];
FLTGoogleMapTileOverlayController *controller =
[[FLTGoogleMapTileOverlayController alloc] initWithTileLayer:tileProvider
mapView:self.mapView
options:tileOverlay];
self.tileOverlayIdentifierToController[identifier] = controller;
}
}
- (void)changeTileOverlays:(NSArray *)tileOverlaysToChange {
for (NSDictionary *tileOverlay in tileOverlaysToChange) {
NSString *identifier = [FLTTileOverlaysController identifierForTileOverlay:tileOverlay];
FLTGoogleMapTileOverlayController *controller =
self.tileOverlayIdentifierToController[identifier];
if (!controller) {
continue;
}
[controller interpretTileOverlayOptions:tileOverlay];
}
}
- (void)removeTileOverlayWithIdentifiers:(NSArray *)identifiers {
for (NSString *identifier in identifiers) {
FLTGoogleMapTileOverlayController *controller =
self.tileOverlayIdentifierToController[identifier];
if (!controller) {
continue;
}
[controller removeTileOverlay];
[self.tileOverlayIdentifierToController removeObjectForKey:identifier];
}
}
- (void)clearTileCacheWithIdentifier:(NSString *)identifier {
FLTGoogleMapTileOverlayController *controller =
self.tileOverlayIdentifierToController[identifier];
if (!controller) {
return;
}
[controller clearTileCache];
}
- (nullable NSDictionary *)tileOverlayInfoWithIdentifier:(NSString *)identifier {
if (self.tileOverlayIdentifierToController[identifier] == nil) {
return nil;
}
return [self.tileOverlayIdentifierToController[identifier] getTileOverlayInfo];
}
+ (NSString *)identifierForTileOverlay:(NSDictionary *)tileOverlay {
return tileOverlay[@"tileOverlayId"];
}
@end
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapTileOverlayController.m/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapTileOverlayController.m",
"repo_id": "plugins",
"token_count": 2967
} | 1,224 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'google_maps_flutter_ios'
s.version = '0.0.1'
s.summary = 'Google Maps for Flutter'
s.description = <<-DESC
A Flutter plugin that provides a Google Maps widget.
Downloaded by pub (not CocoaPods).
DESC
s.homepage = 'https://github.com/flutter/plugins'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/google_maps_flutter/google_maps_flutter/ios' }
s.documentation_url = 'https://pub.dev/packages/google_maps_flutter_ios'
s.source_files = 'Classes/**/*.{h,m}'
s.public_header_files = 'Classes/**/*.h'
s.module_map = 'Classes/google_maps_flutter_ios.modulemap'
s.dependency 'Flutter'
s.dependency 'GoogleMaps'
s.static_framework = true
s.platform = :ios, '9.0'
# GoogleMaps does not support arm64 simulators.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
end
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/google_maps_flutter_ios.podspec/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/google_maps_flutter_ios.podspec",
"repo_id": "plugins",
"token_count": 527
} | 1,225 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'types.dart';
/// Callback that receives updates to the camera position.
///
/// This callback is triggered when the platform Google Map
/// registers a camera movement.
///
/// This is used in [GoogleMap.onCameraMove].
typedef CameraPositionCallback = void Function(CameraPosition position);
/// Callback function taking a single argument.
typedef ArgumentCallback<T> = void Function(T argument);
/// Mutable collection of [ArgumentCallback] instances, itself an [ArgumentCallback].
///
/// Additions and removals happening during a single [call] invocation do not
/// change who gets a callback until the next such invocation.
///
/// Optimized for the singleton case.
class ArgumentCallbacks<T> {
final List<ArgumentCallback<T>> _callbacks = <ArgumentCallback<T>>[];
/// Callback method. Invokes the corresponding method on each callback
/// in this collection.
///
/// The list of callbacks being invoked is computed at the start of the
/// method and is unaffected by any changes subsequently made to this
/// collection.
void call(T argument) {
final int length = _callbacks.length;
if (length == 1) {
_callbacks[0].call(argument);
} else if (0 < length) {
for (final ArgumentCallback<T> callback
in List<ArgumentCallback<T>>.from(_callbacks)) {
callback(argument);
}
}
}
/// Adds a callback to this collection.
void add(ArgumentCallback<T> callback) {
assert(callback != null);
_callbacks.add(callback);
}
/// Removes a callback from this collection.
///
/// Does nothing, if the callback was not present.
void remove(ArgumentCallback<T> callback) {
_callbacks.remove(callback);
}
/// Whether this collection is empty.
bool get isEmpty => _callbacks.isEmpty;
/// Whether this collection is non-empty.
bool get isNotEmpty => _callbacks.isNotEmpty;
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/callbacks.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/callbacks.dart",
"repo_id": "plugins",
"token_count": 589
} | 1,226 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'types.dart';
/// [Polygon] update events to be applied to the [GoogleMap].
///
/// Used in [GoogleMapController] when the map is updated.
// (Do not re-export)
class PolygonUpdates extends MapsObjectUpdates<Polygon> {
/// Computes [PolygonUpdates] given previous and current [Polygon]s.
PolygonUpdates.from(Set<Polygon> previous, Set<Polygon> current)
: super.from(previous, current, objectName: 'polygon');
/// Set of Polygons to be added in this update.
Set<Polygon> get polygonsToAdd => objectsToAdd;
/// Set of PolygonIds to be removed in this update.
Set<PolygonId> get polygonIdsToRemove => objectIdsToRemove.cast<PolygonId>();
/// Set of Polygons to be changed in this update.
Set<Polygon> get polygonsToChange => objectsToChange;
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon_updates.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon_updates.dart",
"repo_id": "plugins",
"token_count": 288
} | 1,227 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:google_maps_flutter_platform_interface/src/types/utils/map_configuration_serialization.dart';
void main() {
test('empty serialization', () async {
const MapConfiguration config = MapConfiguration();
final Map<String, Object> json = jsonForMapConfiguration(config);
expect(json.isEmpty, true);
});
test('complete serialization', () async {
final MapConfiguration config = MapConfiguration(
compassEnabled: false,
mapToolbarEnabled: false,
cameraTargetBounds: CameraTargetBounds(LatLngBounds(
northeast: const LatLng(30, 20), southwest: const LatLng(10, 40))),
mapType: MapType.normal,
minMaxZoomPreference: const MinMaxZoomPreference(1.0, 10.0),
rotateGesturesEnabled: false,
scrollGesturesEnabled: false,
tiltGesturesEnabled: false,
trackCameraPosition: false,
zoomControlsEnabled: false,
zoomGesturesEnabled: false,
liteModeEnabled: false,
myLocationEnabled: false,
myLocationButtonEnabled: false,
padding: const EdgeInsets.all(5.0),
indoorViewEnabled: false,
trafficEnabled: false,
buildingsEnabled: false,
);
final Map<String, Object> json = jsonForMapConfiguration(config);
// This uses literals instead of toJson() for the expectations on
// sub-objects, because if the serialization of any of those objects were
// ever to change MapConfiguration would need to update to serialize those
// objects manually to preserve the format, in order to avoid breaking
// implementations.
expect(json, <String, Object>{
'compassEnabled': false,
'mapToolbarEnabled': false,
'cameraTargetBounds': <Object>[
<Object>[
<double>[10.0, 40.0],
<double>[30.0, 20.0]
]
],
'mapType': 1,
'minMaxZoomPreference': <double>[1.0, 10.0],
'rotateGesturesEnabled': false,
'scrollGesturesEnabled': false,
'tiltGesturesEnabled': false,
'zoomControlsEnabled': false,
'zoomGesturesEnabled': false,
'liteModeEnabled': false,
'trackCameraPosition': false,
'myLocationEnabled': false,
'myLocationButtonEnabled': false,
'padding': <double>[5.0, 5.0, 5.0, 5.0],
'indoorEnabled': false,
'trafficEnabled': false,
'buildingsEnabled': false
});
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/map_configuration_serialization_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/map_configuration_serialization_test.dart",
"repo_id": "plugins",
"token_count": 993
} | 1,228 |
// 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 'dart:ui';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps/google_maps_geometry.dart' as geometry;
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';
// This value is used when comparing the results of
// converting from a byte value to a double between 0 and 1.
// (For Color opacity values, for example)
const double _acceptableDelta = 0.01;
/// Test Shapes (Circle, Polygon, Polyline)
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
late gmaps.GMap map;
setUp(() {
map = gmaps.GMap(html.DivElement());
});
group('CirclesController', () {
late StreamController<MapEvent<Object?>> events;
late CirclesController controller;
setUp(() {
events = StreamController<MapEvent<Object?>>();
controller = CirclesController(stream: events);
controller.bindToMap(123, map);
});
testWidgets('addCircles', (WidgetTester tester) async {
final Set<Circle> circles = <Circle>{
const Circle(circleId: CircleId('1')),
const Circle(circleId: CircleId('2')),
};
controller.addCircles(circles);
expect(controller.circles.length, 2);
expect(controller.circles, contains(const CircleId('1')));
expect(controller.circles, contains(const CircleId('2')));
expect(controller.circles, isNot(contains(const CircleId('66'))));
});
testWidgets('changeCircles', (WidgetTester tester) async {
final Set<Circle> circles = <Circle>{
const Circle(circleId: CircleId('1')),
};
controller.addCircles(circles);
expect(controller.circles[const CircleId('1')]?.circle?.visible, isTrue);
final Set<Circle> updatedCircles = <Circle>{
const Circle(circleId: CircleId('1'), visible: false),
};
controller.changeCircles(updatedCircles);
expect(controller.circles.length, 1);
expect(controller.circles[const CircleId('1')]?.circle?.visible, isFalse);
});
testWidgets('removeCircles', (WidgetTester tester) async {
final Set<Circle> circles = <Circle>{
const Circle(circleId: CircleId('1')),
const Circle(circleId: CircleId('2')),
const Circle(circleId: CircleId('3')),
};
controller.addCircles(circles);
expect(controller.circles.length, 3);
// Remove some circles...
final Set<CircleId> circleIdsToRemove = <CircleId>{
const CircleId('1'),
const CircleId('3'),
};
controller.removeCircles(circleIdsToRemove);
expect(controller.circles.length, 1);
expect(controller.circles, isNot(contains(const CircleId('1'))));
expect(controller.circles, contains(const CircleId('2')));
expect(controller.circles, isNot(contains(const CircleId('3'))));
});
testWidgets('Converts colors to CSS', (WidgetTester tester) async {
final Set<Circle> circles = <Circle>{
const Circle(
circleId: CircleId('1'),
fillColor: Color(0x7FFABADA),
strokeColor: Color(0xFFC0FFEE),
),
};
controller.addCircles(circles);
final gmaps.Circle circle = controller.circles.values.first.circle!;
expect(circle.get('fillColor'), '#fabada');
expect(circle.get('fillOpacity'), closeTo(0.5, _acceptableDelta));
expect(circle.get('strokeColor'), '#c0ffee');
expect(circle.get('strokeOpacity'), closeTo(1, _acceptableDelta));
});
});
group('PolygonsController', () {
late StreamController<MapEvent<Object?>> events;
late PolygonsController controller;
setUp(() {
events = StreamController<MapEvent<Object?>>();
controller = PolygonsController(stream: events);
controller.bindToMap(123, map);
});
testWidgets('addPolygons', (WidgetTester tester) async {
final Set<Polygon> polygons = <Polygon>{
const Polygon(polygonId: PolygonId('1')),
const Polygon(polygonId: PolygonId('2')),
};
controller.addPolygons(polygons);
expect(controller.polygons.length, 2);
expect(controller.polygons, contains(const PolygonId('1')));
expect(controller.polygons, contains(const PolygonId('2')));
expect(controller.polygons, isNot(contains(const PolygonId('66'))));
});
testWidgets('changePolygons', (WidgetTester tester) async {
final Set<Polygon> polygons = <Polygon>{
const Polygon(polygonId: PolygonId('1')),
};
controller.addPolygons(polygons);
expect(
controller.polygons[const PolygonId('1')]?.polygon?.visible, isTrue);
// Update the polygon
final Set<Polygon> updatedPolygons = <Polygon>{
const Polygon(polygonId: PolygonId('1'), visible: false),
};
controller.changePolygons(updatedPolygons);
expect(controller.polygons.length, 1);
expect(
controller.polygons[const PolygonId('1')]?.polygon?.visible, isFalse);
});
testWidgets('removePolygons', (WidgetTester tester) async {
final Set<Polygon> polygons = <Polygon>{
const Polygon(polygonId: PolygonId('1')),
const Polygon(polygonId: PolygonId('2')),
const Polygon(polygonId: PolygonId('3')),
};
controller.addPolygons(polygons);
expect(controller.polygons.length, 3);
// Remove some polygons...
final Set<PolygonId> polygonIdsToRemove = <PolygonId>{
const PolygonId('1'),
const PolygonId('3'),
};
controller.removePolygons(polygonIdsToRemove);
expect(controller.polygons.length, 1);
expect(controller.polygons, isNot(contains(const PolygonId('1'))));
expect(controller.polygons, contains(const PolygonId('2')));
expect(controller.polygons, isNot(contains(const PolygonId('3'))));
});
testWidgets('Converts colors to CSS', (WidgetTester tester) async {
final Set<Polygon> polygons = <Polygon>{
const Polygon(
polygonId: PolygonId('1'),
fillColor: Color(0x7FFABADA),
strokeColor: Color(0xFFC0FFEE),
),
};
controller.addPolygons(polygons);
final gmaps.Polygon polygon = controller.polygons.values.first.polygon!;
expect(polygon.get('fillColor'), '#fabada');
expect(polygon.get('fillOpacity'), closeTo(0.5, _acceptableDelta));
expect(polygon.get('strokeColor'), '#c0ffee');
expect(polygon.get('strokeOpacity'), closeTo(1, _acceptableDelta));
});
testWidgets('Handle Polygons with holes', (WidgetTester tester) async {
final Set<Polygon> polygons = <Polygon>{
const Polygon(
polygonId: PolygonId('BermudaTriangle'),
points: <LatLng>[
LatLng(25.774, -80.19),
LatLng(18.466, -66.118),
LatLng(32.321, -64.757),
],
holes: <List<LatLng>>[
<LatLng>[
LatLng(28.745, -70.579),
LatLng(29.57, -67.514),
LatLng(27.339, -66.668),
],
],
),
};
controller.addPolygons(polygons);
expect(controller.polygons.length, 1);
expect(controller.polygons, contains(const PolygonId('BermudaTriangle')));
expect(controller.polygons, isNot(contains(const PolygonId('66'))));
});
testWidgets('Polygon with hole has a hole', (WidgetTester tester) async {
final Set<Polygon> polygons = <Polygon>{
const Polygon(
polygonId: PolygonId('BermudaTriangle'),
points: <LatLng>[
LatLng(25.774, -80.19),
LatLng(18.466, -66.118),
LatLng(32.321, -64.757),
],
holes: <List<LatLng>>[
<LatLng>[
LatLng(28.745, -70.579),
LatLng(29.57, -67.514),
LatLng(27.339, -66.668),
],
],
),
};
controller.addPolygons(polygons);
final gmaps.Polygon? polygon = controller.polygons.values.first.polygon;
final gmaps.LatLng pointInHole = gmaps.LatLng(28.632, -68.401);
expect(geometry.Poly.containsLocation(pointInHole, polygon), false);
});
testWidgets('Hole Path gets reversed to display correctly',
(WidgetTester tester) async {
final Set<Polygon> polygons = <Polygon>{
const Polygon(
polygonId: PolygonId('BermudaTriangle'),
points: <LatLng>[
LatLng(25.774, -80.19),
LatLng(18.466, -66.118),
LatLng(32.321, -64.757),
],
holes: <List<LatLng>>[
<LatLng>[
LatLng(27.339, -66.668),
LatLng(29.57, -67.514),
LatLng(28.745, -70.579),
],
],
),
};
controller.addPolygons(polygons);
final gmaps.MVCArray<gmaps.MVCArray<gmaps.LatLng?>?> paths =
controller.polygons.values.first.polygon!.paths!;
expect(paths.getAt(1)?.getAt(0)?.lat, 28.745);
expect(paths.getAt(1)?.getAt(1)?.lat, 29.57);
expect(paths.getAt(1)?.getAt(2)?.lat, 27.339);
});
});
group('PolylinesController', () {
late StreamController<MapEvent<Object?>> events;
late PolylinesController controller;
setUp(() {
events = StreamController<MapEvent<Object?>>();
controller = PolylinesController(stream: events);
controller.bindToMap(123, map);
});
testWidgets('addPolylines', (WidgetTester tester) async {
final Set<Polyline> polylines = <Polyline>{
const Polyline(polylineId: PolylineId('1')),
const Polyline(polylineId: PolylineId('2')),
};
controller.addPolylines(polylines);
expect(controller.lines.length, 2);
expect(controller.lines, contains(const PolylineId('1')));
expect(controller.lines, contains(const PolylineId('2')));
expect(controller.lines, isNot(contains(const PolylineId('66'))));
});
testWidgets('changePolylines', (WidgetTester tester) async {
final Set<Polyline> polylines = <Polyline>{
const Polyline(polylineId: PolylineId('1')),
};
controller.addPolylines(polylines);
expect(controller.lines[const PolylineId('1')]?.line?.visible, isTrue);
final Set<Polyline> updatedPolylines = <Polyline>{
const Polyline(polylineId: PolylineId('1'), visible: false),
};
controller.changePolylines(updatedPolylines);
expect(controller.lines.length, 1);
expect(controller.lines[const PolylineId('1')]?.line?.visible, isFalse);
});
testWidgets('removePolylines', (WidgetTester tester) async {
final Set<Polyline> polylines = <Polyline>{
const Polyline(polylineId: PolylineId('1')),
const Polyline(polylineId: PolylineId('2')),
const Polyline(polylineId: PolylineId('3')),
};
controller.addPolylines(polylines);
expect(controller.lines.length, 3);
// Remove some polylines...
final Set<PolylineId> polylineIdsToRemove = <PolylineId>{
const PolylineId('1'),
const PolylineId('3'),
};
controller.removePolylines(polylineIdsToRemove);
expect(controller.lines.length, 1);
expect(controller.lines, isNot(contains(const PolylineId('1'))));
expect(controller.lines, contains(const PolylineId('2')));
expect(controller.lines, isNot(contains(const PolylineId('3'))));
});
testWidgets('Converts colors to CSS', (WidgetTester tester) async {
final Set<Polyline> lines = <Polyline>{
const Polyline(
polylineId: PolylineId('1'),
color: Color(0x7FFABADA),
),
};
controller.addPolylines(lines);
final gmaps.Polyline line = controller.lines.values.first.line!;
expect(line.get('strokeColor'), '#fabada');
expect(line.get('strokeOpacity'), closeTo(0.5, _acceptableDelta));
});
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart",
"repo_id": "plugins",
"token_count": 5242
} | 1,229 |
// 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.
part of google_maps_flutter_web;
/// This class manages a set of [PolygonController]s associated to a [GoogleMapController].
class PolygonsController extends GeometryController {
/// Initializes the cache. The [StreamController] comes from the [GoogleMapController], and is shared with other controllers.
PolygonsController({
required StreamController<MapEvent<Object?>> stream,
}) : _streamController = stream,
_polygonIdToController = <PolygonId, PolygonController>{};
// A cache of [PolygonController]s indexed by their [PolygonId].
final Map<PolygonId, PolygonController> _polygonIdToController;
// The stream over which polygons broadcast events
final StreamController<MapEvent<Object?>> _streamController;
/// Returns the cache of [PolygonController]s. Test only.
@visibleForTesting
Map<PolygonId, PolygonController> get polygons => _polygonIdToController;
/// Adds a set of [Polygon] objects to the cache.
///
/// Wraps each Polygon into its corresponding [PolygonController].
void addPolygons(Set<Polygon> polygonsToAdd) {
if (polygonsToAdd != null) {
polygonsToAdd.forEach(_addPolygon);
}
}
void _addPolygon(Polygon polygon) {
if (polygon == null) {
return;
}
final gmaps.PolygonOptions polygonOptions =
_polygonOptionsFromPolygon(googleMap, polygon);
final gmaps.Polygon gmPolygon = gmaps.Polygon(polygonOptions)
..map = googleMap;
final PolygonController controller = PolygonController(
polygon: gmPolygon,
consumeTapEvents: polygon.consumeTapEvents,
onTap: () {
_onPolygonTap(polygon.polygonId);
});
_polygonIdToController[polygon.polygonId] = controller;
}
/// Updates a set of [Polygon] objects with new options.
void changePolygons(Set<Polygon> polygonsToChange) {
if (polygonsToChange != null) {
polygonsToChange.forEach(_changePolygon);
}
}
void _changePolygon(Polygon polygon) {
final PolygonController? polygonController =
_polygonIdToController[polygon.polygonId];
polygonController?.update(_polygonOptionsFromPolygon(googleMap, polygon));
}
/// Removes a set of [PolygonId]s from the cache.
void removePolygons(Set<PolygonId> polygonIdsToRemove) {
polygonIdsToRemove.forEach(_removePolygon);
}
// Removes a polygon and its controller by its [PolygonId].
void _removePolygon(PolygonId polygonId) {
final PolygonController? polygonController =
_polygonIdToController[polygonId];
polygonController?.remove();
_polygonIdToController.remove(polygonId);
}
// Handle internal events
bool _onPolygonTap(PolygonId polygonId) {
// Have you ended here on your debugging? Is this wrong?
// Comment here: https://github.com/flutter/flutter/issues/64084
_streamController.add(PolygonTapEvent(mapId, polygonId));
return _polygonIdToController[polygonId]?.consumeTapEvents ?? false;
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygons.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygons.dart",
"repo_id": "plugins",
"token_count": 1042
} | 1,230 |
[](https://pub.dev/packages/google_sign_in)
A Flutter plugin for [Google Sign In](https://developers.google.com/identity/).
_Note_: This plugin is still under development, and some APIs might not be
available yet. [Feedback](https://github.com/flutter/flutter/issues) and
[Pull Requests](https://github.com/flutter/plugins/pulls) are most welcome!
| | Android | iOS | Web |
|-------------|---------|--------|-----|
| **Support** | SDK 16+ | iOS 9+ | Any |
## Platform integration
### Android integration
To access Google Sign-In, you'll need to make sure to
[register your application](https://firebase.google.com/docs/android/setup).
You don't need to include the google-services.json file in your app unless you
are using Google services that require it. You do need to enable the OAuth APIs
that you want, using the
[Google Cloud Platform API manager](https://console.developers.google.com/). For
example, if you want to mimic the behavior of the Google Sign-In sample app,
you'll need to enable the
[Google People API](https://developers.google.com/people/).
Make sure you've filled out all required fields in the console for
[OAuth consent screen](https://console.developers.google.com/apis/credentials/consent).
Otherwise, you may encounter `APIException` errors.
### iOS integration
This plugin requires iOS 9.0 or higher.
1. [First register your application](https://firebase.google.com/docs/ios/setup).
2. Make sure the file you download in step 1 is named
`GoogleService-Info.plist`.
3. Move or copy `GoogleService-Info.plist` into the `[my_project]/ios/Runner`
directory.
4. Open Xcode, then right-click on `Runner` directory and select
`Add Files to "Runner"`.
5. Select `GoogleService-Info.plist` from the file manager.
6. A dialog will show up and ask you to select the targets, select the `Runner`
target.
7. If you need to authenticate to a backend server you can add a
`SERVER_CLIENT_ID` key value pair in your `GoogleService-Info.plist`.
```xml
<key>SERVER_CLIENT_ID</key>
<string>[YOUR SERVER CLIENT ID]</string>
```
8. Then add the `CFBundleURLTypes` attributes below into the
`[my_project]/ios/Runner/Info.plist` file.
```xml
<!-- Put me in the [my_project]/ios/Runner/Info.plist file -->
<!-- Google Sign-in Section -->
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<!-- TODO Replace this value: -->
<!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID -->
<string>com.googleusercontent.apps.861823949799-vc35cprkp249096uujjn0vvnmcvjppkn</string>
</array>
</dict>
</array>
<!-- End of the Google Sign-in Section -->
```
As an alternative to adding `GoogleService-Info.plist` to your Xcode project,
you can instead configure your app in Dart code. In this case, skip steps 3 to 7
and pass `clientId` and `serverClientId` to the `GoogleSignIn` constructor:
```dart
GoogleSignIn _googleSignIn = GoogleSignIn(
...
// The OAuth client id of your app. This is required.
clientId: ...,
// If you need to authenticate to a backend server, specify its OAuth client. This is optional.
serverClientId: ...,
);
```
Note that step 8 is still required.
#### iOS additional requirement
Note that according to
https://developer.apple.com/sign-in-with-apple/get-started, starting June 30,
2020, apps that use login services must also offer a "Sign in with Apple" option
when submitting to the Apple App Store.
Consider also using an Apple sign in plugin from pub.dev.
The Flutter Favorite
[sign_in_with_apple](https://pub.dev/packages/sign_in_with_apple) plugin could
be an option.
### Web integration
For web integration details, see the
[`google_sign_in_web` package](https://pub.dev/packages/google_sign_in_web).
## Usage
### Import the package
To use this plugin, follow the
[plugin installation instructions](https://pub.dev/packages/google_sign_in/install).
### Use the plugin
Add the following import to your Dart code:
```dart
import 'package:google_sign_in/google_sign_in.dart';
```
Initialize GoogleSignIn with the scopes you want:
```dart
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
```
[Full list of available scopes](https://developers.google.com/identity/protocols/googlescopes).
You can now use the `GoogleSignIn` class to authenticate in your Dart code, e.g.
```dart
Future<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error);
}
}
```
## Example
Find the example wiring in the
[Google sign-in example application](https://github.com/flutter/plugins/blob/main/packages/google_sign_in/google_sign_in/example/lib/main.dart).
| plugins/packages/google_sign_in/google_sign_in/README.md/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/README.md",
"repo_id": "plugins",
"token_count": 1572
} | 1,231 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_web_client_id">YOUR_WEB_CLIENT_ID</string>
</resources>
| plugins/packages/google_sign_in/google_sign_in/example/android/app/src/main/res/values/strings.xml/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/example/android/app/src/main/res/values/strings.xml",
"repo_id": "plugins",
"token_count": 53
} | 1,232 |
`transparentImage.gif` is a 1x1 transparent gif which comes from [this wikimedia page](https://commons.wikimedia.org/wiki/File:Transparent.gif):

This is the image used a placeholder for the `GoogleCircleAvatar` widget.
The variable `_transparentImage` in `lib/widgets.dart` is the list of bytes of `transparentImage.gif`. | plugins/packages/google_sign_in/google_sign_in/resources/README.md/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/resources/README.md",
"repo_id": "plugins",
"token_count": 106
} | 1,233 |
// 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.googlesignin;
import android.app.Activity;
import android.content.Context;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.Scope;
/**
* A wrapper object that calls static method in GoogleSignIn.
*
* <p>Because GoogleSignIn uses static method mostly, which is hard for unit testing. We use this
* wrapper class to use instance method which calls the corresponding GoogleSignIn static methods.
*
* <p>Warning! This class should stay true that each method calls a GoogleSignIn static method with
* the same name and same parameters.
*/
public class GoogleSignInWrapper {
GoogleSignInClient getClient(Context context, GoogleSignInOptions options) {
return GoogleSignIn.getClient(context, options);
}
GoogleSignInAccount getLastSignedInAccount(Context context) {
return GoogleSignIn.getLastSignedInAccount(context);
}
boolean hasPermissions(GoogleSignInAccount account, Scope scope) {
return GoogleSignIn.hasPermissions(account, scope);
}
void requestPermissions(
Activity activity, int requestCode, GoogleSignInAccount account, Scope[] scopes) {
GoogleSignIn.requestPermissions(activity, requestCode, account, scopes);
}
}
| plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/GoogleSignInWrapper.java/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/GoogleSignInWrapper.java",
"repo_id": "plugins",
"token_count": 460
} | 1,234 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 5.5.1
* Fixes passing `serverClientId` via the channelled `init` call
* Updates minimum Flutter version to 2.10.
## 5.5.0
* Adds override for `GoogleSignInPlatform.initWithParams`.
## 5.4.0
* Adds support for `serverClientId` configuration option.
* Makes `Google-Services.info` file optional.
## 5.3.1
* Suppresses warnings for pre-iOS-13 codepaths.
## 5.3.0
* Supports arm64 iOS simulators by increasing GoogleSignIn dependency to version 6.2.
## 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_ios/CHANGELOG.md/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 267
} | 1,235 |
// 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 header is available in the Test module. Import via "@import google_sign_in.Test;"
#import <google_sign_in_ios/FLTGoogleSignInPlugin.h>
NS_ASSUME_NONNULL_BEGIN
@class GIDSignIn;
/// Methods exposed for unit testing.
@interface FLTGoogleSignInPlugin ()
/// Inject @c GIDSignIn for testing.
- (instancetype)initWithSignIn:(GIDSignIn *)signIn;
/// Inject @c GIDSignIn and @c googleServiceProperties for testing.
- (instancetype)initWithSignIn:(GIDSignIn *)signIn
withGoogleServiceProperties:(nullable NSDictionary<NSString *, id> *)googleServiceProperties
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
| plugins/packages/google_sign_in/google_sign_in_ios/ios/Classes/FLTGoogleSignInPlugin_Test.h/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/ios/Classes/FLTGoogleSignInPlugin_Test.h",
"repo_id": "plugins",
"token_count": 263
} | 1,236 |
// 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:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
void main() {
// Store the initial instance before any tests change it.
final GoogleSignInPlatform initialInstance = GoogleSignInPlatform.instance;
group('$GoogleSignInPlatform', () {
test('$MethodChannelGoogleSignIn is the default instance', () {
expect(initialInstance, isA<MethodChannelGoogleSignIn>());
});
test('Cannot be implemented with `implements`', () {
expect(() {
GoogleSignInPlatform.instance = ImplementsGoogleSignInPlatform();
// In versions of `package:plugin_platform_interface` prior to fixing
// https://github.com/flutter/flutter/issues/109339, an attempt to
// implement a platform interface using `implements` would sometimes
// throw a `NoSuchMethodError` and other times throw an
// `AssertionError`. After the issue is fixed, an `AssertionError` will
// always be thrown. For the purpose of this test, we don't really care
// what exception is thrown, so just allow any exception.
}, throwsA(anything));
});
test('Can be extended', () {
GoogleSignInPlatform.instance = ExtendsGoogleSignInPlatform();
});
test('Can be mocked with `implements`', () {
GoogleSignInPlatform.instance = ModernMockImplementation();
});
test('still supports legacy isMock', () {
GoogleSignInPlatform.instance = LegacyIsMockImplementation();
});
});
group('GoogleSignInTokenData', () {
test('can be compared by == operator', () {
final GoogleSignInTokenData firstInstance = GoogleSignInTokenData(
accessToken: 'accessToken',
idToken: 'idToken',
serverAuthCode: 'serverAuthCode',
);
final GoogleSignInTokenData secondInstance = GoogleSignInTokenData(
accessToken: 'accessToken',
idToken: 'idToken',
serverAuthCode: 'serverAuthCode',
);
expect(firstInstance == secondInstance, isTrue);
});
});
group('GoogleSignInUserData', () {
test('can be compared by == operator', () {
final GoogleSignInUserData firstInstance = GoogleSignInUserData(
email: 'email',
id: 'id',
displayName: 'displayName',
photoUrl: 'photoUrl',
idToken: 'idToken',
serverAuthCode: 'serverAuthCode',
);
final GoogleSignInUserData secondInstance = GoogleSignInUserData(
email: 'email',
id: 'id',
displayName: 'displayName',
photoUrl: 'photoUrl',
idToken: 'idToken',
serverAuthCode: 'serverAuthCode',
);
expect(firstInstance == secondInstance, isTrue);
});
});
}
class LegacyIsMockImplementation extends Mock implements GoogleSignInPlatform {
@override
bool get isMock => true;
}
class ModernMockImplementation extends Mock
with MockPlatformInterfaceMixin
implements GoogleSignInPlatform {
@override
bool get isMock => false;
}
class ImplementsGoogleSignInPlatform extends Mock
implements GoogleSignInPlatform {}
class ExtendsGoogleSignInPlatform extends GoogleSignInPlatform {}
| plugins/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart",
"repo_id": "plugins",
"token_count": 1186
} | 1,237 |
# Image Picker plugin for Flutter
[](https://pub.dev/packages/image_picker)
A Flutter plugin for iOS and Android for picking images from the image library,
and taking new pictures with the camera.
| | Android | iOS | Web |
|-------------|---------|--------|----------------------------------|
| **Support** | SDK 21+ | iOS 9+ | [See `image_picker_for_web `][1] |
## Installation
First, add `image_picker` as a [dependency in your pubspec.yaml file](https://flutter.dev/docs/development/platform-integration/platform-channels).
### iOS
This plugin requires iOS 9.0 or higher.
Starting with version **0.8.1** the iOS implementation uses PHPicker to pick (multiple) images on iOS 14 or higher.
As a result of implementing PHPicker it becomes impossible to pick HEIC images on the iOS simulator in iOS 14+. This is a known issue. Please test this on a real device, or test with non-HEIC images until Apple solves this issue. [63426347 - Apple known issue](https://www.google.com/search?q=63426347+apple&sxsrf=ALeKk01YnTMid5S0PYvhL8GbgXJ40ZS[…]t=gws-wiz&ved=0ahUKEwjKh8XH_5HwAhWL_rsIHUmHDN8Q4dUDCA8&uact=5)
Add the following keys to your _Info.plist_ file, located in `<project root>/ios/Runner/Info.plist`:
* `NSPhotoLibraryUsageDescription` - describe why your app needs permission for the photo library. This is called _Privacy - Photo Library Usage Description_ in the visual editor.
* This permission will not be requested if you always pass `false` for `requestFullMetadata`, but App Store policy requires including the plist entry.
* `NSCameraUsageDescription` - describe why your app needs access to the camera. This is called _Privacy - Camera Usage Description_ in the visual editor.
* `NSMicrophoneUsageDescription` - describe why your app needs access to the microphone, if you intend to record videos. This is called _Privacy - Microphone Usage Description_ in the visual editor.
### Android
Starting with version **0.8.1** the Android implementation support to pick (multiple) images on Android 4.3 or higher.
No configuration required - the plugin should work out of the box. It is
however highly recommended to prepare for Android killing the application when
low on memory. How to prepare for this is discussed in the [Handling
MainActivity destruction on Android](#handling-mainactivity-destruction-on-android)
section.
It is no longer required to add `android:requestLegacyExternalStorage="true"` as an attribute to the `<application>` tag in AndroidManifest.xml, as `image_picker` has been updated to make use of scoped storage.
**Note:** Images and videos picked using the camera are saved to your application's local cache, and should therefore be expected to only be around temporarily.
If you require your picked image to be stored permanently, it is your responsibility to move it to a more permanent location.
### Example
``` dart
import 'package:image_picker/image_picker.dart';
...
final ImagePicker _picker = ImagePicker();
// Pick an image
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
// Capture a photo
final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
// Pick a video
final XFile? image = await _picker.pickVideo(source: ImageSource.gallery);
// Capture a video
final XFile? video = await _picker.pickVideo(source: ImageSource.camera);
// Pick multiple images
final List<XFile>? images = await _picker.pickMultiImage();
...
```
### Handling MainActivity destruction on Android
When under high memory pressure the Android system may kill the MainActivity of
the application using the image_picker. On Android the image_picker makes use
of the default `Intent.ACTION_GET_CONTENT` or `MediaStore.ACTION_IMAGE_CAPTURE`
intents. This means that while the intent is executing the source application
is moved to the background and becomes eligable for cleanup when the system is
low on memory. When the intent finishes executing, Android will restart the
application. Since the data is never returned to the original call use the
`ImagePicker.retrieveLostData()` method to retrieve the lost data. For example:
```dart
Future<void> getLostData() async {
final LostDataResponse response =
await picker.retrieveLostData();
if (response.isEmpty) {
return;
}
if (response.files != null) {
for (final XFile file in response.files) {
_handleFile(file);
}
} else {
_handleError(response.exception);
}
}
```
This check should always be run at startup in order to detect and handle this
case. Please refer to the
[example app](https://pub.dev/packages/image_picker/example) for a more
complete example of handling this flow.
## Migrating to 0.8.2+
Starting with version **0.8.2** of the image_picker plugin, new methods have been added for picking files that return `XFile` instances (from the [cross_file](https://pub.dev/packages/cross_file) package) rather than the plugin's own `PickedFile` instances. While the previous methods still exist, it is already recommended to start migrating over to their new equivalents. Eventually, `PickedFile` and the methods that return instances of it will be deprecated and removed.
#### Call the new methods
| Old API | New API |
|---------|---------|
| `PickedFile image = await _picker.getImage(...)` | `XFile image = await _picker.pickImage(...)` |
| `List<PickedFile> images = await _picker.getMultiImage(...)` | `List<XFile> images = await _picker.pickMultiImage(...)` |
| `PickedFile video = await _picker.getVideo(...)` | `XFile video = await _picker.pickVideo(...)` |
| `LostData response = await _picker.getLostData()` | `LostDataResponse response = await _picker.retrieveLostData()` |
[1]: https://pub.dev/packages/image_picker_for_web#limitations-on-the-web-platform
| plugins/packages/image_picker/image_picker/README.md/0 | {
"file_path": "plugins/packages/image_picker/image_picker/README.md",
"repo_id": "plugins",
"token_count": 1719
} | 1,238 |
org.gradle.jvmargs=-Xmx4G
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/image_picker/image_picker/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/image_picker/image_picker/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 38
} | 1,239 |
// 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 android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import io.flutter.plugin.common.MethodCall;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class ImagePickerCache {
static final String MAP_KEY_PATH = "path";
static final String MAP_KEY_PATH_LIST = "pathList";
static final String MAP_KEY_MAX_WIDTH = "maxWidth";
static final String MAP_KEY_MAX_HEIGHT = "maxHeight";
static final String MAP_KEY_IMAGE_QUALITY = "imageQuality";
private static final String MAP_KEY_TYPE = "type";
private static final String MAP_KEY_ERROR_CODE = "errorCode";
private static final String MAP_KEY_ERROR_MESSAGE = "errorMessage";
private static final String FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY =
"flutter_image_picker_image_path";
private static final String SHARED_PREFERENCE_ERROR_CODE_KEY = "flutter_image_picker_error_code";
private static final String SHARED_PREFERENCE_ERROR_MESSAGE_KEY =
"flutter_image_picker_error_message";
private static final String SHARED_PREFERENCE_MAX_WIDTH_KEY = "flutter_image_picker_max_width";
private static final String SHARED_PREFERENCE_MAX_HEIGHT_KEY = "flutter_image_picker_max_height";
private static final String SHARED_PREFERENCE_IMAGE_QUALITY_KEY =
"flutter_image_picker_image_quality";
private static final String SHARED_PREFERENCE_TYPE_KEY = "flutter_image_picker_type";
private static final String SHARED_PREFERENCE_PENDING_IMAGE_URI_PATH_KEY =
"flutter_image_picker_pending_image_uri";
@VisibleForTesting
static final String SHARED_PREFERENCES_NAME = "flutter_image_picker_shared_preference";
private SharedPreferences prefs;
ImagePickerCache(Context context) {
prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
void saveTypeWithMethodCallName(String methodCallName) {
if (methodCallName.equals(ImagePickerPlugin.METHOD_CALL_IMAGE)
| methodCallName.equals(ImagePickerPlugin.METHOD_CALL_MULTI_IMAGE)) {
setType("image");
} else if (methodCallName.equals(ImagePickerPlugin.METHOD_CALL_VIDEO)) {
setType("video");
}
}
private void setType(String type) {
prefs.edit().putString(SHARED_PREFERENCE_TYPE_KEY, type).apply();
}
void saveDimensionWithMethodCall(MethodCall methodCall) {
Double maxWidth = methodCall.argument(MAP_KEY_MAX_WIDTH);
Double maxHeight = methodCall.argument(MAP_KEY_MAX_HEIGHT);
int imageQuality =
methodCall.argument(MAP_KEY_IMAGE_QUALITY) == null
? 100
: (int) methodCall.argument(MAP_KEY_IMAGE_QUALITY);
setMaxDimension(maxWidth, maxHeight, imageQuality);
}
private void setMaxDimension(Double maxWidth, Double maxHeight, int imageQuality) {
SharedPreferences.Editor editor = prefs.edit();
if (maxWidth != null) {
editor.putLong(SHARED_PREFERENCE_MAX_WIDTH_KEY, Double.doubleToRawLongBits(maxWidth));
}
if (maxHeight != null) {
editor.putLong(SHARED_PREFERENCE_MAX_HEIGHT_KEY, Double.doubleToRawLongBits(maxHeight));
}
if (imageQuality > -1 && imageQuality < 101) {
editor.putInt(SHARED_PREFERENCE_IMAGE_QUALITY_KEY, imageQuality);
} else {
editor.putInt(SHARED_PREFERENCE_IMAGE_QUALITY_KEY, 100);
}
editor.apply();
}
void savePendingCameraMediaUriPath(Uri uri) {
prefs.edit().putString(SHARED_PREFERENCE_PENDING_IMAGE_URI_PATH_KEY, uri.getPath()).apply();
}
String retrievePendingCameraMediaUriPath() {
return prefs.getString(SHARED_PREFERENCE_PENDING_IMAGE_URI_PATH_KEY, "");
}
void saveResult(
@Nullable ArrayList<String> path, @Nullable String errorCode, @Nullable String errorMessage) {
Set<String> imageSet = new HashSet<>();
imageSet.addAll(path);
SharedPreferences.Editor editor = prefs.edit();
if (path != null) {
editor.putStringSet(FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY, imageSet);
}
if (errorCode != null) {
editor.putString(SHARED_PREFERENCE_ERROR_CODE_KEY, errorCode);
}
if (errorMessage != null) {
editor.putString(SHARED_PREFERENCE_ERROR_MESSAGE_KEY, errorMessage);
}
editor.apply();
}
void clear() {
prefs.edit().clear().apply();
}
Map<String, Object> getCacheMap() {
Map<String, Object> resultMap = new HashMap<>();
ArrayList<String> pathList = new ArrayList<>();
boolean hasData = false;
if (prefs.contains(FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY)) {
final Set<String> imagePathList =
prefs.getStringSet(FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY, null);
if (imagePathList != null) {
pathList.addAll(imagePathList);
resultMap.put(MAP_KEY_PATH_LIST, pathList);
hasData = true;
}
}
if (prefs.contains(SHARED_PREFERENCE_ERROR_CODE_KEY)) {
final String errorCodeValue = prefs.getString(SHARED_PREFERENCE_ERROR_CODE_KEY, "");
resultMap.put(MAP_KEY_ERROR_CODE, errorCodeValue);
hasData = true;
if (prefs.contains(SHARED_PREFERENCE_ERROR_MESSAGE_KEY)) {
final String errorMessageValue = prefs.getString(SHARED_PREFERENCE_ERROR_MESSAGE_KEY, "");
resultMap.put(MAP_KEY_ERROR_MESSAGE, errorMessageValue);
}
}
if (hasData) {
if (prefs.contains(SHARED_PREFERENCE_TYPE_KEY)) {
final String typeValue = prefs.getString(SHARED_PREFERENCE_TYPE_KEY, "");
resultMap.put(MAP_KEY_TYPE, typeValue);
}
if (prefs.contains(SHARED_PREFERENCE_MAX_WIDTH_KEY)) {
final long maxWidthValue = prefs.getLong(SHARED_PREFERENCE_MAX_WIDTH_KEY, 0);
resultMap.put(MAP_KEY_MAX_WIDTH, Double.longBitsToDouble(maxWidthValue));
}
if (prefs.contains(SHARED_PREFERENCE_MAX_HEIGHT_KEY)) {
final long maxHeightValue = prefs.getLong(SHARED_PREFERENCE_MAX_HEIGHT_KEY, 0);
resultMap.put(MAP_KEY_MAX_HEIGHT, Double.longBitsToDouble(maxHeightValue));
}
if (prefs.contains(SHARED_PREFERENCE_IMAGE_QUALITY_KEY)) {
final int imageQuality = prefs.getInt(SHARED_PREFERENCE_IMAGE_QUALITY_KEY, 100);
resultMap.put(MAP_KEY_IMAGE_QUALITY, imageQuality);
} else {
resultMap.put(MAP_KEY_IMAGE_QUALITY, 100);
}
}
return resultMap;
}
}
| plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerCache.java/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerCache.java",
"repo_id": "plugins",
"token_count": 2579
} | 1,240 |
## 0.8.6+8
* Fixes issue with images sometimes changing to incorrect orientation.
## 0.8.6+7
* Fixes issue where GIF file would not animate without `Photo Library Usage` permissions. Fixes issue where PNG and GIF files were converted to JPG, but only when they are do not have `Photo Library Usage` permissions.
* Updates minimum Flutter version to 3.0.
## 0.8.6+6
* Updates code for stricter lint checks.
## 0.8.6+5
* Fixes crash when `imageQuality` is set.
## 0.8.6+4
* Fixes authorization status check for iOS14+ so it includes `PHAuthorizationStatusLimited`.
## 0.8.6+3
* Returns error on image load failure.
## 0.8.6+2
* Fixes issue where selectable images of certain types (such as ProRAW images) could not be loaded.
## 0.8.6+1
* Fixes issue with crashing the app when picking images with PHPicker without providing `Photo Library Usage` permission.
## 0.8.6
* Adds `requestFullMetadata` option to `pickImage`, so images on iOS can be picked without `Photo Library Usage` permission.
* Updates minimum Flutter version to 2.10.
## 0.8.5+6
* Updates description.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 0.8.5+5
* Adds non-deprecated codepaths for iOS 13+.
## 0.8.5+4
* Suppresses warnings for pre-iOS-11 codepaths.
## 0.8.5+3
* Fixes 'messages.g.h' file not found.
## 0.8.5+2
* Minor fixes for new analysis options.
## 0.8.5+1
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.8.5
* Switches to an in-package method channel based on Pigeon.
* Fixes invalid casts when selecting multiple images on versions of iOS before
14.0.
## 0.8.4+11
* Splits from `image_picker` as a federated implementation.
| plugins/packages/image_picker/image_picker_ios/CHANGELOG.md/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 585
} | 1,241 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.0.3), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "messages.g.h"
#import <Flutter/Flutter.h>
#if !__has_feature(objc_arc)
#error File requires ARC to be enabled.
#endif
static NSDictionary<NSString *, id> *wrapResult(id result, FlutterError *error) {
NSDictionary *errorDict = (NSDictionary *)[NSNull null];
if (error) {
errorDict = @{
@"code" : (error.code ? error.code : [NSNull null]),
@"message" : (error.message ? error.message : [NSNull null]),
@"details" : (error.details ? error.details : [NSNull null]),
};
}
return @{
@"result" : (result ? result : [NSNull null]),
@"error" : errorDict,
};
}
static id GetNullableObject(NSDictionary *dict, id key) {
id result = dict[key];
return (result == [NSNull null]) ? nil : result;
}
static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) {
id result = array[key];
return (result == [NSNull null]) ? nil : result;
}
@interface FLTMaxSize ()
+ (FLTMaxSize *)fromMap:(NSDictionary *)dict;
- (NSDictionary *)toMap;
@end
@interface FLTSourceSpecification ()
+ (FLTSourceSpecification *)fromMap:(NSDictionary *)dict;
- (NSDictionary *)toMap;
@end
@implementation FLTMaxSize
+ (instancetype)makeWithWidth:(nullable NSNumber *)width height:(nullable NSNumber *)height {
FLTMaxSize *pigeonResult = [[FLTMaxSize alloc] init];
pigeonResult.width = width;
pigeonResult.height = height;
return pigeonResult;
}
+ (FLTMaxSize *)fromMap:(NSDictionary *)dict {
FLTMaxSize *pigeonResult = [[FLTMaxSize alloc] init];
pigeonResult.width = GetNullableObject(dict, @"width");
pigeonResult.height = GetNullableObject(dict, @"height");
return pigeonResult;
}
- (NSDictionary *)toMap {
return [NSDictionary
dictionaryWithObjectsAndKeys:(self.width ? self.width : [NSNull null]), @"width",
(self.height ? self.height : [NSNull null]), @"height", nil];
}
@end
@implementation FLTSourceSpecification
+ (instancetype)makeWithType:(FLTSourceType)type camera:(FLTSourceCamera)camera {
FLTSourceSpecification *pigeonResult = [[FLTSourceSpecification alloc] init];
pigeonResult.type = type;
pigeonResult.camera = camera;
return pigeonResult;
}
+ (FLTSourceSpecification *)fromMap:(NSDictionary *)dict {
FLTSourceSpecification *pigeonResult = [[FLTSourceSpecification alloc] init];
pigeonResult.type = [GetNullableObject(dict, @"type") integerValue];
pigeonResult.camera = [GetNullableObject(dict, @"camera") integerValue];
return pigeonResult;
}
- (NSDictionary *)toMap {
return [NSDictionary
dictionaryWithObjectsAndKeys:@(self.type), @"type", @(self.camera), @"camera", nil];
}
@end
@interface FLTImagePickerApiCodecReader : FlutterStandardReader
@end
@implementation FLTImagePickerApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FLTMaxSize fromMap:[self readValue]];
case 129:
return [FLTSourceSpecification fromMap:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FLTImagePickerApiCodecWriter : FlutterStandardWriter
@end
@implementation FLTImagePickerApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FLTMaxSize class]]) {
[self writeByte:128];
[self writeValue:[value toMap]];
} else if ([value isKindOfClass:[FLTSourceSpecification class]]) {
[self writeByte:129];
[self writeValue:[value toMap]];
} else {
[super writeValue:value];
}
}
@end
@interface FLTImagePickerApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FLTImagePickerApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FLTImagePickerApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FLTImagePickerApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FLTImagePickerApiGetCodec() {
static dispatch_once_t sPred = 0;
static FlutterStandardMessageCodec *sSharedObject = nil;
dispatch_once(&sPred, ^{
FLTImagePickerApiCodecReaderWriter *readerWriter =
[[FLTImagePickerApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void FLTImagePickerApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FLTImagePickerApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.ImagePickerApi.pickImage"
binaryMessenger:binaryMessenger
codec:FLTImagePickerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(pickImageWithSource:maxSize:quality:fullMetadata:completion:)],
@"FLTImagePickerApi api (%@) doesn't respond to "
@"@selector(pickImageWithSource:maxSize:quality:fullMetadata:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FLTSourceSpecification *arg_source = GetNullableObjectAtIndex(args, 0);
FLTMaxSize *arg_maxSize = GetNullableObjectAtIndex(args, 1);
NSNumber *arg_imageQuality = GetNullableObjectAtIndex(args, 2);
NSNumber *arg_requestFullMetadata = GetNullableObjectAtIndex(args, 3);
[api pickImageWithSource:arg_source
maxSize:arg_maxSize
quality:arg_imageQuality
fullMetadata:arg_requestFullMetadata
completion:^(NSString *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.ImagePickerApi.pickMultiImage"
binaryMessenger:binaryMessenger
codec:FLTImagePickerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(pickMultiImageWithMaxSize:quality:fullMetadata:completion:)],
@"FLTImagePickerApi api (%@) doesn't respond to "
@"@selector(pickMultiImageWithMaxSize:quality:fullMetadata:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FLTMaxSize *arg_maxSize = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_imageQuality = GetNullableObjectAtIndex(args, 1);
NSNumber *arg_requestFullMetadata = GetNullableObjectAtIndex(args, 2);
[api pickMultiImageWithMaxSize:arg_maxSize
quality:arg_imageQuality
fullMetadata:arg_requestFullMetadata
completion:^(NSArray<NSString *> *_Nullable output,
FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.ImagePickerApi.pickVideo"
binaryMessenger:binaryMessenger
codec:FLTImagePickerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(pickVideoWithSource:maxDuration:completion:)],
@"FLTImagePickerApi api (%@) doesn't respond to "
@"@selector(pickVideoWithSource:maxDuration:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FLTSourceSpecification *arg_source = GetNullableObjectAtIndex(args, 0);
NSNumber *arg_maxDurationSeconds = GetNullableObjectAtIndex(args, 1);
[api pickVideoWithSource:arg_source
maxDuration:arg_maxDurationSeconds
completion:^(NSString *_Nullable output, FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
}
| plugins/packages/image_picker/image_picker_ios/ios/Classes/messages.g.m/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/ios/Classes/messages.g.m",
"repo_id": "plugins",
"token_count": 3525
} | 1,242 |
// 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.
/// Which camera to use when picking images/videos while source is `ImageSource.camera`.
///
/// Not every device supports both of the positions.
enum CameraDevice {
/// Use the rear camera.
///
/// In most of the cases, it is the default configuration.
rear,
/// Use the front camera.
///
/// Supported on all iPhones/iPads and some Android devices.
front,
}
| plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_device.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_device.dart",
"repo_id": "plugins",
"token_count": 143
} | 1,243 |
// 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:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:image_picker_platform_interface/src/method_channel/method_channel_image_picker.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$MethodChannelImagePicker', () {
final MethodChannelImagePicker picker = MethodChannelImagePicker();
final List<MethodCall> log = <MethodCall>[];
dynamic returnValue = '';
setUp(() {
returnValue = '';
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
log.add(methodCall);
return returnValue;
});
log.clear();
});
group('#pickImage', () {
test('passes the image source argument correctly', () async {
await picker.pickImage(source: ImageSource.camera);
await picker.pickImage(source: ImageSource.gallery);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 1,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'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,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept an 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 {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => 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,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
],
);
});
test('camera position can set to front', () async {
await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 1,
'requestFullMetadata': true,
}),
],
);
});
});
group('#pickMultiImage', () {
test('calls the method correctly', () async {
returnValue = <dynamic>['0', '1'];
await picker.pickMultiImage();
expect(
log,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width and height arguments correctly', () async {
returnValue = <dynamic>['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,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a negative width or height argument', () {
returnValue = <dynamic>['0', '1'];
expect(
() => picker.pickMultiImage(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickMultiImage(maxHeight: -1.0),
throwsArgumentError,
);
});
test('does not accept an invalid imageQuality argument', () {
returnValue = <dynamic>['0', '1'];
expect(
() => picker.pickMultiImage(imageQuality: -1),
throwsArgumentError,
);
expect(
() => picker.pickMultiImage(imageQuality: 101),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => null);
expect(await picker.pickMultiImage(), isNull);
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,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'cameraDevice': 0,
'maxDuration': null,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 1,
'cameraDevice': 0,
'maxDuration': null,
}),
],
);
});
test('passes the duration argument correctly', () async {
await picker.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,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': null,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 10,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 60,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 3600,
'cameraDevice': 0,
}),
],
);
});
test('handles a null video path response gracefully', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => 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,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'cameraDevice': 0,
'maxDuration': null,
}),
],
);
});
test('camera position can set to front', () async {
await picker.pickVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': null,
'cameraDevice': 1,
}),
],
);
});
});
group('#retrieveLostData', () {
test('retrieveLostData get success response', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return <String, String>{
'type': 'image',
'path': '/example/path',
};
});
final LostData response = await picker.retrieveLostData();
expect(response.type, RetrieveType.image);
expect(response.file, isNotNull);
expect(response.file!.path, '/example/path');
});
test('retrieveLostData get error response', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return <String, String>{
'type': 'video',
'errorCode': 'test_error_code',
'errorMessage': 'test_error_message',
};
});
final LostData response = await picker.retrieveLostData();
expect(response.type, RetrieveType.video);
expect(response.exception, isNotNull);
expect(response.exception!.code, 'test_error_code');
expect(response.exception!.message, 'test_error_message');
});
test('retrieveLostData get null response', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return null;
});
expect((await picker.retrieveLostData()).isEmpty, true);
});
test('retrieveLostData get both path and error should throw', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return <String, String>{
'type': 'video',
'errorCode': 'test_error_code',
'errorMessage': 'test_error_message',
'path': '/example/path',
};
});
expect(picker.retrieveLostData(), throwsAssertionError);
});
});
group('#getImage', () {
test('passes the image source argument correctly', () async {
await picker.getImage(source: ImageSource.camera);
await picker.getImage(source: ImageSource.gallery);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 1,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'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,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept an 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 {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => null);
expect(await picker.getImage(source: ImageSource.gallery), isNull);
expect(await picker.getImage(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
await picker.getImage(source: ImageSource.camera);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 1,
'requestFullMetadata': true,
}),
],
);
});
});
group('#getMultiImage', () {
test('calls the method correctly', () async {
returnValue = <dynamic>['0', '1'];
await picker.getMultiImage();
expect(
log,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width and height arguments correctly', () async {
returnValue = <dynamic>['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,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a negative width or height argument', () {
returnValue = <dynamic>['0', '1'];
expect(
() => picker.getMultiImage(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.getMultiImage(maxHeight: -1.0),
throwsArgumentError,
);
});
test('does not accept an invalid imageQuality argument', () {
returnValue = <dynamic>['0', '1'];
expect(
() => picker.getMultiImage(imageQuality: -1),
throwsArgumentError,
);
expect(
() => picker.getMultiImage(imageQuality: 101),
throwsArgumentError,
);
});
test('handles a null image path response gracefully', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => 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,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'cameraDevice': 0,
'maxDuration': null,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 1,
'cameraDevice': 0,
'maxDuration': null,
}),
],
);
});
test('passes the duration argument correctly', () async {
await picker.getVideo(source: ImageSource.camera);
await picker.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 10),
);
await picker.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(minutes: 1),
);
await picker.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(hours: 1),
);
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': null,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 10,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 60,
'cameraDevice': 0,
}),
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': 3600,
'cameraDevice': 0,
}),
],
);
});
test('handles a null video path response gracefully', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => null);
expect(await picker.getVideo(source: ImageSource.gallery), isNull);
expect(await picker.getVideo(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
await picker.getVideo(source: ImageSource.camera);
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'cameraDevice': 0,
'maxDuration': null,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front,
);
expect(
log,
<Matcher>[
isMethodCall('pickVideo', arguments: <String, dynamic>{
'source': 0,
'maxDuration': null,
'cameraDevice': 1,
}),
],
);
});
});
group('#getLostData', () {
test('getLostData get success response', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return <String, String>{
'type': 'image',
'path': '/example/path',
};
});
final LostDataResponse response = await picker.getLostData();
expect(response.type, RetrieveType.image);
expect(response.file, isNotNull);
expect(response.file!.path, '/example/path');
});
test('getLostData should successfully retrieve multiple files', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return <String, dynamic>{
'type': 'image',
'path': '/example/path1',
'pathList': <dynamic>['/example/path0', '/example/path1'],
};
});
final LostDataResponse response = await picker.getLostData();
expect(response.type, RetrieveType.image);
expect(response.file, isNotNull);
expect(response.file!.path, '/example/path1');
expect(response.files!.first.path, '/example/path0');
expect(response.files!.length, 2);
});
test('getLostData get error response', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return <String, String>{
'type': 'video',
'errorCode': 'test_error_code',
'errorMessage': 'test_error_message',
};
});
final LostDataResponse response = await picker.getLostData();
expect(response.type, RetrieveType.video);
expect(response.exception, isNotNull);
expect(response.exception!.code, 'test_error_code');
expect(response.exception!.message, 'test_error_message');
});
test('getLostData get null response', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return null;
});
expect((await picker.getLostData()).isEmpty, true);
});
test('getLostData get both path and error should throw', () async {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(picker.channel,
(MethodCall methodCall) async {
return <String, String>{
'type': 'video',
'errorCode': 'test_error_code',
'errorMessage': 'test_error_message',
'path': '/example/path',
};
});
expect(picker.getLostData(), throwsAssertionError);
});
});
group('#getImageFromSource', () {
test('passes the image source argument correctly', () async {
await picker.getImageFromSource(source: ImageSource.camera);
await picker.getImageFromSource(source: ImageSource.gallery);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 1,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'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,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept an 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 {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => 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,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': true,
}),
],
);
});
test('camera position can set to front', () async {
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(
preferredCameraDevice: CameraDevice.front,
),
);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 1,
'requestFullMetadata': true,
}),
],
);
});
test('passes the full metadata argument correctly', () async {
await picker.getImageFromSource(
source: ImageSource.camera,
options: const ImagePickerOptions(requestFullMetadata: false),
);
expect(
log,
<Matcher>[
isMethodCall('pickImage', arguments: <String, dynamic>{
'source': 0,
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'cameraDevice': 0,
'requestFullMetadata': false,
}),
],
);
});
});
group('#getMultiImageWithOptions', () {
test('calls the method correctly', () async {
returnValue = <dynamic>['0', '1'];
await picker.getMultiImageWithOptions();
expect(
log,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('passes the width, height and imageQuality arguments correctly',
() async {
returnValue = <dynamic>['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,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': null,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': null,
'imageQuality': 70,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': 10.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': 10.0,
'maxHeight': 20.0,
'imageQuality': 70,
'requestFullMetadata': true,
}),
],
);
});
test('does not accept a negative width or height argument', () {
returnValue = <dynamic>['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 an invalid imageQuality argument', () {
returnValue = <dynamic>['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 {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
picker.channel, (MethodCall methodCall) => null);
expect(await picker.getMultiImage(), isNull);
expect(await picker.getMultiImage(), isNull);
});
test('Request full metadata argument defaults to true', () async {
returnValue = <dynamic>['0', '1'];
await picker.getMultiImageWithOptions();
expect(
log,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': true,
}),
],
);
});
test('passes the request full metadata argument correctly', () async {
returnValue = <dynamic>['0', '1'];
await picker.getMultiImageWithOptions(
options: const MultiImagePickerOptions(
imageOptions: ImageOptions(requestFullMetadata: false),
),
);
expect(
log,
<Matcher>[
isMethodCall('pickMultiImage', arguments: <String, dynamic>{
'maxWidth': null,
'maxHeight': null,
'imageQuality': null,
'requestFullMetadata': false,
}),
],
);
});
});
});
}
/// 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/image_picker/image_picker_platform_interface/test/new_method_channel_image_picker_test.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_platform_interface/test/new_method_channel_image_picker_test.dart",
"repo_id": "plugins",
"token_count": 24520
} | 1,244 |
// 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 io.flutter.plugins.inapppurchase.Translator.fromPurchaseHistoryRecordList;
import static io.flutter.plugins.inapppurchase.Translator.fromPurchasesList;
import static io.flutter.plugins.inapppurchase.Translator.fromSkuDetailsList;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingFlowParams.ProrationMode;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.PriceChangeFlowParams;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.PurchaseHistoryResponseListener;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.QueryPurchaseHistoryParams;
import com.android.billingclient.api.QueryPurchasesParams;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Handles method channel for the plugin. */
class MethodCallHandlerImpl
implements MethodChannel.MethodCallHandler, Application.ActivityLifecycleCallbacks {
private static final String TAG = "InAppPurchasePlugin";
private static final String LOAD_SKU_DOC_URL =
"https://github.com/flutter/plugins/blob/main/packages/in_app_purchase/in_app_purchase/README.md#loading-products-for-sale";
@Nullable private BillingClient billingClient;
private final BillingClientFactory billingClientFactory;
@Nullable private Activity activity;
private final Context applicationContext;
private final MethodChannel methodChannel;
private HashMap<String, SkuDetails> cachedSkus = new HashMap<>();
/** Constructs the MethodCallHandlerImpl */
MethodCallHandlerImpl(
@Nullable Activity activity,
@NonNull Context applicationContext,
@NonNull MethodChannel methodChannel,
@NonNull BillingClientFactory billingClientFactory) {
this.billingClientFactory = billingClientFactory;
this.applicationContext = applicationContext;
this.activity = activity;
this.methodChannel = methodChannel;
}
/**
* Sets the activity. Should be called as soon as the the activity is available. When the activity
* becomes unavailable, call this method again with {@code null}.
*/
void setActivity(@Nullable Activity activity) {
this.activity = activity;
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityDestroyed(Activity activity) {
if (this.activity == activity && this.applicationContext != null) {
((Application) this.applicationContext).unregisterActivityLifecycleCallbacks(this);
endBillingClientConnection();
}
}
@Override
public void onActivityStopped(Activity activity) {}
void onDetachedFromActivity() {
endBillingClientConnection();
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
switch (call.method) {
case InAppPurchasePlugin.MethodNames.IS_READY:
isReady(result);
break;
case InAppPurchasePlugin.MethodNames.START_CONNECTION:
startConnection((int) call.argument("handle"), result);
break;
case InAppPurchasePlugin.MethodNames.END_CONNECTION:
endConnection(result);
break;
case InAppPurchasePlugin.MethodNames.QUERY_SKU_DETAILS:
List<String> skusList = call.argument("skusList");
querySkuDetailsAsync((String) call.argument("skuType"), skusList, result);
break;
case InAppPurchasePlugin.MethodNames.LAUNCH_BILLING_FLOW:
launchBillingFlow(
(String) call.argument("sku"),
(String) call.argument("accountId"),
(String) call.argument("obfuscatedProfileId"),
(String) call.argument("oldSku"),
(String) call.argument("purchaseToken"),
call.hasArgument("prorationMode")
? (int) call.argument("prorationMode")
: ProrationMode.UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY,
result);
break;
case InAppPurchasePlugin.MethodNames.QUERY_PURCHASES: // Legacy method name.
queryPurchasesAsync((String) call.argument("skuType"), result);
break;
case InAppPurchasePlugin.MethodNames.QUERY_PURCHASES_ASYNC:
queryPurchasesAsync((String) call.argument("skuType"), result);
break;
case InAppPurchasePlugin.MethodNames.QUERY_PURCHASE_HISTORY_ASYNC:
Log.e("flutter", (String) call.argument("skuType"));
queryPurchaseHistoryAsync((String) call.argument("skuType"), result);
break;
case InAppPurchasePlugin.MethodNames.CONSUME_PURCHASE_ASYNC:
consumeAsync((String) call.argument("purchaseToken"), result);
break;
case InAppPurchasePlugin.MethodNames.ACKNOWLEDGE_PURCHASE:
acknowledgePurchase((String) call.argument("purchaseToken"), result);
break;
case InAppPurchasePlugin.MethodNames.IS_FEATURE_SUPPORTED:
isFeatureSupported((String) call.argument("feature"), result);
break;
case InAppPurchasePlugin.MethodNames.LAUNCH_PRICE_CHANGE_CONFIRMATION_FLOW:
launchPriceChangeConfirmationFlow((String) call.argument("sku"), result);
break;
case InAppPurchasePlugin.MethodNames.GET_CONNECTION_STATE:
getConnectionState(result);
break;
default:
result.notImplemented();
}
}
private void endConnection(final MethodChannel.Result result) {
endBillingClientConnection();
result.success(null);
}
private void endBillingClientConnection() {
if (billingClient != null) {
billingClient.endConnection();
billingClient = null;
}
}
private void isReady(MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
result.success(billingClient.isReady());
}
// TODO(garyq): Migrate to new subscriptions API: https://developer.android.com/google/play/billing/migrate-gpblv5
private void querySkuDetailsAsync(
final String skuType, final List<String> skusList, final MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
SkuDetailsParams params =
SkuDetailsParams.newBuilder().setType(skuType).setSkusList(skusList).build();
billingClient.querySkuDetailsAsync(
params,
new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(
BillingResult billingResult, List<SkuDetails> skuDetailsList) {
updateCachedSkus(skuDetailsList);
final Map<String, Object> skuDetailsResponse = new HashMap<>();
skuDetailsResponse.put("billingResult", Translator.fromBillingResult(billingResult));
skuDetailsResponse.put("skuDetailsList", fromSkuDetailsList(skuDetailsList));
result.success(skuDetailsResponse);
}
});
}
private void launchBillingFlow(
String sku,
@Nullable String accountId,
@Nullable String obfuscatedProfileId,
@Nullable String oldSku,
@Nullable String purchaseToken,
int prorationMode,
MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
SkuDetails skuDetails = cachedSkus.get(sku);
if (skuDetails == null) {
result.error(
"NOT_FOUND",
String.format(
"Details for sku %s are not available. It might because skus were not fetched prior to the call. Please fetch the skus first. An example of how to fetch the skus could be found here: %s",
sku, LOAD_SKU_DOC_URL),
null);
return;
}
if (oldSku == null
&& prorationMode != ProrationMode.UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY) {
result.error(
"IN_APP_PURCHASE_REQUIRE_OLD_SKU",
"launchBillingFlow failed because oldSku is null. You must provide a valid oldSku in order to use a proration mode.",
null);
return;
} else if (oldSku != null && !cachedSkus.containsKey(oldSku)) {
result.error(
"IN_APP_PURCHASE_INVALID_OLD_SKU",
String.format(
"Details for sku %s are not available. It might because skus were not fetched prior to the call. Please fetch the skus first. An example of how to fetch the skus could be found here: %s",
oldSku, LOAD_SKU_DOC_URL),
null);
return;
}
if (activity == null) {
result.error(
"ACTIVITY_UNAVAILABLE",
"Details for sku "
+ sku
+ " are not available. This method must be run with the app in foreground.",
null);
return;
}
BillingFlowParams.Builder paramsBuilder =
BillingFlowParams.newBuilder().setSkuDetails(skuDetails);
if (accountId != null && !accountId.isEmpty()) {
paramsBuilder.setObfuscatedAccountId(accountId);
}
if (obfuscatedProfileId != null && !obfuscatedProfileId.isEmpty()) {
paramsBuilder.setObfuscatedProfileId(obfuscatedProfileId);
}
BillingFlowParams.SubscriptionUpdateParams.Builder subscriptionUpdateParamsBuilder =
BillingFlowParams.SubscriptionUpdateParams.newBuilder();
if (oldSku != null && !oldSku.isEmpty() && purchaseToken != null) {
subscriptionUpdateParamsBuilder.setOldPurchaseToken(purchaseToken);
// The proration mode value has to match one of the following declared in
// https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.ProrationMode
subscriptionUpdateParamsBuilder.setReplaceProrationMode(prorationMode);
paramsBuilder.setSubscriptionUpdateParams(subscriptionUpdateParamsBuilder.build());
}
result.success(
Translator.fromBillingResult(
billingClient.launchBillingFlow(activity, paramsBuilder.build())));
}
private void consumeAsync(String purchaseToken, final MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
ConsumeResponseListener listener =
new ConsumeResponseListener() {
@Override
public void onConsumeResponse(BillingResult billingResult, String outToken) {
result.success(Translator.fromBillingResult(billingResult));
}
};
ConsumeParams.Builder paramsBuilder =
ConsumeParams.newBuilder().setPurchaseToken(purchaseToken);
ConsumeParams params = paramsBuilder.build();
billingClient.consumeAsync(params, listener);
}
private void queryPurchasesAsync(String skuType, MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
// Like in our connect call, consider the billing client responding a "success" here regardless
// of status code.
QueryPurchasesParams.Builder paramsBuilder = QueryPurchasesParams.newBuilder();
paramsBuilder.setProductType(skuType);
billingClient.queryPurchasesAsync(
paramsBuilder.build(),
new PurchasesResponseListener() {
@Override
public void onQueryPurchasesResponse(
BillingResult billingResult, List<Purchase> purchasesList) {
final Map<String, Object> serialized = new HashMap<>();
// The response code is no longer passed, as part of billing 4.0, so we pass OK here
// as success is implied by calling this callback.
serialized.put("responseCode", BillingClient.BillingResponseCode.OK);
serialized.put("billingResult", Translator.fromBillingResult(billingResult));
serialized.put("purchasesList", fromPurchasesList(purchasesList));
result.success(serialized);
}
});
}
private void queryPurchaseHistoryAsync(String skuType, final MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
billingClient.queryPurchaseHistoryAsync(
QueryPurchaseHistoryParams.newBuilder().setProductType(skuType).build(),
new PurchaseHistoryResponseListener() {
@Override
public void onPurchaseHistoryResponse(
BillingResult billingResult, List<PurchaseHistoryRecord> purchasesList) {
final Map<String, Object> serialized = new HashMap<>();
serialized.put("billingResult", Translator.fromBillingResult(billingResult));
serialized.put(
"purchaseHistoryRecordList", fromPurchaseHistoryRecordList(purchasesList));
result.success(serialized);
}
});
}
private void getConnectionState(final MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
final Map<String, Object> serialized = new HashMap<>();
serialized.put("connectionState", billingClient.getConnectionState());
result.success(serialized);
}
private void startConnection(final int handle, final MethodChannel.Result result) {
if (billingClient == null) {
billingClient = billingClientFactory.createBillingClient(applicationContext, methodChannel);
}
billingClient.startConnection(
new BillingClientStateListener() {
private boolean alreadyFinished = false;
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (alreadyFinished) {
Log.d(TAG, "Tried to call onBillingSetupFinished multiple times.");
return;
}
alreadyFinished = true;
// Consider the fact that we've finished a success, leave it to the Dart side to
// validate the responseCode.
result.success(Translator.fromBillingResult(billingResult));
}
@Override
public void onBillingServiceDisconnected() {
final Map<String, Object> arguments = new HashMap<>();
arguments.put("handle", handle);
methodChannel.invokeMethod(InAppPurchasePlugin.MethodNames.ON_DISCONNECT, arguments);
}
});
}
private void acknowledgePurchase(String purchaseToken, final MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
AcknowledgePurchaseParams params =
AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchaseToken).build();
billingClient.acknowledgePurchase(
params,
new AcknowledgePurchaseResponseListener() {
@Override
public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
result.success(Translator.fromBillingResult(billingResult));
}
});
}
private void updateCachedSkus(@Nullable List<SkuDetails> skuDetailsList) {
if (skuDetailsList == null) {
return;
}
for (SkuDetails skuDetails : skuDetailsList) {
cachedSkus.put(skuDetails.getSku(), skuDetails);
}
}
private void launchPriceChangeConfirmationFlow(String sku, MethodChannel.Result result) {
if (activity == null) {
result.error(
"ACTIVITY_UNAVAILABLE",
"launchPriceChangeConfirmationFlow is not available. "
+ "This method must be run with the app in foreground.",
null);
return;
}
if (billingClientError(result)) {
return;
}
// Note that assert doesn't work on Android (see https://stackoverflow.com/a/6176529/5167831 and https://stackoverflow.com/a/8164195/5167831)
// and that this assert is only added to silence the analyser. The actual null check
// is handled by the `billingClientError()` call.
assert billingClient != null;
SkuDetails skuDetails = cachedSkus.get(sku);
if (skuDetails == null) {
result.error(
"NOT_FOUND",
String.format(
"Details for sku %s are not available. It might because skus were not fetched prior to the call. Please fetch the skus first. An example of how to fetch the skus could be found here: %s",
sku, LOAD_SKU_DOC_URL),
null);
return;
}
PriceChangeFlowParams params =
new PriceChangeFlowParams.Builder().setSkuDetails(skuDetails).build();
billingClient.launchPriceChangeConfirmationFlow(
activity,
params,
billingResult -> {
result.success(Translator.fromBillingResult(billingResult));
});
}
private boolean billingClientError(MethodChannel.Result result) {
if (billingClient != null) {
return false;
}
result.error("UNAVAILABLE", "BillingClient is unset. Try reconnecting.", null);
return true;
}
private void isFeatureSupported(String feature, MethodChannel.Result result) {
if (billingClientError(result)) {
return;
}
assert billingClient != null;
BillingResult billingResult = billingClient.isFeatureSupported(feature);
result.success(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK);
}
}
| plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java",
"repo_id": "plugins",
"token_count": 6656
} | 1,245 |
// 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.
#if TARGET_OS_OSX
#import <FlutterMacOS/FlutterMacOS.h>
#else
#import <Flutter/Flutter.h>
#endif
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
NS_ASSUME_NONNULL_BEGIN
API_AVAILABLE(ios(13))
API_UNAVAILABLE(tvos, macos, watchos)
@interface FIAPPaymentQueueDelegate : NSObject <SKPaymentQueueDelegate>
- (id)initWithMethodChannel:(FlutterMethodChannel *)methodChannel;
@end
NS_ASSUME_NONNULL_END
| plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAPPaymentQueueDelegate.h/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAPPaymentQueueDelegate.h",
"repo_id": "plugins",
"token_count": 208
} | 1,246 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../in_app_purchase_storekit.dart';
import '../store_kit_wrappers.dart';
/// Contains InApp Purchase features that are only available on iOS.
class InAppPurchaseStoreKitPlatformAddition
extends InAppPurchasePlatformAddition {
/// Present Code Redemption Sheet.
///
/// Available on devices running iOS 14 and iPadOS 14 and later.
Future<void> presentCodeRedemptionSheet() {
return SKPaymentQueueWrapper().presentCodeRedemptionSheet();
}
/// Retry loading purchase data after an initial failure.
///
/// If no results, a `null` value is returned.
Future<PurchaseVerificationData?> refreshPurchaseVerificationData() async {
await SKRequestMaker().startRefreshReceiptRequest();
try {
final String receipt = await SKReceiptManager.retrieveReceiptData();
return PurchaseVerificationData(
localVerificationData: receipt,
serverVerificationData: receipt,
source: kIAPSource);
} catch (e) {
print(
'Something is wrong while fetching the receipt, this normally happens when the app is '
'running on a simulator: $e');
return null;
}
}
/// Sets an implementation of the [SKPaymentQueueDelegateWrapper].
///
/// The [SKPaymentQueueDelegateWrapper] can be used to inform iOS how to
/// finish transactions when the storefront changes or if the price consent
/// sheet should be displayed when the price of a subscription has changed. If
/// no delegate is registered iOS will fallback to it's default configuration.
/// See the documentation on StoreKite's [`-[SKPaymentQueue delegate:]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/3182429-delegate?language=objc).
///
/// When set to `null` the payment queue delegate will be removed and the
/// default behaviour will apply (see [documentation](https://developer.apple.com/documentation/storekit/skpaymentqueue/3182429-delegate?language=objc)).
Future<void> setDelegate(SKPaymentQueueDelegateWrapper? delegate) =>
SKPaymentQueueWrapper().setDelegate(delegate);
/// Shows the price consent sheet if the user has not yet responded to a
/// subscription price change.
///
/// Use this function when you have registered a [SKPaymentQueueDelegateWrapper]
/// (using the [setDelegate] method) and returned `false` when the
/// `SKPaymentQueueDelegateWrapper.shouldShowPriceConsent()` method was called.
///
/// See documentation of StoreKit's [`-[SKPaymentQueue showPriceConsentIfNeeded]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/3521327-showpriceconsentifneeded?language=objc).
Future<void> showPriceConsentIfNeeded() =>
SKPaymentQueueWrapper().showPriceConsentIfNeeded();
}
| plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform_addition.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform_addition.dart",
"repo_id": "plugins",
"token_count": 902
} | 1,247 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../../in_app_purchase_storekit.dart';
import '../../store_kit_wrappers.dart';
import '../store_kit_wrappers/enum_converters.dart';
/// The class represents the information of a purchase made with the Apple
/// AppStore.
class AppStorePurchaseDetails extends PurchaseDetails {
/// Creates a new AppStore specific purchase details object with the provided
/// details.
AppStorePurchaseDetails({
super.purchaseID,
required super.productID,
required super.verificationData,
required super.transactionDate,
required this.skPaymentTransaction,
required PurchaseStatus status,
}) : super(status: status) {
this.status = status;
}
/// Generate a [AppStorePurchaseDetails] object based on an iOS
/// [SKPaymentTransactionWrapper] object.
factory AppStorePurchaseDetails.fromSKTransaction(
SKPaymentTransactionWrapper transaction,
String base64EncodedReceipt,
) {
final AppStorePurchaseDetails purchaseDetails = AppStorePurchaseDetails(
productID: transaction.payment.productIdentifier,
purchaseID: transaction.transactionIdentifier,
skPaymentTransaction: transaction,
status: const SKTransactionStatusConverter()
.toPurchaseStatus(transaction.transactionState, transaction.error),
transactionDate: transaction.transactionTimeStamp != null
? (transaction.transactionTimeStamp! * 1000).toInt().toString()
: null,
verificationData: PurchaseVerificationData(
localVerificationData: base64EncodedReceipt,
serverVerificationData: base64EncodedReceipt,
source: kIAPSource),
);
if (purchaseDetails.status == PurchaseStatus.error ||
purchaseDetails.status == PurchaseStatus.canceled) {
purchaseDetails.error = IAPError(
source: kIAPSource,
code: kPurchaseErrorCode,
message: transaction.error?.domain ?? '',
details: transaction.error?.userInfo,
);
}
return purchaseDetails;
}
/// Points back to the [SKPaymentTransactionWrapper] which was used to
/// generate this [AppStorePurchaseDetails] object.
final SKPaymentTransactionWrapper skPaymentTransaction;
late PurchaseStatus _status;
/// The status that this [PurchaseDetails] is currently on.
@override
PurchaseStatus get status => _status;
@override
set status(PurchaseStatus status) {
_pendingCompletePurchase = status != PurchaseStatus.pending;
_status = status;
}
bool _pendingCompletePurchase = false;
@override
bool get pendingCompletePurchase => _pendingCompletePurchase;
}
| plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_purchase_details.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_purchase_details.dart",
"repo_id": "plugins",
"token_count": 893
} | 1,248 |
// 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.
#if TARGET_OS_OSX
#import <FlutterMacOS/FlutterMacOS.h>
#else
#import <Flutter/Flutter.h>
#endif
@class FIAPaymentQueueHandler;
@class FIAPReceiptManager;
@interface InAppPurchasePlugin : NSObject <FlutterPlugin>
@property(strong, nonatomic) FIAPaymentQueueHandler *paymentQueueHandler;
- (instancetype)initWithReceiptManager:(FIAPReceiptManager *)receiptManager
NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
@end
| plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/InAppPurchasePlugin.h/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/InAppPurchasePlugin.h",
"repo_id": "plugins",
"token_count": 207
} | 1,249 |
name: ios_platform_images_example
description: Demonstrates how to use the ios_platform_images plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
ios_platform_images:
# When depending on this package from a real application you should use:
# ios_platform_images: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/ios_platform_images/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/ios_platform_images/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 260
} | 1,250 |
# local_auth_example
Demonstrates how to use the local_auth plugin.
| plugins/packages/local_auth/local_auth/example/README.md/0 | {
"file_path": "plugins/packages/local_auth/local_auth/example/README.md",
"repo_id": "plugins",
"token_count": 21
} | 1,251 |
targets:
$default:
sources:
include:
- lib/**
# Some default includes that aren't really used here but will prevent
# false-negative warnings:
- $package$
- lib/$lib$
exclude:
- '**/.*/**'
- '**/build/**'
builders:
code_excerpter|code_excerpter:
enabled: true
| plugins/packages/local_auth/local_auth/example/build.excerpt.yaml/0 | {
"file_path": "plugins/packages/local_auth/local_auth/example/build.excerpt.yaml",
"repo_id": "plugins",
"token_count": 168
} | 1,252 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, avoid_print
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final LocalAuthentication auth = LocalAuthentication();
_SupportState _supportState = _SupportState.unknown;
bool? _canCheckBiometrics;
List<BiometricType>? _availableBiometrics;
String _authorized = 'Not Authorized';
bool _isAuthenticating = false;
@override
void initState() {
super.initState();
auth.isDeviceSupported().then(
(bool isSupported) => setState(() => _supportState = isSupported
? _SupportState.supported
: _SupportState.unsupported),
);
}
Future<void> _checkBiometrics() async {
late bool canCheckBiometrics;
try {
canCheckBiometrics = await auth.canCheckBiometrics;
} on PlatformException catch (e) {
canCheckBiometrics = false;
print(e);
}
if (!mounted) {
return;
}
setState(() {
_canCheckBiometrics = canCheckBiometrics;
});
}
Future<void> _getAvailableBiometrics() async {
late List<BiometricType> availableBiometrics;
try {
availableBiometrics = await auth.getAvailableBiometrics();
} on PlatformException catch (e) {
availableBiometrics = <BiometricType>[];
print(e);
}
if (!mounted) {
return;
}
setState(() {
_availableBiometrics = availableBiometrics;
});
}
Future<void> _authenticate() async {
bool authenticated = false;
try {
setState(() {
_isAuthenticating = true;
_authorized = 'Authenticating';
});
authenticated = await auth.authenticate(
localizedReason: 'Let OS determine authentication method',
options: const AuthenticationOptions(
stickyAuth: true,
),
);
setState(() {
_isAuthenticating = false;
});
} on PlatformException catch (e) {
print(e);
setState(() {
_isAuthenticating = false;
_authorized = 'Error - ${e.message}';
});
return;
}
if (!mounted) {
return;
}
setState(
() => _authorized = authenticated ? 'Authorized' : 'Not Authorized');
}
Future<void> _authenticateWithBiometrics() async {
bool authenticated = false;
try {
setState(() {
_isAuthenticating = true;
_authorized = 'Authenticating';
});
authenticated = await auth.authenticate(
localizedReason:
'Scan your fingerprint (or face or whatever) to authenticate',
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
setState(() {
_isAuthenticating = false;
_authorized = 'Authenticating';
});
} on PlatformException catch (e) {
print(e);
setState(() {
_isAuthenticating = false;
_authorized = 'Error - ${e.message}';
});
return;
}
if (!mounted) {
return;
}
final String message = authenticated ? 'Authorized' : 'Not Authorized';
setState(() {
_authorized = message;
});
}
Future<void> _cancelAuthentication() async {
await auth.stopAuthentication();
setState(() => _isAuthenticating = false);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: ListView(
padding: const EdgeInsets.only(top: 30),
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_supportState == _SupportState.unknown)
const CircularProgressIndicator()
else if (_supportState == _SupportState.supported)
const Text('This device is supported')
else
const Text('This device is not supported'),
const Divider(height: 100),
Text('Can check biometrics: $_canCheckBiometrics\n'),
ElevatedButton(
onPressed: _checkBiometrics,
child: const Text('Check biometrics'),
),
const Divider(height: 100),
Text('Available biometrics: $_availableBiometrics\n'),
ElevatedButton(
onPressed: _getAvailableBiometrics,
child: const Text('Get available biometrics'),
),
const Divider(height: 100),
Text('Current State: $_authorized\n'),
if (_isAuthenticating)
ElevatedButton(
onPressed: _cancelAuthentication,
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Text('Cancel Authentication'),
Icon(Icons.cancel),
],
),
)
else
Column(
children: <Widget>[
ElevatedButton(
onPressed: _authenticate,
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Text('Authenticate'),
Icon(Icons.perm_device_information),
],
),
),
ElevatedButton(
onPressed: _authenticateWithBiometrics,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(_isAuthenticating
? 'Cancel'
: 'Authenticate: biometrics only'),
const Icon(Icons.fingerprint),
],
),
),
],
),
],
),
],
),
),
);
}
}
enum _SupportState {
unknown,
supported,
unsupported,
}
| plugins/packages/local_auth/local_auth/example/lib/main.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 3470
} | 1,253 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.localauth;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import io.flutter.plugin.common.MethodCall;
import java.util.concurrent.Executor;
/**
* Authenticates the user with biometrics and sends corresponding response back to Flutter.
*
* <p>One instance per call is generated to ensure readable separation of executable paths across
* method calls.
*/
@SuppressWarnings("deprecation")
class AuthenticationHelper extends BiometricPrompt.AuthenticationCallback
implements Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver {
/** The callback that handles the result of this authentication process. */
interface AuthCompletionHandler {
/** Called when authentication was successful. */
void onSuccess();
/**
* Called when authentication failed due to user. For instance, when user cancels the auth or
* quits the app.
*/
void onFailure();
/**
* Called when authentication fails due to non-user related problems such as system errors,
* phone not having a FP reader etc.
*
* @param code The error code to be returned to Flutter app.
* @param error The description of the error.
*/
void onError(String code, String error);
}
// This is null when not using v2 embedding;
private final Lifecycle lifecycle;
private final FragmentActivity activity;
private final AuthCompletionHandler completionHandler;
private final MethodCall call;
private final BiometricPrompt.PromptInfo promptInfo;
private final boolean isAuthSticky;
private final UiThreadExecutor uiThreadExecutor;
private boolean activityPaused = false;
private BiometricPrompt biometricPrompt;
AuthenticationHelper(
Lifecycle lifecycle,
FragmentActivity activity,
MethodCall call,
AuthCompletionHandler completionHandler,
boolean allowCredentials) {
this.lifecycle = lifecycle;
this.activity = activity;
this.completionHandler = completionHandler;
this.call = call;
this.isAuthSticky = call.argument("stickyAuth");
this.uiThreadExecutor = new UiThreadExecutor();
BiometricPrompt.PromptInfo.Builder promptBuilder =
new BiometricPrompt.PromptInfo.Builder()
.setDescription((String) call.argument("localizedReason"))
.setTitle((String) call.argument("signInTitle"))
.setSubtitle((String) call.argument("biometricHint"))
.setConfirmationRequired((Boolean) call.argument("sensitiveTransaction"))
.setConfirmationRequired((Boolean) call.argument("sensitiveTransaction"));
int allowedAuthenticators =
BiometricManager.Authenticators.BIOMETRIC_WEAK
| BiometricManager.Authenticators.BIOMETRIC_STRONG;
if (allowCredentials) {
allowedAuthenticators |= BiometricManager.Authenticators.DEVICE_CREDENTIAL;
} else {
promptBuilder.setNegativeButtonText((String) call.argument("cancelButton"));
}
promptBuilder.setAllowedAuthenticators(allowedAuthenticators);
this.promptInfo = promptBuilder.build();
}
/** Start the biometric listener. */
void authenticate() {
if (lifecycle != null) {
lifecycle.addObserver(this);
} else {
activity.getApplication().registerActivityLifecycleCallbacks(this);
}
biometricPrompt = new BiometricPrompt(activity, uiThreadExecutor, this);
biometricPrompt.authenticate(promptInfo);
}
/** Cancels the biometric authentication. */
void stopAuthentication() {
if (biometricPrompt != null) {
biometricPrompt.cancelAuthentication();
biometricPrompt = null;
}
}
/** Stops the biometric listener. */
private void stop() {
if (lifecycle != null) {
lifecycle.removeObserver(this);
return;
}
activity.getApplication().unregisterActivityLifecycleCallbacks(this);
}
@SuppressLint("SwitchIntDef")
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
switch (errorCode) {
case BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL:
if (call.argument("useErrorDialogs")) {
showGoToSettingsDialog(
(String) call.argument("deviceCredentialsRequired"),
(String) call.argument("deviceCredentialsSetupDescription"));
return;
}
completionHandler.onError("NotAvailable", "Security credentials not available.");
break;
case BiometricPrompt.ERROR_NO_SPACE:
case BiometricPrompt.ERROR_NO_BIOMETRICS:
if (call.argument("useErrorDialogs")) {
showGoToSettingsDialog(
(String) call.argument("biometricRequired"),
(String) call.argument("goToSettingDescription"));
return;
}
completionHandler.onError("NotEnrolled", "No Biometrics enrolled on this device.");
break;
case BiometricPrompt.ERROR_HW_UNAVAILABLE:
case BiometricPrompt.ERROR_HW_NOT_PRESENT:
completionHandler.onError("NotAvailable", "Security credentials not available.");
break;
case BiometricPrompt.ERROR_LOCKOUT:
completionHandler.onError(
"LockedOut",
"The operation was canceled because the API is locked out due to too many attempts. This occurs after 5 failed attempts, and lasts for 30 seconds.");
break;
case BiometricPrompt.ERROR_LOCKOUT_PERMANENT:
completionHandler.onError(
"PermanentlyLockedOut",
"The operation was canceled because ERROR_LOCKOUT occurred too many times. Biometric authentication is disabled until the user unlocks with strong authentication (PIN/Pattern/Password)");
break;
case BiometricPrompt.ERROR_CANCELED:
// If we are doing sticky auth and the activity has been paused,
// ignore this error. We will start listening again when resumed.
if (activityPaused && isAuthSticky) {
return;
} else {
completionHandler.onFailure();
}
break;
default:
completionHandler.onFailure();
}
stop();
}
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
completionHandler.onSuccess();
stop();
}
@Override
public void onAuthenticationFailed() {}
/**
* If the activity is paused, we keep track because biometric dialog simply returns "User
* cancelled" when the activity is paused.
*/
@Override
public void onActivityPaused(Activity ignored) {
if (isAuthSticky) {
activityPaused = true;
}
}
@Override
public void onActivityResumed(Activity ignored) {
if (isAuthSticky) {
activityPaused = false;
final BiometricPrompt prompt = new BiometricPrompt(activity, uiThreadExecutor, this);
// When activity is resuming, we cannot show the prompt right away. We need to post it to the
// UI queue.
uiThreadExecutor.handler.post(
new Runnable() {
@Override
public void run() {
prompt.authenticate(promptInfo);
}
});
}
}
@Override
public void onPause(@NonNull LifecycleOwner owner) {
onActivityPaused(null);
}
@Override
public void onResume(@NonNull LifecycleOwner owner) {
onActivityResumed(null);
}
// Suppress inflateParams lint because dialogs do not need to attach to a parent view.
@SuppressLint("InflateParams")
private void showGoToSettingsDialog(String title, String descriptionText) {
View view = LayoutInflater.from(activity).inflate(R.layout.go_to_setting, null, false);
TextView message = (TextView) view.findViewById(R.id.fingerprint_required);
TextView description = (TextView) view.findViewById(R.id.go_to_setting_description);
message.setText(title);
description.setText(descriptionText);
Context context = new ContextThemeWrapper(activity, R.style.AlertDialogCustom);
OnClickListener goToSettingHandler =
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
completionHandler.onFailure();
stop();
activity.startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
}
};
OnClickListener cancelHandler =
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
completionHandler.onFailure();
stop();
}
};
new AlertDialog.Builder(context)
.setView(view)
.setPositiveButton((String) call.argument("goToSetting"), goToSettingHandler)
.setNegativeButton((String) call.argument("cancelButton"), cancelHandler)
.setCancelable(false)
.show();
}
// Unused methods for activity lifecycle.
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {}
@Override
public void onStop(@NonNull LifecycleOwner owner) {}
@Override
public void onStart(@NonNull LifecycleOwner owner) {}
@Override
public void onCreate(@NonNull LifecycleOwner owner) {}
private static class UiThreadExecutor implements Executor {
final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
handler.post(command);
}
}
}
| plugins/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/AuthenticationHelper.java/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/AuthenticationHelper.java",
"repo_id": "plugins",
"token_count": 3630
} | 1,254 |
name: local_auth_android_example
description: Demonstrates how to use the local_auth_android plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
local_auth_android:
# When depending on this package from a real application you should use:
# local_auth_android: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
local_auth_platform_interface: ^1.0.0
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/local_auth/local_auth_android/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 289
} | 1,255 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.pathprovider">
</manifest>
| plugins/packages/path_provider/path_provider_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/android/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 46
} | 1,256 |
This only contains symlinks to ../darwin, to support versions of Flutter
prior that don't include https://github.com/flutter/flutter/pull/115337.
Once the minimum Flutter version supported by this implementation is one that
includes that functionality, this directory should be removed.
| plugins/packages/path_provider/path_provider_foundation/ios/README.md/0 | {
"file_path": "plugins/packages/path_provider/path_provider_foundation/ios/README.md",
"repo_id": "plugins",
"token_count": 67
} | 1,257 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/services.dart';
import 'package:platform/platform.dart';
import '../path_provider_platform_interface.dart';
/// An implementation of [PathProviderPlatform] that uses method channels.
class MethodChannelPathProvider extends PathProviderPlatform {
/// The method channel used to interact with the native platform.
@visibleForTesting
MethodChannel methodChannel =
const MethodChannel('plugins.flutter.io/path_provider');
// Ideally, this property shouldn't exist, and each platform should
// just implement the supported methods. Once all the platforms are
// federated, this property should be removed.
Platform _platform = const LocalPlatform();
/// This API is only exposed for the unit tests. It should not be used by
/// any code outside of the plugin itself.
@visibleForTesting
// ignore: use_setters_to_change_properties
void setMockPathProviderPlatform(Platform platform) {
_platform = platform;
}
@override
Future<String?> getTemporaryPath() {
return methodChannel.invokeMethod<String>('getTemporaryDirectory');
}
@override
Future<String?> getApplicationSupportPath() {
return methodChannel.invokeMethod<String>('getApplicationSupportDirectory');
}
@override
Future<String?> getLibraryPath() {
if (!_platform.isIOS && !_platform.isMacOS) {
throw UnsupportedError('Functionality only available on iOS/macOS');
}
return methodChannel.invokeMethod<String>('getLibraryDirectory');
}
@override
Future<String?> getApplicationDocumentsPath() {
return methodChannel
.invokeMethod<String>('getApplicationDocumentsDirectory');
}
@override
Future<String?> getExternalStoragePath() {
if (!_platform.isAndroid) {
throw UnsupportedError('Functionality only available on Android');
}
return methodChannel.invokeMethod<String>('getStorageDirectory');
}
@override
Future<List<String>?> getExternalCachePaths() {
if (!_platform.isAndroid) {
throw UnsupportedError('Functionality only available on Android');
}
return methodChannel
.invokeListMethod<String>('getExternalCacheDirectories');
}
@override
Future<List<String>?> getExternalStoragePaths({
StorageDirectory? type,
}) async {
if (!_platform.isAndroid) {
throw UnsupportedError('Functionality only available on Android');
}
return methodChannel.invokeListMethod<String>(
'getExternalStorageDirectories',
<String, dynamic>{'type': type?.index},
);
}
@override
Future<String?> getDownloadsPath() {
if (!_platform.isMacOS) {
throw UnsupportedError('Functionality only available on macOS');
}
return methodChannel.invokeMethod<String>('getDownloadsDirectory');
}
}
| plugins/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart",
"repo_id": "plugins",
"token_count": 890
} | 1,258 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:test/test.dart';
class SamplePluginPlatform extends PlatformInterface {
SamplePluginPlatform() : super(token: _token);
static final Object _token = Object();
// ignore: avoid_setters_without_getters
static set instance(SamplePluginPlatform instance) {
PlatformInterface.verify(instance, _token);
// A real implementation would set a static instance field here.
}
}
class ImplementsSamplePluginPlatform extends Mock
implements SamplePluginPlatform {}
class ImplementsSamplePluginPlatformUsingNoSuchMethod
implements SamplePluginPlatform {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class ImplementsSamplePluginPlatformUsingMockPlatformInterfaceMixin extends Mock
with MockPlatformInterfaceMixin
implements SamplePluginPlatform {}
class ImplementsSamplePluginPlatformUsingFakePlatformInterfaceMixin extends Fake
with MockPlatformInterfaceMixin
implements SamplePluginPlatform {}
class ExtendsSamplePluginPlatform extends SamplePluginPlatform {}
class ConstTokenPluginPlatform extends PlatformInterface {
ConstTokenPluginPlatform() : super(token: _token);
static const Object _token = Object(); // invalid
// ignore: avoid_setters_without_getters
static set instance(ConstTokenPluginPlatform instance) {
PlatformInterface.verify(instance, _token);
}
}
class ExtendsConstTokenPluginPlatform extends ConstTokenPluginPlatform {}
class VerifyTokenPluginPlatform extends PlatformInterface {
VerifyTokenPluginPlatform() : super(token: _token);
static final Object _token = Object();
// ignore: avoid_setters_without_getters
static set instance(VerifyTokenPluginPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
// A real implementation would set a static instance field here.
}
}
class ImplementsVerifyTokenPluginPlatform extends Mock
implements VerifyTokenPluginPlatform {}
class ImplementsVerifyTokenPluginPlatformUsingMockPlatformInterfaceMixin
extends Mock
with MockPlatformInterfaceMixin
implements VerifyTokenPluginPlatform {}
class ExtendsVerifyTokenPluginPlatform extends VerifyTokenPluginPlatform {}
class ConstVerifyTokenPluginPlatform extends PlatformInterface {
ConstVerifyTokenPluginPlatform() : super(token: _token);
static const Object _token = Object(); // invalid
// ignore: avoid_setters_without_getters
static set instance(ConstVerifyTokenPluginPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
}
}
class ImplementsConstVerifyTokenPluginPlatform extends PlatformInterface
implements ConstVerifyTokenPluginPlatform {
ImplementsConstVerifyTokenPluginPlatform() : super(token: const Object());
}
// Ensures that `PlatformInterface` has no instance methods. Adding an
// instance method is discouraged and may be a breaking change if it
// conflicts with instance methods in subclasses.
class StaticMethodsOnlyPlatformInterfaceTest implements PlatformInterface {}
class StaticMethodsOnlyMockPlatformInterfaceMixinTest
implements MockPlatformInterfaceMixin {}
void main() {
group('`verify`', () {
test('prevents implementation with `implements`', () {
expect(() {
SamplePluginPlatform.instance = ImplementsSamplePluginPlatform();
}, throwsA(isA<AssertionError>()));
});
test('prevents implmentation with `implements` and `noSuchMethod`', () {
expect(() {
SamplePluginPlatform.instance =
ImplementsSamplePluginPlatformUsingNoSuchMethod();
}, throwsA(isA<AssertionError>()));
});
test('allows mocking with `implements`', () {
final SamplePluginPlatform mock =
ImplementsSamplePluginPlatformUsingMockPlatformInterfaceMixin();
SamplePluginPlatform.instance = mock;
});
test('allows faking with `implements`', () {
final SamplePluginPlatform fake =
ImplementsSamplePluginPlatformUsingFakePlatformInterfaceMixin();
SamplePluginPlatform.instance = fake;
});
test('allows extending', () {
SamplePluginPlatform.instance = ExtendsSamplePluginPlatform();
});
test('prevents `const Object()` token', () {
expect(() {
ConstTokenPluginPlatform.instance = ExtendsConstTokenPluginPlatform();
}, throwsA(isA<AssertionError>()));
});
});
// Tests of the earlier, to-be-deprecated `verifyToken` method
group('`verifyToken`', () {
test('prevents implementation with `implements`', () {
expect(() {
VerifyTokenPluginPlatform.instance =
ImplementsVerifyTokenPluginPlatform();
}, throwsA(isA<AssertionError>()));
});
test('allows mocking with `implements`', () {
final VerifyTokenPluginPlatform mock =
ImplementsVerifyTokenPluginPlatformUsingMockPlatformInterfaceMixin();
VerifyTokenPluginPlatform.instance = mock;
});
test('allows extending', () {
VerifyTokenPluginPlatform.instance = ExtendsVerifyTokenPluginPlatform();
});
test('does not prevent `const Object()` token', () {
ConstVerifyTokenPluginPlatform.instance =
ImplementsConstVerifyTokenPluginPlatform();
});
});
}
| plugins/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart/0 | {
"file_path": "plugins/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart",
"repo_id": "plugins",
"token_count": 1584
} | 1,259 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:quick_actions/quick_actions.dart';
import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart';
void main() {
group('$QuickActions', () {
setUp(() {
QuickActionsPlatform.instance = MockQuickActionsPlatform();
});
test('constructor() should return valid QuickActions instance', () {
const QuickActions quickActions = QuickActions();
expect(quickActions, isNotNull);
});
test('initialize() PlatformInterface', () async {
const QuickActions quickActions = QuickActions();
void handler(String type) {}
await quickActions.initialize(handler);
verify(QuickActionsPlatform.instance.initialize(handler)).called(1);
});
test('setShortcutItems() PlatformInterface', () {
const QuickActions quickActions = QuickActions();
void handler(String type) {}
quickActions.initialize(handler);
quickActions.setShortcutItems(<ShortcutItem>[]);
verify(QuickActionsPlatform.instance.initialize(handler)).called(1);
verify(QuickActionsPlatform.instance.setShortcutItems(<ShortcutItem>[]))
.called(1);
});
test('clearShortcutItems() PlatformInterface', () {
const QuickActions quickActions = QuickActions();
void handler(String type) {}
quickActions.initialize(handler);
quickActions.clearShortcutItems();
verify(QuickActionsPlatform.instance.initialize(handler)).called(1);
verify(QuickActionsPlatform.instance.clearShortcutItems()).called(1);
});
});
}
class MockQuickActionsPlatform extends Mock
with MockPlatformInterfaceMixin
implements QuickActionsPlatform {
@override
Future<void> clearShortcutItems() async =>
super.noSuchMethod(Invocation.method(#clearShortcutItems, <Object?>[]));
@override
Future<void> initialize(QuickActionHandler? handler) async =>
super.noSuchMethod(Invocation.method(#initialize, <Object?>[handler]));
@override
Future<void> setShortcutItems(List<ShortcutItem>? items) async => super
.noSuchMethod(Invocation.method(#setShortcutItems, <Object?>[items]));
}
class MockQuickActions extends QuickActions {}
| plugins/packages/quick_actions/quick_actions/test/quick_actions_test.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions/test/quick_actions_test.dart",
"repo_id": "plugins",
"token_count": 823
} | 1,260 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'shared_preferences_foundation'
s.version = '0.0.1'
s.summary = 'iOS and macOS implementation of the shared_preferences plugin.'
s.description = <<-DESC
Wraps NSUserDefaults, providing a persistent store for simple key-value pairs.
DESC
s.homepage = 'https://github.com/flutter/plugins/tree/main/packages/shared_preferences/shared_preferences_foundation'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/shared_preferences/shared_preferences_foundation' }
s.source_files = 'Classes/**/*'
s.ios.dependency 'Flutter'
s.osx.dependency 'FlutterMacOS'
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.11'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.xcconfig = {
'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift',
'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',
}
s.swift_version = '5.0'
end
| plugins/packages/shared_preferences/shared_preferences_foundation/darwin/shared_preferences_foundation.podspec/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/darwin/shared_preferences_foundation.podspec",
"repo_id": "plugins",
"token_count": 565
} | 1,261 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:shared_preferences_linux/shared_preferences_linux.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('SharedPreferencesLinux', () {
const Map<String, Object> kTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.bool': true,
'flutter.int': 42,
'flutter.double': 3.14159,
'flutter.List': <String>['foo', 'bar'],
};
const Map<String, Object> kTestValues2 = <String, Object>{
'flutter.String': 'goodbye world',
'flutter.bool': false,
'flutter.int': 1337,
'flutter.double': 2.71828,
'flutter.List': <String>['baz', 'quox'],
};
late SharedPreferencesLinux preferences;
setUp(() async {
preferences = SharedPreferencesLinux();
});
tearDown(() {
preferences.clear();
});
testWidgets('reading', (WidgetTester _) async {
final Map<String, Object> all = await preferences.getAll();
expect(all['String'], isNull);
expect(all['bool'], isNull);
expect(all['int'], isNull);
expect(all['double'], isNull);
expect(all['List'], isNull);
});
testWidgets('writing', (WidgetTester _) async {
await Future.wait(<Future<bool>>[
preferences.setValue(
'String', 'String', kTestValues2['flutter.String']!),
preferences.setValue('Bool', 'bool', kTestValues2['flutter.bool']!),
preferences.setValue('Int', 'int', kTestValues2['flutter.int']!),
preferences.setValue(
'Double', 'double', kTestValues2['flutter.double']!),
preferences.setValue(
'StringList', 'List', kTestValues2['flutter.List']!)
]);
final Map<String, Object> all = await preferences.getAll();
expect(all['String'], kTestValues2['flutter.String']);
expect(all['bool'], kTestValues2['flutter.bool']);
expect(all['int'], kTestValues2['flutter.int']);
expect(all['double'], kTestValues2['flutter.double']);
expect(all['List'], kTestValues2['flutter.List']);
});
testWidgets('removing', (WidgetTester _) async {
const String key = 'testKey';
await Future.wait(<Future<bool>>[
preferences.setValue('String', key, kTestValues['flutter.String']!),
preferences.setValue('Bool', key, kTestValues['flutter.bool']!),
preferences.setValue('Int', key, kTestValues['flutter.int']!),
preferences.setValue('Double', key, kTestValues['flutter.double']!),
preferences.setValue('StringList', key, kTestValues['flutter.List']!)
]);
await preferences.remove(key);
final Map<String, Object> all = await preferences.getAll();
expect(all['testKey'], isNull);
});
testWidgets('clearing', (WidgetTester _) async {
await Future.wait(<Future<bool>>[
preferences.setValue(
'String', 'String', kTestValues['flutter.String']!),
preferences.setValue('Bool', 'bool', kTestValues['flutter.bool']!),
preferences.setValue('Int', 'int', kTestValues['flutter.int']!),
preferences.setValue(
'Double', 'double', kTestValues['flutter.double']!),
preferences.setValue('StringList', 'List', kTestValues['flutter.List']!)
]);
await preferences.clear();
final Map<String, Object> all = await preferences.getAll();
expect(all['String'], null);
expect(all['bool'], null);
expect(all['int'], null);
expect(all['double'], null);
expect(all['List'], null);
});
});
}
| plugins/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart",
"repo_id": "plugins",
"token_count": 1505
} | 1,262 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:shared_preferences_windows/shared_preferences_windows.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('SharedPreferencesWindows', () {
const Map<String, Object> kTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.bool': true,
'flutter.int': 42,
'flutter.double': 3.14159,
'flutter.List': <String>['foo', 'bar'],
};
const Map<String, Object> kTestValues2 = <String, Object>{
'flutter.String': 'goodbye world',
'flutter.bool': false,
'flutter.int': 1337,
'flutter.double': 2.71828,
'flutter.List': <String>['baz', 'quox'],
};
testWidgets('reading', (WidgetTester _) async {
final SharedPreferencesWindows preferences = SharedPreferencesWindows();
preferences.clear();
final Map<String, Object> values = await preferences.getAll();
expect(values['String'], isNull);
expect(values['bool'], isNull);
expect(values['int'], isNull);
expect(values['double'], isNull);
expect(values['List'], isNull);
});
testWidgets('writing', (WidgetTester _) async {
final SharedPreferencesWindows preferences = SharedPreferencesWindows();
preferences.clear();
await preferences.setValue(
'String', 'String', kTestValues2['flutter.String']!);
await preferences.setValue('Bool', 'bool', kTestValues2['flutter.bool']!);
await preferences.setValue('Int', 'int', kTestValues2['flutter.int']!);
await preferences.setValue(
'Double', 'double', kTestValues2['flutter.double']!);
await preferences.setValue(
'StringList', 'List', kTestValues2['flutter.List']!);
final Map<String, Object> values = await preferences.getAll();
expect(values['String'], kTestValues2['flutter.String']);
expect(values['bool'], kTestValues2['flutter.bool']);
expect(values['int'], kTestValues2['flutter.int']);
expect(values['double'], kTestValues2['flutter.double']);
expect(values['List'], kTestValues2['flutter.List']);
});
testWidgets('removing', (WidgetTester _) async {
final SharedPreferencesWindows preferences = SharedPreferencesWindows();
preferences.clear();
const String key = 'testKey';
await preferences.setValue('String', key, kTestValues['flutter.String']!);
await preferences.setValue('Bool', key, kTestValues['flutter.bool']!);
await preferences.setValue('Int', key, kTestValues['flutter.int']!);
await preferences.setValue('Double', key, kTestValues['flutter.double']!);
await preferences.setValue(
'StringList', key, kTestValues['flutter.List']!);
await preferences.remove(key);
final Map<String, Object> values = await preferences.getAll();
expect(values[key], isNull);
});
testWidgets('clearing', (WidgetTester _) async {
final SharedPreferencesWindows preferences = SharedPreferencesWindows();
preferences.clear();
await preferences.setValue(
'String', 'String', kTestValues['flutter.String']!);
await preferences.setValue('Bool', 'bool', kTestValues['flutter.bool']!);
await preferences.setValue('Int', 'int', kTestValues['flutter.int']!);
await preferences.setValue(
'Double', 'double', kTestValues['flutter.double']!);
await preferences.setValue(
'StringList', 'List', kTestValues['flutter.List']!);
await preferences.clear();
final Map<String, Object> values = await preferences.getAll();
expect(values['String'], null);
expect(values['bool'], null);
expect(values['int'], null);
expect(values['double'], null);
expect(values['List'], null);
});
});
}
| plugins/packages/shared_preferences/shared_preferences_windows/example/integration_test/shared_preferences_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_windows/example/integration_test/shared_preferences_test.dart",
"repo_id": "plugins",
"token_count": 1489
} | 1,263 |
name: url_launcher_example
description: Demonstrates how to use the url_launcher plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
path: ^1.8.0
url_launcher:
# When depending on this package from a real application you should use:
# url_launcher: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
dev_dependencies:
build_runner: ^2.1.10
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
flutter:
uses-material-design: true
| plugins/packages/url_launcher/url_launcher/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 316
} | 1,264 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.urllauncher;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.util.Log;
import androidx.annotation.Nullable;
/** Launches components for URLs. */
class UrlLauncher {
private static final String TAG = "UrlLauncher";
private final Context applicationContext;
@Nullable private Activity activity;
/**
* Uses the given {@code applicationContext} for launching intents.
*
* <p>It may be null initially, but should be set before calling {@link #launch}.
*/
UrlLauncher(Context applicationContext, @Nullable Activity activity) {
this.applicationContext = applicationContext;
this.activity = activity;
}
void setActivity(@Nullable Activity activity) {
this.activity = activity;
}
/** Returns whether the given {@code url} resolves into an existing component. */
boolean canLaunch(String url) {
Intent launchIntent = new Intent(Intent.ACTION_VIEW);
launchIntent.setData(Uri.parse(url));
ComponentName componentName =
launchIntent.resolveActivity(applicationContext.getPackageManager());
if (componentName == null) {
Log.i(TAG, "component name for " + url + " is null");
return false;
} else {
Log.i(TAG, "component name for " + url + " is " + componentName.toShortString());
return !"{com.android.fallback/com.android.fallback.Fallback}"
.equals(componentName.toShortString());
}
}
/**
* Attempts to launch the given {@code url}.
*
* @param headersBundle forwarded to the intent as {@code Browser.EXTRA_HEADERS}.
* @param useWebView when true, the URL is launched inside of {@link WebViewActivity}.
* @param enableJavaScript Only used if {@param useWebView} is true. Enables JS in the WebView.
* @param enableDomStorage Only used if {@param useWebView} is true. Enables DOM storage in the
* @return {@link LaunchStatus#NO_ACTIVITY} if there's no available {@code applicationContext}.
* {@link LaunchStatus#ACTIVITY_NOT_FOUND} if there's no activity found to handle {@code
* launchIntent}. {@link LaunchStatus#OK} otherwise.
*/
LaunchStatus launch(
String url,
Bundle headersBundle,
boolean useWebView,
boolean enableJavaScript,
boolean enableDomStorage) {
if (activity == null) {
return LaunchStatus.NO_ACTIVITY;
}
Intent launchIntent;
if (useWebView) {
launchIntent =
WebViewActivity.createIntent(
activity, url, enableJavaScript, enableDomStorage, headersBundle);
} else {
launchIntent =
new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse(url))
.putExtra(Browser.EXTRA_HEADERS, headersBundle);
}
try {
activity.startActivity(launchIntent);
} catch (ActivityNotFoundException e) {
return LaunchStatus.ACTIVITY_NOT_FOUND;
}
return LaunchStatus.OK;
}
/** Closes any activities started with {@link #launch} {@code useWebView=true}. */
void closeWebView() {
applicationContext.sendBroadcast(new Intent(WebViewActivity.ACTION_CLOSE));
}
/** Result of a {@link #launch} call. */
enum LaunchStatus {
/** The intent was well formed. */
OK,
/** No activity was found to launch. */
NO_ACTIVITY,
/** No Activity found that can handle given intent. */
ACTIVITY_NOT_FOUND,
}
}
| plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncher.java/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncher.java",
"repo_id": "plugins",
"token_count": 1266
} | 1,265 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 3.0.2
* Updates code for stricter lint checks.
* Updates minimum Flutter version to 2.10.
## 3.0.1
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 3.0.0
* Changes the major version since, due to a typo in `default_package` in
existing versions of `url_launcher`, requiring Dart registration in this
package is in practice a breaking change.
* Does not include any API changes; clients can allow both 2.x or 3.x.
## 2.0.4
* **\[Retracted\]** Switches to an in-package method channel implementation.
## 2.0.3
* Updates code for new analysis options.
* Fix minor memory leak in Linux url_launcher tests.
* Fixes canLaunch detection for URIs addressing on local or network file systems
## 2.0.2
* Replaced reference to `shared_preferences` plugin with the `url_launcher` in the README.
## 2.0.1
* Updated installation instructions in README.
## 2.0.0
* Migrate to null safety.
* Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets.
* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276))
* Set `implementation` in pubspec.yaml
## 0.0.2+1
* Update Flutter SDK constraint.
## 0.0.2
* Update integration test examples to use `testWidgets` instead of `test`.
## 0.0.1+4
* Update Dart SDK constraint in example.
## 0.0.1+3
* Add a missing include.
## 0.0.1+2
* Check in linux/ directory for example/
# 0.0.1+1
* README update for endorsement by url_launcher.
# 0.0.1
* The initial implementation of url_launcher for Linux
| plugins/packages/url_launcher/url_launcher_linux/CHANGELOG.md/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_linux/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 538
} | 1,266 |
name: url_launcher_macos
description: macOS implementation of the url_launcher plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_macos
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:
macos:
pluginClass: UrlLauncherPlugin
fileName: url_launcher_macos.dart
dartPluginClass: UrlLauncherMacOS
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_macos/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_macos/pubspec.yaml",
"repo_id": "plugins",
"token_count": 312
} | 1,267 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.0.14
* Updates code for stricter lint checks.
* Updates minimum Flutter version to 2.10.
## 2.0.13
* Updates `url_launcher_platform_interface` constraint to the correct minimum
version.
## 2.0.12
* Fixes call to `setState` after dispose on the `Link` widget.
[Issue](https://github.com/flutter/flutter/issues/102741).
* Removes unused `BuildContext` from the `LinkViewController`.
## 2.0.11
* Minor fixes for new analysis options.
## 2.0.10
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.9
- Fixes invalid routes when opening a `Link` in a new tab
## 2.0.8
* Updates the minimum Flutter version to 2.10, which is required by the change
in 2.0.7.
## 2.0.7
* Marks the `Link` widget as invisible so it can be optimized by the engine.
## 2.0.6
* Removes dependency on `meta`.
## 2.0.5
* Updates code for new analysis options.
## 2.0.4
- Add `implements` to pubspec.
## 2.0.3
- Replaced reference to `shared_preferences` plugin with the `url_launcher` in the README.
## 2.0.2
- Updated installation instructions in README.
## 2.0.1
- Change sizing code of `Link` widget's `HtmlElementView` so it works well when slotted.
## 2.0.0
- Migrate to null safety.
## 0.1.5+3
- Fix Link misalignment [issue](https://github.com/flutter/flutter/issues/70053).
## 0.1.5+2
- Update Flutter SDK constraint.
## 0.1.5+1
- Substitute `undefined_prefixed_name: ignore` analyzer setting by a `dart:ui` shim with conditional exports. [Issue](https://github.com/flutter/flutter/issues/69309).
## 0.1.5
- Added the web implementation of the Link widget.
## 0.1.4+2
- Move `lib/third_party` to `lib/src/third_party`.
## 0.1.4+1
- Add a more correct attribution to `package:platform_detect` code.
## 0.1.4
- (Null safety) Remove dependency on `package:platform_detect`
- Port unit tests to run with `flutter drive`
## 0.1.3+2
- Fix a typo in a test name and fix some style inconsistencies.
## 0.1.3+1
- Depend explicitly on the `platform_interface` package that adds the `webOnlyWindowName` parameter.
## 0.1.3
- Added webOnlyWindowName parameter to launch()
## 0.1.2+1
- Update docs
## 0.1.2
- Adds "tel" and "sms" support
## 0.1.1+6
- Open "mailto" urls with target set as "\_top" on Safari browsers.
- Update lower bound of dart dependency to 2.2.0.
## 0.1.1+5
- Update lower bound of dart dependency to 2.1.0.
## 0.1.1+4
- Declare API stability and compatibility with `1.0.0` (more details at: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0).
## 0.1.1+3
- Refactor tests to not rely on the underlying browser behavior.
## 0.1.1+2
- Open urls with target "\_top" on iOS PWAs.
## 0.1.1+1
- Make the pedantic dev_dependency explicit.
## 0.1.1
- Added support for mailto scheme
## 0.1.0+2
- Remove androidx references from the no-op android implemenation.
## 0.1.0+1
- Add an android/ folder with no-op implementation to workaround https://github.com/flutter/flutter/issues/46304.
- Bump the minimal required Flutter version to 1.10.0.
## 0.1.0
- Update docs and pubspec.
## 0.0.2
- Switch to using `url_launcher_platform_interface`.
## 0.0.1
- Initial open-source release.
| plugins/packages/url_launcher/url_launcher_web/CHANGELOG.md/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 1183
} | 1,268 |
name: video_player_example
description: Demonstrates how to use the video_player plugin.
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
video_player:
# When depending on this package from a real application you should use:
# video_player: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
dev_dependencies:
build_runner: ^2.1.10
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
path_provider: ^2.0.6
test: any
flutter:
uses-material-design: true
assets:
- assets/flutter-mark-square-64.png
- assets/Butterfly-209.mp4
- assets/Butterfly-209.webm
- assets/bumble_bee_captions.srt
- assets/bumble_bee_captions.vtt
- assets/Audio.mp3
| plugins/packages/video_player/video_player/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/video_player/video_player/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 391
} | 1,269 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.3.10
* Adds compatibilty with version 6.0 of the platform interface.
* Fixes file URI construction in example.
* Updates code for new analysis options.
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
* Fixes violations of new analysis option use_named_constants.
* Removes an unnecessary override in example code.
## 2.3.9
* Updates ExoPlayer to 2.18.1.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.3.8
* Updates ExoPlayer to 2.18.0.
## 2.3.7
* Bumps gradle version to 7.2.1.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 2.3.6
* Updates references to the obsolete master branch.
## 2.3.5
* Sets rotationCorrection for videos recorded in landscapeRight (https://github.com/flutter/flutter/issues/60327).
## 2.3.4
* Updates ExoPlayer to 2.17.1.
## 2.3.3
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.3.2
* Updates ExoPlayer to 2.17.0.
## 2.3.1
* Renames internal method channels to avoid potential confusion with the
default implementation's method channel.
* Updates Pigeon to 2.0.1.
## 2.3.0
* Updates Pigeon to ^1.0.16.
## 2.2.17
* Splits from `video_player` as a federated implementation.
| plugins/packages/video_player/video_player_android/CHANGELOG.md/0 | {
"file_path": "plugins/packages/video_player/video_player_android/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 490
} | 1,270 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
| plugins/packages/video_player/video_player_android/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/video_player/video_player_android/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 38
} | 1,271 |
name: video_player_android
description: Android implementation of the video_player plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/video_player/video_player_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
version: 2.3.10
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: video_player
platforms:
android:
dartPluginClass: AndroidVideoPlayer
package: io.flutter.plugins.videoplayer
pluginClass: VideoPlayerPlugin
dependencies:
flutter:
sdk: flutter
video_player_platform_interface: ">=5.1.1 <7.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
pigeon: ^2.0.1
| plugins/packages/video_player/video_player_android/pubspec.yaml/0 | {
"file_path": "plugins/packages/video_player/video_player_android/pubspec.yaml",
"repo_id": "plugins",
"token_count": 306
} | 1,272 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'video_player_avfoundation'
s.version = '0.0.1'
s.summary = 'Flutter Video Player'
s.description = <<-DESC
A Flutter plugin for playing back video on a Widget surface.
Downloaded by pub (not CocoaPods).
DESC
s.homepage = 'https://github.com/flutter/plugins'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/video_player/video_player_avfoundation' }
s.documentation_url = 'https://pub.dev/packages/video_player'
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.platform = :ios, '9.0'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
end
| plugins/packages/video_player/video_player_avfoundation/ios/video_player_avfoundation.podspec/0 | {
"file_path": "plugins/packages/video_player/video_player_avfoundation/ios/video_player_avfoundation.podspec",
"repo_id": "plugins",
"token_count": 433
} | 1,273 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
void main() {
// Store the initial instance before any tests change it.
final VideoPlayerPlatform initialInstance = VideoPlayerPlatform.instance;
test('default implementation throws uninimpletemented', () async {
await expectLater(() => initialInstance.init(), throwsUnimplementedError);
});
}
| plugins/packages/video_player/video_player_platform_interface/test/video_player_platform_interface_test.dart/0 | {
"file_path": "plugins/packages/video_player/video_player_platform_interface/test/video_player_platform_interface_test.dart",
"repo_id": "plugins",
"token_count": 161
} | 1,274 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter/webview_flutter.dart';
// #docregion platform_imports
// Import for Android features.
import 'package:webview_flutter_android/webview_flutter_android.dart';
// Import for iOS features.
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
// #enddocregion platform_imports
void main() => runApp(const MaterialApp(home: WebViewExample()));
const String kNavigationExamplePage = '''
<!DOCTYPE html><html>
<head><title>Navigation Delegate Example</title></head>
<body>
<p>
The navigation delegate is set to block navigation to the youtube website.
</p>
<ul>
<ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
<ul><a href="https://www.google.com/">https://www.google.com/</a></ul>
</ul>
</body>
</html>
''';
const String kLocalExamplePage = '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Load file or HTML string example</title>
</head>
<body>
<h1>Local demo page</h1>
<p>
This is an example page used to demonstrate how to load a local file or HTML
string using the <a href="https://pub.dev/packages/webview_flutter">Flutter
webview</a> plugin.
</p>
</body>
</html>
''';
const String kTransparentBackgroundPage = '''
<!DOCTYPE html>
<html>
<head>
<title>Transparent background test</title>
</head>
<style type="text/css">
body { background: transparent; margin: 0; padding: 0; }
#container { position: relative; margin: 0; padding: 0; width: 100vw; height: 100vh; }
#shape { background: red; width: 200px; height: 200px; margin: 0; padding: 0; position: absolute; top: calc(50% - 100px); left: calc(50% - 100px); }
p { text-align: center; }
</style>
<body>
<div id="container">
<p>Transparent background test</p>
<div id="shape"></div>
</div>
</body>
</html>
''';
class WebViewExample extends StatefulWidget {
const WebViewExample({super.key});
@override
State<WebViewExample> createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
late final WebViewController _controller;
@override
void initState() {
super.initState();
// #docregion platform_features
late final PlatformWebViewControllerCreationParams params;
if (WebViewPlatform.instance is WebKitWebViewPlatform) {
params = WebKitWebViewControllerCreationParams(
allowsInlineMediaPlayback: true,
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
);
} else {
params = const PlatformWebViewControllerCreationParams();
}
final WebViewController controller =
WebViewController.fromPlatformCreationParams(params);
// #enddocregion platform_features
controller
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
debugPrint('WebView is loading (progress : $progress%)');
},
onPageStarted: (String url) {
debugPrint('Page started loading: $url');
},
onPageFinished: (String url) {
debugPrint('Page finished loading: $url');
},
onWebResourceError: (WebResourceError error) {
debugPrint('''
Page resource error:
code: ${error.errorCode}
description: ${error.description}
errorType: ${error.errorType}
isForMainFrame: ${error.isForMainFrame}
''');
},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
debugPrint('blocking navigation to ${request.url}');
return NavigationDecision.prevent;
}
debugPrint('allowing navigation to ${request.url}');
return NavigationDecision.navigate;
},
),
)
..addJavaScriptChannel(
'Toaster',
onMessageReceived: (JavaScriptMessage message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message.message)),
);
},
)
..loadRequest(Uri.parse('https://flutter.dev'));
// #docregion platform_features
if (controller.platform is AndroidWebViewController) {
AndroidWebViewController.enableDebugging(true);
(controller.platform as AndroidWebViewController)
.setMediaPlaybackRequiresUserGesture(false);
}
// #enddocregion platform_features
_controller = controller;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green,
appBar: AppBar(
title: const Text('Flutter WebView example'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
NavigationControls(webViewController: _controller),
SampleMenu(webViewController: _controller),
],
),
body: WebViewWidget(controller: _controller),
floatingActionButton: favoriteButton(),
);
}
Widget favoriteButton() {
return FloatingActionButton(
onPressed: () async {
final String? url = await _controller.currentUrl();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Favorited $url')),
);
}
},
child: const Icon(Icons.favorite),
);
}
}
enum MenuOptions {
showUserAgent,
listCookies,
clearCookies,
addToCache,
listCache,
clearCache,
navigationDelegate,
doPostRequest,
loadLocalFile,
loadFlutterAsset,
loadHtmlString,
transparentBackground,
setCookie,
}
class SampleMenu extends StatelessWidget {
SampleMenu({
super.key,
required this.webViewController,
});
final WebViewController webViewController;
late final WebViewCookieManager cookieManager = WebViewCookieManager();
@override
Widget build(BuildContext context) {
return PopupMenuButton<MenuOptions>(
key: const ValueKey<String>('ShowPopupMenu'),
onSelected: (MenuOptions value) {
switch (value) {
case MenuOptions.showUserAgent:
_onShowUserAgent();
break;
case MenuOptions.listCookies:
_onListCookies(context);
break;
case MenuOptions.clearCookies:
_onClearCookies(context);
break;
case MenuOptions.addToCache:
_onAddToCache(context);
break;
case MenuOptions.listCache:
_onListCache();
break;
case MenuOptions.clearCache:
_onClearCache(context);
break;
case MenuOptions.navigationDelegate:
_onNavigationDelegateExample();
break;
case MenuOptions.doPostRequest:
_onDoPostRequest();
break;
case MenuOptions.loadLocalFile:
_onLoadLocalFileExample();
break;
case MenuOptions.loadFlutterAsset:
_onLoadFlutterAssetExample();
break;
case MenuOptions.loadHtmlString:
_onLoadHtmlStringExample();
break;
case MenuOptions.transparentBackground:
_onTransparentBackground();
break;
case MenuOptions.setCookie:
_onSetCookie();
break;
}
},
itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
const PopupMenuItem<MenuOptions>(
value: MenuOptions.showUserAgent,
child: Text('Show user agent'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCookies,
child: Text('List cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCookies,
child: Text('Clear cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.addToCache,
child: Text('Add to cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCache,
child: Text('List cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCache,
child: Text('Clear cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.navigationDelegate,
child: Text('Navigation Delegate example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.doPostRequest,
child: Text('Post Request'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadHtmlString,
child: Text('Load HTML string'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadLocalFile,
child: Text('Load local file'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadFlutterAsset,
child: Text('Load Flutter Asset'),
),
const PopupMenuItem<MenuOptions>(
key: ValueKey<String>('ShowTransparentBackgroundExample'),
value: MenuOptions.transparentBackground,
child: Text('Transparent background example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.setCookie,
child: Text('Set cookie'),
),
],
);
}
Future<void> _onShowUserAgent() {
// Send a message with the user agent string to the Toaster JavaScript channel we registered
// with the WebView.
return webViewController.runJavaScript(
'Toaster.postMessage("User Agent: " + navigator.userAgent);',
);
}
Future<void> _onListCookies(BuildContext context) async {
final String cookies = await webViewController
.runJavaScriptReturningResult('document.cookie') as String;
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Cookies:'),
_getCookieList(cookies),
],
),
));
}
}
Future<void> _onAddToCache(BuildContext context) async {
await webViewController.runJavaScript(
'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";',
);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Added a test entry to cache.'),
));
}
}
Future<void> _onListCache() {
return webViewController.runJavaScript('caches.keys()'
// ignore: missing_whitespace_between_adjacent_strings
'.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))'
'.then((caches) => Toaster.postMessage(caches))');
}
Future<void> _onClearCache(BuildContext context) async {
await webViewController.clearCache();
await webViewController.clearLocalStorage();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Cache cleared.'),
));
}
}
Future<void> _onClearCookies(BuildContext context) async {
final bool hadCookies = await cookieManager.clearCookies();
String message = 'There were cookies. Now, they are gone!';
if (!hadCookies) {
message = 'There are no cookies.';
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
));
}
}
Future<void> _onNavigationDelegateExample() {
final String contentBase64 = base64Encode(
const Utf8Encoder().convert(kNavigationExamplePage),
);
return webViewController.loadRequest(
Uri.parse('data:text/html;base64,$contentBase64'),
);
}
Future<void> _onSetCookie() async {
await cookieManager.setCookie(
const WebViewCookie(
name: 'foo',
value: 'bar',
domain: 'httpbin.org',
path: '/anything',
),
);
await webViewController.loadRequest(Uri.parse(
'https://httpbin.org/anything',
));
}
Future<void> _onDoPostRequest() {
return webViewController.loadRequest(
Uri.parse('https://httpbin.org/post'),
method: LoadRequestMethod.post,
headers: <String, String>{'foo': 'bar', 'Content-Type': 'text/plain'},
body: Uint8List.fromList('Test Body'.codeUnits),
);
}
Future<void> _onLoadLocalFileExample() async {
final String pathToIndex = await _prepareLocalFile();
await webViewController.loadFile(pathToIndex);
}
Future<void> _onLoadFlutterAssetExample() {
return webViewController.loadFlutterAsset('assets/www/index.html');
}
Future<void> _onLoadHtmlStringExample() {
return webViewController.loadHtmlString(kLocalExamplePage);
}
Future<void> _onTransparentBackground() {
return webViewController.loadHtmlString(kTransparentBackgroundPage);
}
Widget _getCookieList(String cookies) {
if (cookies == null || cookies == '""') {
return Container();
}
final List<String> cookieList = cookies.split(';');
final Iterable<Text> cookieWidgets =
cookieList.map((String cookie) => Text(cookie));
return Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: cookieWidgets.toList(),
);
}
static Future<String> _prepareLocalFile() async {
final String tmpDir = (await getTemporaryDirectory()).path;
final File indexFile = File(
<String>{tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator));
await indexFile.create(recursive: true);
await indexFile.writeAsString(kLocalExamplePage);
return indexFile.path;
}
}
class NavigationControls extends StatelessWidget {
const NavigationControls({super.key, required this.webViewController});
final WebViewController webViewController;
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () async {
if (await webViewController.canGoBack()) {
await webViewController.goBack();
} else {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No back history item')),
);
}
}
},
),
IconButton(
icon: const Icon(Icons.arrow_forward_ios),
onPressed: () async {
if (await webViewController.canGoForward()) {
await webViewController.goForward();
} else {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No forward history item')),
);
}
}
},
),
IconButton(
icon: const Icon(Icons.replay),
onPressed: () => webViewController.reload(),
),
],
);
}
}
| plugins/packages/webview_flutter/webview_flutter/example/lib/main.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 6364
} | 1,275 |
// 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:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'navigation_delegate_test.mocks.dart';
@GenerateMocks(<Type>[WebViewPlatform, PlatformNavigationDelegate])
void main() {
group('NavigationDelegate', () {
test('onNavigationRequest', () async {
WebViewPlatform.instance = TestWebViewPlatform();
NavigationDecision onNavigationRequest(NavigationRequest request) {
return NavigationDecision.navigate;
}
final NavigationDelegate delegate = NavigationDelegate(
onNavigationRequest: onNavigationRequest,
);
verify(delegate.platform.setOnNavigationRequest(onNavigationRequest));
});
test('onPageStarted', () async {
WebViewPlatform.instance = TestWebViewPlatform();
void onPageStarted(String url) {}
final NavigationDelegate delegate = NavigationDelegate(
onPageStarted: onPageStarted,
);
verify(delegate.platform.setOnPageStarted(onPageStarted));
});
test('onPageFinished', () async {
WebViewPlatform.instance = TestWebViewPlatform();
void onPageFinished(String url) {}
final NavigationDelegate delegate = NavigationDelegate(
onPageFinished: onPageFinished,
);
verify(delegate.platform.setOnPageFinished(onPageFinished));
});
test('onProgress', () async {
WebViewPlatform.instance = TestWebViewPlatform();
void onProgress(int progress) {}
final NavigationDelegate delegate = NavigationDelegate(
onProgress: onProgress,
);
verify(delegate.platform.setOnProgress(onProgress));
});
test('onWebResourceError', () async {
WebViewPlatform.instance = TestWebViewPlatform();
void onWebResourceError(WebResourceError error) {}
final NavigationDelegate delegate = NavigationDelegate(
onWebResourceError: onWebResourceError,
);
verify(delegate.platform.setOnWebResourceError(onWebResourceError));
});
});
}
class TestWebViewPlatform extends WebViewPlatform {
@override
PlatformNavigationDelegate createPlatformNavigationDelegate(
PlatformNavigationDelegateCreationParams params,
) {
return TestMockPlatformNavigationDelegate();
}
}
class TestMockPlatformNavigationDelegate extends MockPlatformNavigationDelegate
with MockPlatformInterfaceMixin {}
| plugins/packages/webview_flutter/webview_flutter/test/navigation_delegate_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/test/navigation_delegate_test.dart",
"repo_id": "plugins",
"token_count": 919
} | 1,276 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.os.Build;
import android.webkit.CookieManager;
class CookieManagerHostApiImpl implements GeneratedAndroidWebView.CookieManagerHostApi {
@Override
public void clearCookies(GeneratedAndroidWebView.Result<Boolean> result) {
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.removeAllCookies(result::success);
} else {
final boolean hasCookies = cookieManager.hasCookies();
if (hasCookies) {
cookieManager.removeAllCookie();
}
result.success(hasCookies);
}
}
@Override
public void setCookie(String url, String value) {
CookieManager.getInstance().setCookie(url, value);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/CookieManagerHostApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/CookieManagerHostApiImpl.java",
"repo_id": "plugins",
"token_count": 312
} | 1,277 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.os.Build;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import androidx.annotation.RequiresApi;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebChromeClientFlutterApi;
import java.util.List;
import java.util.Objects;
/**
* Flutter Api implementation for {@link WebChromeClient}.
*
* <p>Passes arguments of callbacks methods from a {@link WebChromeClient} to Dart.
*/
public class WebChromeClientFlutterApiImpl extends WebChromeClientFlutterApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
/**
* Creates a Flutter api that sends messages to Dart.
*
* @param binaryMessenger handles sending messages to Dart
* @param instanceManager maintains instances stored to communicate with Dart objects
*/
public WebChromeClientFlutterApiImpl(
BinaryMessenger binaryMessenger, InstanceManager instanceManager) {
super(binaryMessenger);
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
}
/** Passes arguments from {@link WebChromeClient#onProgressChanged} to Dart. */
public void onProgressChanged(
WebChromeClient webChromeClient, WebView webView, Long progress, Reply<Void> callback) {
final Long webViewIdentifier = instanceManager.getIdentifierForStrongReference(webView);
if (webViewIdentifier == null) {
throw new IllegalStateException("Could not find identifier for WebView.");
}
super.onProgressChanged(
getIdentifierForClient(webChromeClient), webViewIdentifier, progress, callback);
}
/** Passes arguments from {@link WebChromeClient#onShowFileChooser} to Dart. */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void onShowFileChooser(
WebChromeClient webChromeClient,
WebView webView,
WebChromeClient.FileChooserParams fileChooserParams,
Reply<List<String>> callback) {
Long paramsInstanceId = instanceManager.getIdentifierForStrongReference(fileChooserParams);
if (paramsInstanceId == null) {
final FileChooserParamsFlutterApiImpl flutterApi =
new FileChooserParamsFlutterApiImpl(binaryMessenger, instanceManager);
paramsInstanceId = flutterApi.create(fileChooserParams, reply -> {});
}
onShowFileChooser(
Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(webChromeClient)),
Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(webView)),
paramsInstanceId,
callback);
}
private long getIdentifierForClient(WebChromeClient webChromeClient) {
final Long identifier = instanceManager.getIdentifierForStrongReference(webChromeClient);
if (identifier == null) {
throw new IllegalStateException("Could not find identifier for WebChromeClient.");
}
return identifier;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientFlutterApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientFlutterApiImpl.java",
"repo_id": "plugins",
"token_count": 973
} | 1,278 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutterexample;
import static androidx.test.espresso.flutter.EspressoFlutter.onFlutterWidget;
import static androidx.test.espresso.flutter.action.FlutterActions.click;
import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withText;
import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withValueKey;
import static org.junit.Assert.assertEquals;
import android.graphics.Bitmap;
import android.graphics.Color;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.screenshot.ScreenCapture;
import androidx.test.runner.screenshot.Screenshot;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class BackgroundColorTest {
@Rule
public ActivityTestRule<DriverExtensionActivity> myActivityTestRule =
new ActivityTestRule<>(DriverExtensionActivity.class, true, false);
@Before
public void setUp() {
ActivityScenario.launch(DriverExtensionActivity.class);
}
@Ignore("Doesn't run in Firebase Test Lab: https://github.com/flutter/flutter/issues/94748")
@Test
public void backgroundColor() {
onFlutterWidget(withValueKey("ShowPopupMenu")).perform(click());
onFlutterWidget(withValueKey("ShowTransparentBackgroundExample")).perform(click());
onFlutterWidget(withText("Transparent background test"));
final ScreenCapture screenCapture = Screenshot.capture();
final Bitmap screenBitmap = screenCapture.getBitmap();
final int centerLeftColor =
screenBitmap.getPixel(10, (int) Math.floor(screenBitmap.getHeight() / 2.0));
final int centerColor =
screenBitmap.getPixel(
(int) Math.floor(screenBitmap.getWidth() / 2.0),
(int) Math.floor(screenBitmap.getHeight() / 2.0));
// Flutter Colors.green color : 0xFF4CAF50
// https://github.com/flutter/flutter/blob/f4abaa0735eba4dfd8f33f73363911d63931fe03/packages/flutter/lib/src/material/colors.dart#L1208
// The background color of the webview is : rgba(0, 0, 0, 0.5)
// The expected color is : rgba(38, 87, 40, 1) -> 0xFF265728
assertEquals(0xFF265728, centerLeftColor);
assertEquals(Color.RED, centerColor);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/example/android/app/src/androidTest/java/io/flutter/plugins/webviewflutterexample/BackgroundColorTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/android/app/src/androidTest/java/io/flutter/plugins/webviewflutterexample/BackgroundColorTest.java",
"repo_id": "plugins",
"token_count": 873
} | 1,279 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v4.2.14), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
/// Mode of how to select files for a file chooser.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams.
enum FileChooserMode {
/// Open single file and requires that the file exists before allowing the
/// user to pick it.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN.
open,
/// Similar to [open] but allows multiple files to be selected.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN_MULTIPLE.
openMultiple,
/// Allows picking a nonexistent file and saving it.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_SAVE.
save,
}
class FileChooserModeEnumData {
FileChooserModeEnumData({
required this.value,
});
FileChooserMode value;
Object encode() {
return <Object?>[
value.index,
];
}
static FileChooserModeEnumData decode(Object result) {
result as List<Object?>;
return FileChooserModeEnumData(
value: FileChooserMode.values[result[0]! as int],
);
}
}
class WebResourceRequestData {
WebResourceRequestData({
required this.url,
required this.isForMainFrame,
this.isRedirect,
required this.hasGesture,
required this.method,
required this.requestHeaders,
});
String url;
bool isForMainFrame;
bool? isRedirect;
bool hasGesture;
String method;
Map<String?, String?> requestHeaders;
Object encode() {
return <Object?>[
url,
isForMainFrame,
isRedirect,
hasGesture,
method,
requestHeaders,
];
}
static WebResourceRequestData decode(Object result) {
result as List<Object?>;
return WebResourceRequestData(
url: result[0]! as String,
isForMainFrame: result[1]! as bool,
isRedirect: result[2] as bool?,
hasGesture: result[3]! as bool,
method: result[4]! as String,
requestHeaders:
(result[5] as Map<Object?, Object?>?)!.cast<String?, String?>(),
);
}
}
class WebResourceErrorData {
WebResourceErrorData({
required this.errorCode,
required this.description,
});
int errorCode;
String description;
Object encode() {
return <Object?>[
errorCode,
description,
];
}
static WebResourceErrorData decode(Object result) {
result as List<Object?>;
return WebResourceErrorData(
errorCode: result[0]! as int,
description: result[1]! as String,
);
}
}
class WebViewPoint {
WebViewPoint({
required this.x,
required this.y,
});
int x;
int y;
Object encode() {
return <Object?>[
x,
y,
];
}
static WebViewPoint decode(Object result) {
result as List<Object?>;
return WebViewPoint(
x: result[0]! as int,
y: result[1]! as int,
);
}
}
/// Handles methods calls to the native Java Object class.
///
/// Also handles calls to remove the reference to an instance with `dispose`.
///
/// See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html.
class JavaObjectHostApi {
/// Constructor for [JavaObjectHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
JavaObjectHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> dispose(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.JavaObjectHostApi.dispose', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Handles callbacks methods for the native Java Object class.
///
/// See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html.
abstract class JavaObjectFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void dispose(int identifier);
static void setup(JavaObjectFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.JavaObjectFlutterApi.dispose', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.JavaObjectFlutterApi.dispose was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.JavaObjectFlutterApi.dispose was null, expected non-null int.');
api.dispose(arg_identifier!);
return;
});
}
}
}
}
class CookieManagerHostApi {
/// Constructor for [CookieManagerHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
CookieManagerHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<bool> clearCookies() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CookieManagerHostApi.clearCookies', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(null) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
Future<void> setCookie(String arg_url, String arg_value) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CookieManagerHostApi.setCookie', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_url, arg_value]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _WebViewHostApiCodec extends StandardMessageCodec {
const _WebViewHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is WebViewPoint) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return WebViewPoint.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class WebViewHostApi {
/// Constructor for [WebViewHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
WebViewHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _WebViewHostApiCodec();
Future<void> create(int arg_instanceId, bool arg_useHybridComposition) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId, arg_useHybridComposition])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> loadData(int arg_instanceId, String arg_data,
String? arg_mimeType, String? arg_encoding) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.loadData', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(
<Object?>[arg_instanceId, arg_data, arg_mimeType, arg_encoding])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> loadDataWithBaseUrl(
int arg_instanceId,
String? arg_baseUrl,
String arg_data,
String? arg_mimeType,
String? arg_encoding,
String? arg_historyUrl) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.loadDataWithBaseUrl', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(<Object?>[
arg_instanceId,
arg_baseUrl,
arg_data,
arg_mimeType,
arg_encoding,
arg_historyUrl
]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> loadUrl(int arg_instanceId, String arg_url,
Map<String?, String?> arg_headers) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.loadUrl', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId, arg_url, arg_headers])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> postUrl(
int arg_instanceId, String arg_url, Uint8List arg_data) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.postUrl', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_url, arg_data]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<String?> getUrl(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.getUrl', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
Future<bool> canGoBack(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.canGoBack', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
Future<bool> canGoForward(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.canGoForward', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
Future<void> goBack(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.goBack', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> goForward(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.goForward', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> reload(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.reload', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> clearCache(int arg_instanceId, bool arg_includeDiskFiles) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.clearCache', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId, arg_includeDiskFiles])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<String?> evaluateJavascript(
int arg_instanceId, String arg_javascriptString) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.evaluateJavascript', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId, arg_javascriptString])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
Future<String?> getTitle(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.getTitle', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
Future<void> scrollTo(int arg_instanceId, int arg_x, int arg_y) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.scrollTo', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_x, arg_y]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> scrollBy(int arg_instanceId, int arg_x, int arg_y) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.scrollBy', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_x, arg_y]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<int> getScrollX(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.getScrollX', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as int?)!;
}
}
Future<int> getScrollY(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.getScrollY', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as int?)!;
}
}
Future<WebViewPoint> getScrollPosition(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.getScrollPosition', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as WebViewPoint?)!;
}
}
Future<void> setWebContentsDebuggingEnabled(bool arg_enabled) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.setWebContentsDebuggingEnabled',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_enabled]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setWebViewClient(
int arg_instanceId, int arg_webViewClientInstanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.setWebViewClient', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_webViewClientInstanceId])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> addJavaScriptChannel(
int arg_instanceId, int arg_javaScriptChannelInstanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.addJavaScriptChannel', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_javaScriptChannelInstanceId])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> removeJavaScriptChannel(
int arg_instanceId, int arg_javaScriptChannelInstanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.removeJavaScriptChannel', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_javaScriptChannelInstanceId])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setDownloadListener(
int arg_instanceId, int? arg_listenerInstanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.setDownloadListener', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId, arg_listenerInstanceId])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setWebChromeClient(
int arg_instanceId, int? arg_clientInstanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.setWebChromeClient', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId, arg_clientInstanceId])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setBackgroundColor(int arg_instanceId, int arg_color) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewHostApi.setBackgroundColor', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_color]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class WebSettingsHostApi {
/// Constructor for [WebSettingsHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
WebSettingsHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_instanceId, int arg_webViewInstanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId, arg_webViewInstanceId])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setDomStorageEnabled(int arg_instanceId, bool arg_flag) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setDomStorageEnabled', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_flag]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setJavaScriptCanOpenWindowsAutomatically(
int arg_instanceId, bool arg_flag) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setJavaScriptCanOpenWindowsAutomatically',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_flag]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setSupportMultipleWindows(
int arg_instanceId, bool arg_support) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setSupportMultipleWindows',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_support]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setJavaScriptEnabled(int arg_instanceId, bool arg_flag) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setJavaScriptEnabled', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_flag]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setUserAgentString(
int arg_instanceId, String? arg_userAgentString) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setUserAgentString', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_userAgentString]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setMediaPlaybackRequiresUserGesture(
int arg_instanceId, bool arg_require) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setMediaPlaybackRequiresUserGesture',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_require]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setSupportZoom(int arg_instanceId, bool arg_support) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setSupportZoom', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_support]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setLoadWithOverviewMode(
int arg_instanceId, bool arg_overview) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setLoadWithOverviewMode', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_overview]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setUseWideViewPort(int arg_instanceId, bool arg_use) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setUseWideViewPort', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_use]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setDisplayZoomControls(
int arg_instanceId, bool arg_enabled) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setDisplayZoomControls', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_enabled]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setBuiltInZoomControls(
int arg_instanceId, bool arg_enabled) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setBuiltInZoomControls', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_enabled]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setAllowFileAccess(int arg_instanceId, bool arg_enabled) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebSettingsHostApi.setAllowFileAccess', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_enabled]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class JavaScriptChannelHostApi {
/// Constructor for [JavaScriptChannelHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
JavaScriptChannelHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_instanceId, String arg_channelName) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.JavaScriptChannelHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_channelName]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
abstract class JavaScriptChannelFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void postMessage(int instanceId, String message);
static void setup(JavaScriptChannelFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.JavaScriptChannelFlutterApi.postMessage', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.JavaScriptChannelFlutterApi.postMessage was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.JavaScriptChannelFlutterApi.postMessage was null, expected non-null int.');
final String? arg_message = (args[1] as String?);
assert(arg_message != null,
'Argument for dev.flutter.pigeon.JavaScriptChannelFlutterApi.postMessage was null, expected non-null String.');
api.postMessage(arg_instanceId!, arg_message!);
return;
});
}
}
}
}
class WebViewClientHostApi {
/// Constructor for [WebViewClientHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
WebViewClientHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setSynchronousReturnValueForShouldOverrideUrlLoading(
int arg_instanceId, bool arg_value) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_value]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _WebViewClientFlutterApiCodec extends StandardMessageCodec {
const _WebViewClientFlutterApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is WebResourceErrorData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is WebResourceRequestData) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return WebResourceErrorData.decode(readValue(buffer)!);
case 129:
return WebResourceRequestData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class WebViewClientFlutterApi {
static const MessageCodec<Object?> codec = _WebViewClientFlutterApiCodec();
void onPageStarted(int instanceId, int webViewInstanceId, String url);
void onPageFinished(int instanceId, int webViewInstanceId, String url);
void onReceivedRequestError(int instanceId, int webViewInstanceId,
WebResourceRequestData request, WebResourceErrorData error);
void onReceivedError(int instanceId, int webViewInstanceId, int errorCode,
String description, String failingUrl);
void requestLoading(
int instanceId, int webViewInstanceId, WebResourceRequestData request);
void urlLoading(int instanceId, int webViewInstanceId, String url);
static void setup(WebViewClientFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientFlutterApi.onPageStarted', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageStarted was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageStarted was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageStarted was null, expected non-null int.');
final String? arg_url = (args[2] as String?);
assert(arg_url != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageStarted was null, expected non-null String.');
api.onPageStarted(arg_instanceId!, arg_webViewInstanceId!, arg_url!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientFlutterApi.onPageFinished', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageFinished was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageFinished was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageFinished was null, expected non-null int.');
final String? arg_url = (args[2] as String?);
assert(arg_url != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onPageFinished was null, expected non-null String.');
api.onPageFinished(arg_instanceId!, arg_webViewInstanceId!, arg_url!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedRequestError',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedRequestError was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null int.');
final WebResourceRequestData? arg_request =
(args[2] as WebResourceRequestData?);
assert(arg_request != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null WebResourceRequestData.');
final WebResourceErrorData? arg_error =
(args[3] as WebResourceErrorData?);
assert(arg_error != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedRequestError was null, expected non-null WebResourceErrorData.');
api.onReceivedRequestError(arg_instanceId!, arg_webViewInstanceId!,
arg_request!, arg_error!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedError', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedError was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedError was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedError was null, expected non-null int.');
final int? arg_errorCode = (args[2] as int?);
assert(arg_errorCode != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedError was null, expected non-null int.');
final String? arg_description = (args[3] as String?);
assert(arg_description != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedError was null, expected non-null String.');
final String? arg_failingUrl = (args[4] as String?);
assert(arg_failingUrl != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.onReceivedError was null, expected non-null String.');
api.onReceivedError(arg_instanceId!, arg_webViewInstanceId!,
arg_errorCode!, arg_description!, arg_failingUrl!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientFlutterApi.requestLoading', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.requestLoading was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.requestLoading was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.requestLoading was null, expected non-null int.');
final WebResourceRequestData? arg_request =
(args[2] as WebResourceRequestData?);
assert(arg_request != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.requestLoading was null, expected non-null WebResourceRequestData.');
api.requestLoading(
arg_instanceId!, arg_webViewInstanceId!, arg_request!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebViewClientFlutterApi.urlLoading', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.urlLoading was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.urlLoading was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.urlLoading was null, expected non-null int.');
final String? arg_url = (args[2] as String?);
assert(arg_url != null,
'Argument for dev.flutter.pigeon.WebViewClientFlutterApi.urlLoading was null, expected non-null String.');
api.urlLoading(arg_instanceId!, arg_webViewInstanceId!, arg_url!);
return;
});
}
}
}
}
class DownloadListenerHostApi {
/// Constructor for [DownloadListenerHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
DownloadListenerHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.DownloadListenerHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
abstract class DownloadListenerFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void onDownloadStart(int instanceId, String url, String userAgent,
String contentDisposition, String mimetype, int contentLength);
static void setup(DownloadListenerFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null int.');
final String? arg_url = (args[1] as String?);
assert(arg_url != null,
'Argument for dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.');
final String? arg_userAgent = (args[2] as String?);
assert(arg_userAgent != null,
'Argument for dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.');
final String? arg_contentDisposition = (args[3] as String?);
assert(arg_contentDisposition != null,
'Argument for dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.');
final String? arg_mimetype = (args[4] as String?);
assert(arg_mimetype != null,
'Argument for dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null String.');
final int? arg_contentLength = (args[5] as int?);
assert(arg_contentLength != null,
'Argument for dev.flutter.pigeon.DownloadListenerFlutterApi.onDownloadStart was null, expected non-null int.');
api.onDownloadStart(arg_instanceId!, arg_url!, arg_userAgent!,
arg_contentDisposition!, arg_mimetype!, arg_contentLength!);
return;
});
}
}
}
}
class WebChromeClientHostApi {
/// Constructor for [WebChromeClientHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
WebChromeClientHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebChromeClientHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setSynchronousReturnValueForOnShowFileChooser(
int arg_instanceId, bool arg_value) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebChromeClientHostApi.setSynchronousReturnValueForOnShowFileChooser',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_instanceId, arg_value]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class FlutterAssetManagerHostApi {
/// Constructor for [FlutterAssetManagerHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
FlutterAssetManagerHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<List<String?>> list(String arg_path) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FlutterAssetManagerHostApi.list', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_path]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as List<Object?>?)!.cast<String?>();
}
}
Future<String> getAssetFilePathByName(String arg_name) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FlutterAssetManagerHostApi.getAssetFilePathByName',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_name]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as String?)!;
}
}
}
abstract class WebChromeClientFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void onProgressChanged(int instanceId, int webViewInstanceId, int progress);
Future<List<String?>> onShowFileChooser(
int instanceId, int webViewInstanceId, int paramsInstanceId);
static void setup(WebChromeClientFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebChromeClientFlutterApi.onProgressChanged',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onProgressChanged was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onProgressChanged was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onProgressChanged was null, expected non-null int.');
final int? arg_progress = (args[2] as int?);
assert(arg_progress != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onProgressChanged was null, expected non-null int.');
api.onProgressChanged(
arg_instanceId!, arg_webViewInstanceId!, arg_progress!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebChromeClientFlutterApi.onShowFileChooser',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onShowFileChooser was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onShowFileChooser was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onShowFileChooser was null, expected non-null int.');
final int? arg_paramsInstanceId = (args[2] as int?);
assert(arg_paramsInstanceId != null,
'Argument for dev.flutter.pigeon.WebChromeClientFlutterApi.onShowFileChooser was null, expected non-null int.');
final List<String?> output = await api.onShowFileChooser(
arg_instanceId!, arg_webViewInstanceId!, arg_paramsInstanceId!);
return output;
});
}
}
}
}
class WebStorageHostApi {
/// Constructor for [WebStorageHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
WebStorageHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebStorageHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> deleteAllData(int arg_instanceId) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.WebStorageHostApi.deleteAllData', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_instanceId]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _FileChooserParamsFlutterApiCodec extends StandardMessageCodec {
const _FileChooserParamsFlutterApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is FileChooserModeEnumData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return FileChooserModeEnumData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Handles callbacks methods for the native Java FileChooserParams class.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams.
abstract class FileChooserParamsFlutterApi {
static const MessageCodec<Object?> codec =
_FileChooserParamsFlutterApiCodec();
void create(int instanceId, bool isCaptureEnabled, List<String?> acceptTypes,
FileChooserModeEnumData mode, String? filenameHint);
static void setup(FileChooserParamsFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileChooserParamsFlutterApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.FileChooserParamsFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.FileChooserParamsFlutterApi.create was null, expected non-null int.');
final bool? arg_isCaptureEnabled = (args[1] as bool?);
assert(arg_isCaptureEnabled != null,
'Argument for dev.flutter.pigeon.FileChooserParamsFlutterApi.create was null, expected non-null bool.');
final List<String?>? arg_acceptTypes =
(args[2] as List<Object?>?)?.cast<String?>();
assert(arg_acceptTypes != null,
'Argument for dev.flutter.pigeon.FileChooserParamsFlutterApi.create was null, expected non-null List<String?>.');
final FileChooserModeEnumData? arg_mode =
(args[3] as FileChooserModeEnumData?);
assert(arg_mode != null,
'Argument for dev.flutter.pigeon.FileChooserParamsFlutterApi.create was null, expected non-null FileChooserModeEnumData.');
final String? arg_filenameHint = (args[4] as String?);
api.create(arg_instanceId!, arg_isCaptureEnabled!, arg_acceptTypes!,
arg_mode!, arg_filenameHint);
return;
});
}
}
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview.g.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview.g.dart",
"repo_id": "plugins",
"token_count": 29235
} | 1,280 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:webview_flutter_android/src/android_proxy.dart';
import 'package:webview_flutter_android/src/android_webview.dart'
as android_webview;
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
void main() {
group('AndroidNavigationDelegate', () {
test('onPageFinished', () {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
late final String callbackUrl;
androidNavigationDelegate
.setOnPageFinished((String url) => callbackUrl = url);
CapturingWebViewClient.lastCreatedDelegate.onPageFinished!(
android_webview.WebView.detached(),
'https://www.google.com',
);
expect(callbackUrl, 'https://www.google.com');
});
test('onPageStarted', () {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
late final String callbackUrl;
androidNavigationDelegate
.setOnPageStarted((String url) => callbackUrl = url);
CapturingWebViewClient.lastCreatedDelegate.onPageStarted!(
android_webview.WebView.detached(),
'https://www.google.com',
);
expect(callbackUrl, 'https://www.google.com');
});
test('onWebResourceError from onReceivedRequestError', () {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
late final WebResourceError callbackError;
androidNavigationDelegate.setOnWebResourceError(
(WebResourceError error) => callbackError = error);
CapturingWebViewClient.lastCreatedDelegate.onReceivedRequestError!(
android_webview.WebView.detached(),
android_webview.WebResourceRequest(
url: 'https://www.google.com',
isForMainFrame: false,
isRedirect: true,
hasGesture: true,
method: 'GET',
requestHeaders: <String, String>{'X-Mock': 'mocking'},
),
android_webview.WebResourceError(
errorCode: android_webview.WebViewClient.errorFileNotFound,
description: 'Page not found.',
),
);
expect(callbackError.errorCode,
android_webview.WebViewClient.errorFileNotFound);
expect(callbackError.description, 'Page not found.');
expect(callbackError.errorType, WebResourceErrorType.fileNotFound);
expect(callbackError.isForMainFrame, false);
});
test('onWebResourceError from onRequestError', () {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
late final WebResourceError callbackError;
androidNavigationDelegate.setOnWebResourceError(
(WebResourceError error) => callbackError = error);
CapturingWebViewClient.lastCreatedDelegate.onReceivedError!(
android_webview.WebView.detached(),
android_webview.WebViewClient.errorFileNotFound,
'Page not found.',
'https://www.google.com',
);
expect(callbackError.errorCode,
android_webview.WebViewClient.errorFileNotFound);
expect(callbackError.description, 'Page not found.');
expect(callbackError.errorType, WebResourceErrorType.fileNotFound);
expect(callbackError.isForMainFrame, true);
});
test(
'onNavigationRequest from requestLoading should not be called when loadUrlCallback is not specified',
() {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
NavigationRequest? callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.prevent;
});
CapturingWebViewClient.lastCreatedDelegate.requestLoading!(
android_webview.WebView.detached(),
android_webview.WebResourceRequest(
url: 'https://www.google.com',
isForMainFrame: true,
isRedirect: true,
hasGesture: true,
method: 'GET',
requestHeaders: <String, String>{'X-Mock': 'mocking'},
),
);
expect(callbackNavigationRequest, isNull);
});
test(
'onLoadRequest from requestLoading should not be called when navigationRequestCallback is not specified',
() {
final Completer<void> completer = Completer<void>();
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((_) {
completer.complete();
return completer.future;
});
CapturingWebViewClient.lastCreatedDelegate.requestLoading!(
android_webview.WebView.detached(),
android_webview.WebResourceRequest(
url: 'https://www.google.com',
isForMainFrame: true,
isRedirect: true,
hasGesture: true,
method: 'GET',
requestHeaders: <String, String>{'X-Mock': 'mocking'},
),
);
expect(completer.isCompleted, false);
});
test(
'onLoadRequest from requestLoading should not be called when onNavigationRequestCallback returns NavigationDecision.prevent',
() {
final Completer<void> completer = Completer<void>();
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((_) {
completer.complete();
return completer.future;
});
late final NavigationRequest callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.prevent;
});
CapturingWebViewClient.lastCreatedDelegate.requestLoading!(
android_webview.WebView.detached(),
android_webview.WebResourceRequest(
url: 'https://www.google.com',
isForMainFrame: true,
isRedirect: true,
hasGesture: true,
method: 'GET',
requestHeaders: <String, String>{'X-Mock': 'mocking'},
),
);
expect(callbackNavigationRequest.isMainFrame, true);
expect(callbackNavigationRequest.url, 'https://www.google.com');
expect(completer.isCompleted, false);
});
test(
'onLoadRequest from requestLoading should complete when onNavigationRequestCallback returns NavigationDecision.navigate',
() {
final Completer<void> completer = Completer<void>();
late final LoadRequestParams loadRequestParams;
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) {
loadRequestParams = params;
completer.complete();
return completer.future;
});
late final NavigationRequest callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.navigate;
});
CapturingWebViewClient.lastCreatedDelegate.requestLoading!(
android_webview.WebView.detached(),
android_webview.WebResourceRequest(
url: 'https://www.google.com',
isForMainFrame: true,
isRedirect: true,
hasGesture: true,
method: 'GET',
requestHeaders: <String, String>{'X-Mock': 'mocking'},
),
);
expect(loadRequestParams.uri.toString(), 'https://www.google.com');
expect(loadRequestParams.headers, <String, String>{'X-Mock': 'mocking'});
expect(callbackNavigationRequest.isMainFrame, true);
expect(callbackNavigationRequest.url, 'https://www.google.com');
expect(completer.isCompleted, true);
});
test(
'onNavigationRequest from urlLoading should not be called when loadUrlCallback is not specified',
() {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
NavigationRequest? callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.prevent;
});
CapturingWebViewClient.lastCreatedDelegate.urlLoading!(
android_webview.WebView.detached(),
'https://www.google.com',
);
expect(callbackNavigationRequest, isNull);
});
test(
'onLoadRequest from urlLoading should not be called when navigationRequestCallback is not specified',
() {
final Completer<void> completer = Completer<void>();
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((_) {
completer.complete();
return completer.future;
});
CapturingWebViewClient.lastCreatedDelegate.urlLoading!(
android_webview.WebView.detached(),
'https://www.google.com',
);
expect(completer.isCompleted, false);
});
test(
'onLoadRequest from urlLoading should not be called when onNavigationRequestCallback returns NavigationDecision.prevent',
() {
final Completer<void> completer = Completer<void>();
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((_) {
completer.complete();
return completer.future;
});
late final NavigationRequest callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.prevent;
});
CapturingWebViewClient.lastCreatedDelegate.urlLoading!(
android_webview.WebView.detached(),
'https://www.google.com',
);
expect(callbackNavigationRequest.isMainFrame, true);
expect(callbackNavigationRequest.url, 'https://www.google.com');
expect(completer.isCompleted, false);
});
test(
'onLoadRequest from urlLoading should complete when onNavigationRequestCallback returns NavigationDecision.navigate',
() {
final Completer<void> completer = Completer<void>();
late final LoadRequestParams loadRequestParams;
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) {
loadRequestParams = params;
completer.complete();
return completer.future;
});
late final NavigationRequest callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.navigate;
});
CapturingWebViewClient.lastCreatedDelegate.urlLoading!(
android_webview.WebView.detached(),
'https://www.google.com',
);
expect(loadRequestParams.uri.toString(), 'https://www.google.com');
expect(loadRequestParams.headers, <String, String>{});
expect(callbackNavigationRequest.isMainFrame, true);
expect(callbackNavigationRequest.url, 'https://www.google.com');
expect(completer.isCompleted, true);
});
test('setOnNavigationRequest should override URL loading', () {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnNavigationRequest(
(NavigationRequest request) => NavigationDecision.navigate,
);
expect(
CapturingWebViewClient.lastCreatedDelegate
.synchronousReturnValueForShouldOverrideUrlLoading,
isTrue);
});
test(
'onLoadRequest from onDownloadStart should not be called when navigationRequestCallback is not specified',
() {
final Completer<void> completer = Completer<void>();
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((_) {
completer.complete();
return completer.future;
});
CapturingDownloadListener.lastCreatedListener.onDownloadStart(
'',
'',
'',
'',
0,
);
expect(completer.isCompleted, false);
});
test(
'onLoadRequest from onDownloadStart should not be called when onNavigationRequestCallback returns NavigationDecision.prevent',
() {
final Completer<void> completer = Completer<void>();
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((_) {
completer.complete();
return completer.future;
});
late final NavigationRequest callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.prevent;
});
CapturingDownloadListener.lastCreatedListener.onDownloadStart(
'https://www.google.com',
'',
'',
'',
0,
);
expect(callbackNavigationRequest.isMainFrame, true);
expect(callbackNavigationRequest.url, 'https://www.google.com');
expect(completer.isCompleted, false);
});
test(
'onLoadRequest from onDownloadStart should complete when onNavigationRequestCallback returns NavigationDecision.navigate',
() {
final Completer<void> completer = Completer<void>();
late final LoadRequestParams loadRequestParams;
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(_buildCreationParams());
androidNavigationDelegate.setOnLoadRequest((LoadRequestParams params) {
loadRequestParams = params;
completer.complete();
return completer.future;
});
late final NavigationRequest callbackNavigationRequest;
androidNavigationDelegate
.setOnNavigationRequest((NavigationRequest navigationRequest) {
callbackNavigationRequest = navigationRequest;
return NavigationDecision.navigate;
});
CapturingDownloadListener.lastCreatedListener.onDownloadStart(
'https://www.google.com',
'',
'',
'',
0,
);
expect(loadRequestParams.uri.toString(), 'https://www.google.com');
expect(loadRequestParams.headers, <String, String>{});
expect(callbackNavigationRequest.isMainFrame, true);
expect(callbackNavigationRequest.url, 'https://www.google.com');
expect(completer.isCompleted, true);
});
});
}
AndroidNavigationDelegateCreationParams _buildCreationParams() {
return AndroidNavigationDelegateCreationParams
.fromPlatformNavigationDelegateCreationParams(
const PlatformNavigationDelegateCreationParams(),
androidWebViewProxy: const AndroidWebViewProxy(
createAndroidWebChromeClient: CapturingWebChromeClient.new,
createAndroidWebViewClient: CapturingWebViewClient.new,
createDownloadListener: CapturingDownloadListener.new,
),
);
}
// Records the last created instance of itself.
class CapturingWebViewClient extends android_webview.WebViewClient {
CapturingWebViewClient({
super.onPageFinished,
super.onPageStarted,
super.onReceivedError,
super.onReceivedRequestError,
super.requestLoading,
super.urlLoading,
}) : super.detached() {
lastCreatedDelegate = this;
}
static CapturingWebViewClient lastCreatedDelegate = CapturingWebViewClient();
bool synchronousReturnValueForShouldOverrideUrlLoading = false;
@override
Future<void> setSynchronousReturnValueForShouldOverrideUrlLoading(
bool value) async {
synchronousReturnValueForShouldOverrideUrlLoading = value;
}
}
// Records the last created instance of itself.
class CapturingWebChromeClient extends android_webview.WebChromeClient {
CapturingWebChromeClient({
super.onProgressChanged,
super.onShowFileChooser,
}) : super.detached() {
lastCreatedDelegate = this;
}
static CapturingWebChromeClient lastCreatedDelegate =
CapturingWebChromeClient();
}
// Records the last created instance of itself.
class CapturingDownloadListener extends android_webview.DownloadListener {
CapturingDownloadListener({
required super.onDownloadStart,
}) : super.detached() {
lastCreatedListener = this;
}
static CapturingDownloadListener lastCreatedListener =
CapturingDownloadListener(onDownloadStart: (_, __, ___, ____, _____) {});
}
| plugins/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart",
"repo_id": "plugins",
"token_count": 6513
} | 1,281 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'javascript_mode.dart';
/// A single setting for configuring a WebViewPlatform which may be absent.
@immutable
class WebSetting<T> {
/// Constructs an absent setting instance.
///
/// The [isPresent] field for the instance will be false.
///
/// Accessing [value] for an absent instance will throw.
const WebSetting.absent()
: _value = null,
isPresent = false;
/// Constructs a setting of the given `value`.
///
/// The [isPresent] field for the instance will be true.
const WebSetting.of(T value)
: _value = value,
isPresent = true;
final T? _value;
/// The setting's value.
///
/// Throws if [WebSetting.isPresent] is false.
T get value {
if (!isPresent) {
throw StateError('Cannot access a value of an absent WebSetting');
}
assert(isPresent);
// The intention of this getter is to return T whether it is nullable or
// not whereas _value is of type T? since _value can be null even when
// T is not nullable (when isPresent == false).
//
// We promote _value to T using `as T` instead of `!` operator to handle
// the case when _value is legitimately null (and T is a nullable type).
// `!` operator would always throw if _value is null.
return _value as T;
}
/// True when this web setting instance contains a value.
///
/// When false the [WebSetting.value] getter throws.
final bool isPresent;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is WebSetting<T> &&
other.isPresent == isPresent &&
other._value == _value;
}
@override
int get hashCode => Object.hash(_value, isPresent);
}
/// Settings for configuring a WebViewPlatform.
///
/// Initial settings are passed as part of [CreationParams], settings updates are sent with
/// [WebViewPlatform#updateSettings].
///
/// The `userAgent` parameter must not be null.
class WebSettings {
/// Construct an instance with initial settings. Future setting changes can be
/// sent with [WebviewPlatform#updateSettings].
///
/// The `userAgent` parameter must not be null.
WebSettings({
this.javascriptMode,
this.hasNavigationDelegate,
this.hasProgressTracking,
this.debuggingEnabled,
this.gestureNavigationEnabled,
this.allowsInlineMediaPlayback,
this.zoomEnabled,
required this.userAgent,
}) : assert(userAgent != null);
/// The JavaScript execution mode to be used by the webview.
final JavascriptMode? javascriptMode;
/// Whether the [WebView] has a [NavigationDelegate] set.
final bool? hasNavigationDelegate;
/// Whether the [WebView] should track page loading progress.
/// See also: [WebViewPlatformCallbacksHandler.onProgress] to get the progress.
final bool? hasProgressTracking;
/// Whether to enable the platform's webview content debugging tools.
///
/// See also: [WebView.debuggingEnabled].
final bool? debuggingEnabled;
/// Whether to play HTML5 videos inline or use the native full-screen controller on iOS.
///
/// This will have no effect on Android.
final bool? allowsInlineMediaPlayback;
/// The value used for the HTTP `User-Agent:` request header.
///
/// If [userAgent.value] is null the platform's default user agent should be used.
///
/// An absent value ([userAgent.isPresent] is false) represents no change to this setting from the
/// last time it was set.
///
/// See also [WebView.userAgent].
final WebSetting<String?> userAgent;
/// Sets whether the WebView should support zooming using its on-screen zoom controls and gestures.
final bool? zoomEnabled;
/// Whether to allow swipe based navigation in iOS.
///
/// See also: [WebView.gestureNavigationEnabled]
final bool? gestureNavigationEnabled;
@override
String toString() {
return 'WebSettings(javascriptMode: $javascriptMode, hasNavigationDelegate: $hasNavigationDelegate, hasProgressTracking: $hasProgressTracking, debuggingEnabled: $debuggingEnabled, gestureNavigationEnabled: $gestureNavigationEnabled, userAgent: $userAgent, allowsInlineMediaPlayback: $allowsInlineMediaPlayback)';
}
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_settings.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_settings.dart",
"repo_id": "plugins",
"token_count": 1304
} | 1,282 |
// 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:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'webview_platform_test.mocks.dart';
@GenerateMocks(<Type>[WebViewPlatform])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('Default instance WebViewPlatform instance should be null', () {
expect(WebViewPlatform.instance, isNull);
});
// This test can only run while `WebViewPlatform.instance` is still null.
test(
'Interface classes throw assertion error when `WebViewPlatform.instance` is null',
() {
expect(
() => PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
),
throwsA(isA<AssertionError>().having(
(AssertionError error) => error.message,
'message',
'A platform implementation for `webview_flutter` has not been set. Please '
'ensure that an implementation of `WebViewPlatform` has been set to '
'`WebViewPlatform.instance` before use. For unit testing, '
'`WebViewPlatform.instance` can be set with your own test implementation.',
)),
);
expect(
() => PlatformWebViewController(
const PlatformWebViewControllerCreationParams(),
),
throwsA(isA<AssertionError>().having(
(AssertionError error) => error.message,
'message',
'A platform implementation for `webview_flutter` has not been set. Please '
'ensure that an implementation of `WebViewPlatform` has been set to '
'`WebViewPlatform.instance` before use. For unit testing, '
'`WebViewPlatform.instance` can be set with your own test implementation.',
)),
);
expect(
() => PlatformWebViewCookieManager(
const PlatformWebViewCookieManagerCreationParams(),
),
throwsA(isA<AssertionError>().having(
(AssertionError error) => error.message,
'message',
'A platform implementation for `webview_flutter` has not been set. Please '
'ensure that an implementation of `WebViewPlatform` has been set to '
'`WebViewPlatform.instance` before use. For unit testing, '
'`WebViewPlatform.instance` can be set with your own test implementation.',
)),
);
expect(
() => PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(
controller: MockWebViewControllerDelegate(),
),
),
throwsA(isA<AssertionError>().having(
(AssertionError error) => error.message,
'message',
'A platform implementation for `webview_flutter` has not been set. Please '
'ensure that an implementation of `WebViewPlatform` has been set to '
'`WebViewPlatform.instance` before use. For unit testing, '
'`WebViewPlatform.instance` can be set with your own test implementation.',
)),
);
});
test('Cannot be implemented with `implements`', () {
expect(() {
WebViewPlatform.instance = ImplementsWebViewPlatform();
// In versions of `package:plugin_platform_interface` prior to fixing
// https://github.com/flutter/flutter/issues/109339, an attempt to
// implement a platform interface using `implements` would sometimes throw
// a `NoSuchMethodError` and other times throw an `AssertionError`. After
// the issue is fixed, an `AssertionError` will always be thrown. For the
// purpose of this test, we don't really care what exception is thrown, so
// just allow any exception.
}, throwsA(anything));
});
test('Can be extended', () {
WebViewPlatform.instance = ExtendsWebViewPlatform();
});
test('Can be mocked with `implements`', () {
final MockWebViewPlatform mock = MockWebViewPlatformWithMixin();
WebViewPlatform.instance = mock;
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of createCookieManagerDelegate should throw unimplemented error',
() {
final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform();
expect(
() => webViewPlatform.createPlatformCookieManager(
const PlatformWebViewCookieManagerCreationParams()),
throwsUnimplementedError,
);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of createNavigationCallbackHandlerDelegate should throw unimplemented error',
() {
final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform();
expect(
() => webViewPlatform.createPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams()),
throwsUnimplementedError,
);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of createWebViewControllerDelegate should throw unimplemented error',
() {
final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform();
expect(
() => webViewPlatform.createPlatformWebViewController(
const PlatformWebViewControllerCreationParams()),
throwsUnimplementedError,
);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of createWebViewWidgetDelegate should throw unimplemented error',
() {
final WebViewPlatform webViewPlatform = ExtendsWebViewPlatform();
final MockWebViewControllerDelegate controller =
MockWebViewControllerDelegate();
expect(
() => webViewPlatform.createPlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller)),
throwsUnimplementedError,
);
});
}
class ImplementsWebViewPlatform implements WebViewPlatform {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class MockWebViewPlatformWithMixin extends MockWebViewPlatform
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin {}
class ExtendsWebViewPlatform extends WebViewPlatform {}
class MockWebViewControllerDelegate extends Mock
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin
implements
PlatformWebViewController {}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.dart",
"repo_id": "plugins",
"token_count": 2257
} | 1,283 |
h1 {
color: blue;
} | plugins/packages/webview_flutter/webview_flutter_wkwebview/example/assets/www/styles/style.css/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/assets/www/styles/style.css",
"repo_id": "plugins",
"token_count": 13
} | 1,284 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFUIViewHostApiTests : XCTestCase
@end
@implementation FWFUIViewHostApiTests
- (void)testSetBackgroundColor {
UIView *mockUIView = OCMClassMock([UIView class]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockUIView withIdentifier:0];
FWFUIViewHostApiImpl *hostAPI =
[[FWFUIViewHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
[hostAPI setBackgroundColorForViewWithIdentifier:@0 toValue:@123 error:&error];
OCMVerify([mockUIView setBackgroundColor:[UIColor colorWithRed:(123 >> 16 & 0xff) / 255.0
green:(123 >> 8 & 0xff) / 255.0
blue:(123 & 0xff) / 255.0
alpha:(123 >> 24 & 0xff) / 255.0]]);
XCTAssertNil(error);
}
- (void)testSetOpaque {
UIView *mockUIView = OCMClassMock([UIView class]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockUIView withIdentifier:0];
FWFUIViewHostApiImpl *hostAPI =
[[FWFUIViewHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
[hostAPI setOpaqueForViewWithIdentifier:@0 isOpaque:@YES error:&error];
OCMVerify([mockUIView setOpaque:YES]);
XCTAssertNil(error);
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUIViewHostApiTests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUIViewHostApiTests.m",
"repo_id": "plugins",
"token_count": 717
} | 1,285 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFPreferencesHostApi.h"
#import "FWFWebViewConfigurationHostApi.h"
@interface FWFPreferencesHostApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFPreferencesHostApiImpl
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (WKPreferences *)preferencesForIdentifier:(NSNumber *)identifier {
return (WKPreferences *)[self.instanceManager instanceForIdentifier:identifier.longValue];
}
- (void)createWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable *_Nonnull)error {
WKPreferences *preferences = [[WKPreferences alloc] init];
[self.instanceManager addDartCreatedInstance:preferences withIdentifier:identifier.longValue];
}
- (void)createFromWebViewConfigurationWithIdentifier:(nonnull NSNumber *)identifier
configurationIdentifier:(nonnull NSNumber *)configurationIdentifier
error:(FlutterError *_Nullable *_Nonnull)error {
WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager
instanceForIdentifier:configurationIdentifier.longValue];
[self.instanceManager addDartCreatedInstance:configuration.preferences
withIdentifier:identifier.longValue];
}
- (void)setJavaScriptEnabledForPreferencesWithIdentifier:(nonnull NSNumber *)identifier
isEnabled:(nonnull NSNumber *)enabled
error:(FlutterError *_Nullable *_Nonnull)error {
[[self preferencesForIdentifier:identifier] setJavaScriptEnabled:enabled.boolValue];
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFPreferencesHostApi.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFPreferencesHostApi.m",
"repo_id": "plugins",
"token_count": 752
} | 1,286 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFWebViewHostApi.h"
#import "FWFDataConverters.h"
@implementation FWFAssetManager
- (NSString *)lookupKeyForAsset:(NSString *)asset {
return [FlutterDartProject lookupKeyForAsset:asset];
}
@end
@implementation FWFWebView
- (instancetype)initWithFrame:(CGRect)frame
configuration:(nonnull WKWebViewConfiguration *)configuration
binaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self initWithFrame:frame configuration:configuration];
if (self) {
_objectApi = [[FWFObjectFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager];
if (@available(iOS 11.0, *)) {
self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
if (@available(iOS 13.0, *)) {
self.scrollView.automaticallyAdjustsScrollIndicatorInsets = NO;
}
}
}
return self;
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
// Prevents the contentInsets from being adjusted by iOS and gives control to Flutter.
self.scrollView.contentInset = UIEdgeInsetsZero;
if (@available(iOS 11, *)) {
// Above iOS 11, adjust contentInset to compensate the adjustedContentInset so the sum will
// always be 0.
if (UIEdgeInsetsEqualToEdgeInsets(self.scrollView.adjustedContentInset, UIEdgeInsetsZero)) {
return;
}
UIEdgeInsets insetToAdjust = self.scrollView.adjustedContentInset;
self.scrollView.contentInset = UIEdgeInsetsMake(-insetToAdjust.top, -insetToAdjust.left,
-insetToAdjust.bottom, -insetToAdjust.right);
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
context:(void *)context {
[self.objectApi observeValueForObject:self
keyPath:keyPath
object:object
change:change
completion:^(NSError *error) {
NSAssert(!error, @"%@", error);
}];
}
- (nonnull UIView *)view {
return self;
}
@end
@interface FWFWebViewHostApiImpl ()
// BinaryMessenger must be weak to prevent a circular reference with the host API it
// references.
@property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger;
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@property NSBundle *bundle;
@property FWFAssetManager *assetManager;
@end
@implementation FWFWebViewHostApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
return [self initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager
bundle:[NSBundle mainBundle]
assetManager:[[FWFAssetManager alloc] init]];
}
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager
bundle:(NSBundle *)bundle
assetManager:(FWFAssetManager *)assetManager {
self = [self init];
if (self) {
_binaryMessenger = binaryMessenger;
_instanceManager = instanceManager;
_bundle = bundle;
_assetManager = assetManager;
}
return self;
}
- (FWFWebView *)webViewForIdentifier:(NSNumber *)identifier {
return (FWFWebView *)[self.instanceManager instanceForIdentifier:identifier.longValue];
}
+ (nonnull FlutterError *)errorForURLString:(nonnull NSString *)string {
NSString *errorDetails = [NSString stringWithFormat:@"Initializing NSURL with the supplied "
@"'%@' path resulted in a nil value.",
string];
return [FlutterError errorWithCode:@"FWFURLParsingError"
message:@"Failed parsing file path."
details:errorDetails];
}
- (void)createWithIdentifier:(nonnull NSNumber *)identifier
configurationIdentifier:(nonnull NSNumber *)configurationIdentifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager
instanceForIdentifier:configurationIdentifier.longValue];
FWFWebView *webView = [[FWFWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)
configuration:configuration
binaryMessenger:self.binaryMessenger
instanceManager:self.instanceManager];
[self.instanceManager addDartCreatedInstance:webView withIdentifier:identifier.longValue];
}
- (void)loadRequestForWebViewWithIdentifier:(nonnull NSNumber *)identifier
request:(nonnull FWFNSUrlRequestData *)request
error:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
NSURLRequest *urlRequest = FWFNSURLRequestFromRequestData(request);
if (!urlRequest) {
*error = [FlutterError errorWithCode:@"FWFURLRequestParsingError"
message:@"Failed instantiating an NSURLRequest."
details:[NSString stringWithFormat:@"URL was: '%@'", request.url]];
return;
}
[[self webViewForIdentifier:identifier] loadRequest:urlRequest];
}
- (void)setUserAgentForWebViewWithIdentifier:(nonnull NSNumber *)identifier
userAgent:(nullable NSString *)userAgent
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
[[self webViewForIdentifier:identifier] setCustomUserAgent:userAgent];
}
- (nullable NSNumber *)
canGoBackForWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return @([self webViewForIdentifier:identifier].canGoBack);
}
- (nullable NSString *)
URLForWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return [self webViewForIdentifier:identifier].URL.absoluteString;
}
- (nullable NSNumber *)
canGoForwardForWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return @([[self webViewForIdentifier:identifier] canGoForward]);
}
- (nullable NSNumber *)
estimatedProgressForWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
return @([[self webViewForIdentifier:identifier] estimatedProgress]);
}
- (void)evaluateJavaScriptForWebViewWithIdentifier:(nonnull NSNumber *)identifier
javaScriptString:(nonnull NSString *)javaScriptString
completion:
(nonnull void (^)(id _Nullable,
FlutterError *_Nullable))completion {
[[self webViewForIdentifier:identifier]
evaluateJavaScript:javaScriptString
completionHandler:^(id _Nullable result, NSError *_Nullable error) {
id returnValue = nil;
FlutterError *flutterError = nil;
if (!error) {
if (!result || [result isKindOfClass:[NSString class]] ||
[result isKindOfClass:[NSNumber class]]) {
returnValue = result;
} else if (![result isKindOfClass:[NSNull class]]) {
NSString *className = NSStringFromClass([result class]);
NSLog(@"Return type of evaluateJavaScript is not directly supported: %@. Returned "
@"description of value.",
className);
returnValue = [result description];
}
} else {
flutterError = [FlutterError errorWithCode:@"FWFEvaluateJavaScriptError"
message:@"Failed evaluating JavaScript."
details:FWFNSErrorDataFromNSError(error)];
}
completion(returnValue, flutterError);
}];
}
- (void)goBackForWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] goBack];
}
- (void)goForwardForWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] goForward];
}
- (void)loadAssetForWebViewWithIdentifier:(nonnull NSNumber *)identifier
assetKey:(nonnull NSString *)key
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
NSString *assetFilePath = [self.assetManager lookupKeyForAsset:key];
NSURL *url = [self.bundle URLForResource:[assetFilePath stringByDeletingPathExtension]
withExtension:assetFilePath.pathExtension];
if (!url) {
*error = [FWFWebViewHostApiImpl errorForURLString:assetFilePath];
} else {
[[self webViewForIdentifier:identifier] loadFileURL:url
allowingReadAccessToURL:[url URLByDeletingLastPathComponent]];
}
}
- (void)loadFileForWebViewWithIdentifier:(nonnull NSNumber *)identifier
fileURL:(nonnull NSString *)url
readAccessURL:(nonnull NSString *)readAccessUrl
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
NSURL *fileURL = [NSURL fileURLWithPath:url isDirectory:NO];
NSURL *readAccessNSURL = [NSURL fileURLWithPath:readAccessUrl isDirectory:YES];
if (!fileURL) {
*error = [FWFWebViewHostApiImpl errorForURLString:url];
} else if (!readAccessNSURL) {
*error = [FWFWebViewHostApiImpl errorForURLString:readAccessUrl];
} else {
[[self webViewForIdentifier:identifier] loadFileURL:fileURL
allowingReadAccessToURL:readAccessNSURL];
}
}
- (void)loadHTMLForWebViewWithIdentifier:(nonnull NSNumber *)identifier
HTMLString:(nonnull NSString *)string
baseURL:(nullable NSString *)baseUrl
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] loadHTMLString:string
baseURL:[NSURL URLWithString:baseUrl]];
}
- (void)reloadWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] reload];
}
- (void)
setAllowsBackForwardForWebViewWithIdentifier:(nonnull NSNumber *)identifier
isAllowed:(nonnull NSNumber *)allow
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
[[self webViewForIdentifier:identifier] setAllowsBackForwardNavigationGestures:allow.boolValue];
}
- (void)
setNavigationDelegateForWebViewWithIdentifier:(nonnull NSNumber *)identifier
delegateIdentifier:(nullable NSNumber *)navigationDelegateIdentifier
error:
(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
id<WKNavigationDelegate> navigationDelegate = (id<WKNavigationDelegate>)[self.instanceManager
instanceForIdentifier:navigationDelegateIdentifier.longValue];
[[self webViewForIdentifier:identifier] setNavigationDelegate:navigationDelegate];
}
- (void)setUIDelegateForWebViewWithIdentifier:(nonnull NSNumber *)identifier
delegateIdentifier:(nullable NSNumber *)uiDelegateIdentifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
id<WKUIDelegate> navigationDelegate =
(id<WKUIDelegate>)[self.instanceManager instanceForIdentifier:uiDelegateIdentifier.longValue];
[[self webViewForIdentifier:identifier] setUIDelegate:navigationDelegate];
}
- (nullable NSString *)
titleForWebViewWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return [[self webViewForIdentifier:identifier] title];
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewHostApi.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewHostApi.m",
"repo_id": "plugins",
"token_count": 6186
} | 1,287 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../common/instance_manager.dart';
import '../foundation/foundation.dart';
import '../ui_kit/ui_kit.dart';
import 'web_kit_api_impls.dart';
export 'web_kit_api_impls.dart' show WKNavigationType;
/// Times at which to inject script content into a webpage.
///
/// Wraps [WKUserScriptInjectionTime](https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime?language=objc).
enum WKUserScriptInjectionTime {
/// Inject the script after the creation of the webpage’s document element, but before loading any other content.
///
/// See https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime/wkuserscriptinjectiontimeatdocumentstart?language=objc.
atDocumentStart,
/// Inject the script after the document finishes loading, but before loading any other subresources.
///
/// See https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime/wkuserscriptinjectiontimeatdocumentend?language=objc.
atDocumentEnd,
}
/// The media types that require a user gesture to begin playing.
///
/// Wraps [WKAudiovisualMediaTypes](https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes?language=objc).
enum WKAudiovisualMediaType {
/// No media types require a user gesture to begin playing.
///
/// See https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes/wkaudiovisualmediatypenone?language=objc.
none,
/// Media types that contain audio require a user gesture to begin playing.
///
/// See https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes/wkaudiovisualmediatypeaudio?language=objc.
audio,
/// Media types that contain video require a user gesture to begin playing.
///
/// See https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes/wkaudiovisualmediatypevideo?language=objc.
video,
/// All media types require a user gesture to begin playing.
///
/// See https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes/wkaudiovisualmediatypeall?language=objc.
all,
}
/// Types of data that websites store.
///
/// See https://developer.apple.com/documentation/webkit/wkwebsitedatarecord/data_store_record_types?language=objc.
enum WKWebsiteDataType {
/// Cookies.
cookies,
/// In-memory caches.
memoryCache,
/// On-disk caches.
diskCache,
/// HTML offline web app caches.
offlineWebApplicationCache,
/// HTML local storage.
localStorage,
/// HTML session storage.
sessionStorage,
/// WebSQL databases.
webSQLDatabases,
/// IndexedDB databases.
indexedDBDatabases,
}
/// Indicate whether to allow or cancel navigation to a webpage.
///
/// Wraps [WKNavigationActionPolicy](https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc).
enum WKNavigationActionPolicy {
/// Allow navigation to continue.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy/wknavigationactionpolicyallow?language=objc.
allow,
/// Cancel navigation.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy/wknavigationactionpolicycancel?language=objc.
cancel,
}
/// Possible error values that WebKit APIs can return.
///
/// See https://developer.apple.com/documentation/webkit/wkerrorcode.
class WKErrorCode {
WKErrorCode._();
/// Indicates an unknown issue occurred.
///
/// See https://developer.apple.com/documentation/webkit/wkerrorcode/wkerrorunknown.
static const int unknown = 1;
/// Indicates the web process that contains the content is no longer running.
///
/// See https://developer.apple.com/documentation/webkit/wkerrorcode/wkerrorwebcontentprocessterminated.
static const int webContentProcessTerminated = 2;
/// Indicates the web view was invalidated.
///
/// See https://developer.apple.com/documentation/webkit/wkerrorcode/wkerrorwebviewinvalidated.
static const int webViewInvalidated = 3;
/// Indicates a JavaScript exception occurred.
///
/// See https://developer.apple.com/documentation/webkit/wkerrorcode/wkerrorjavascriptexceptionoccurred.
static const int javaScriptExceptionOccurred = 4;
/// Indicates the result of JavaScript execution could not be returned.
///
/// See https://developer.apple.com/documentation/webkit/wkerrorcode/wkerrorjavascriptresulttypeisunsupported.
static const int javaScriptResultTypeIsUnsupported = 5;
}
/// A record of the data that a particular website stores persistently.
///
/// Wraps [WKWebsiteDataRecord](https://developer.apple.com/documentation/webkit/wkwebsitedatarecord?language=objc).
@immutable
class WKWebsiteDataRecord {
/// Constructs a [WKWebsiteDataRecord].
const WKWebsiteDataRecord({required this.displayName});
/// Identifying information that you display to users.
final String displayName;
}
/// An object that contains information about an action that causes navigation to occur.
///
/// Wraps [WKNavigationAction](https://developer.apple.com/documentation/webkit/wknavigationaction?language=objc).
@immutable
class WKNavigationAction {
/// Constructs a [WKNavigationAction].
const WKNavigationAction({
required this.request,
required this.targetFrame,
required this.navigationType,
});
/// The URL request object associated with the navigation action.
final NSUrlRequest request;
/// The frame in which to display the new content.
final WKFrameInfo targetFrame;
/// The type of action that triggered the navigation.
final WKNavigationType navigationType;
}
/// An object that contains information about a frame on a webpage.
///
/// An instance of this class is a transient, data-only object; it does not
/// uniquely identify a frame across multiple delegate method calls.
///
/// Wraps [WKFrameInfo](https://developer.apple.com/documentation/webkit/wkframeinfo?language=objc).
@immutable
class WKFrameInfo {
/// Construct a [WKFrameInfo].
const WKFrameInfo({required this.isMainFrame});
/// Indicates whether the frame is the web site's main frame or a subframe.
final bool isMainFrame;
}
/// A script that the web view injects into a webpage.
///
/// Wraps [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript?language=objc).
@immutable
class WKUserScript {
/// Constructs a [UserScript].
const WKUserScript(
this.source,
this.injectionTime, {
required this.isMainFrameOnly,
});
/// The script’s source code.
final String source;
/// The time at which to inject the script into the webpage.
final WKUserScriptInjectionTime injectionTime;
/// Indicates whether to inject the script into the main frame or all frames.
final bool isMainFrameOnly;
}
/// An object that encapsulates a message sent by JavaScript code from a webpage.
///
/// Wraps [WKScriptMessage](https://developer.apple.com/documentation/webkit/wkscriptmessage?language=objc).
@immutable
class WKScriptMessage {
/// Constructs a [WKScriptMessage].
const WKScriptMessage({required this.name, this.body});
/// The name of the message handler to which the message is sent.
final String name;
/// The body of the message.
///
/// Allowed types are [num], [String], [List], [Map], and `null`.
final Object? body;
}
/// Encapsulates the standard behaviors to apply to websites.
///
/// Wraps [WKPreferences](https://developer.apple.com/documentation/webkit/wkpreferences?language=objc).
@immutable
class WKPreferences extends NSObject {
/// Constructs a [WKPreferences] that is owned by [configuration].
factory WKPreferences.fromWebViewConfiguration(
WKWebViewConfiguration configuration, {
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
final WKPreferences preferences = WKPreferences.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
preferences._preferencesApi.createFromWebViewConfigurationForInstances(
preferences,
configuration,
);
return preferences;
}
/// Constructs a [WKPreferences] without creating the associated
/// Objective-C object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
WKPreferences.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _preferencesApi = WKPreferencesHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final WKPreferencesHostApiImpl _preferencesApi;
// TODO(bparrishMines): Deprecated for iOS 14.0+. Add support for alternative.
/// Sets whether JavaScript is enabled.
///
/// The default value is true.
Future<void> setJavaScriptEnabled(bool enabled) {
return _preferencesApi.setJavaScriptEnabledForInstances(this, enabled);
}
@override
WKPreferences copy() {
return WKPreferences.detached(
observeValue: observeValue,
binaryMessenger: _preferencesApi.binaryMessenger,
instanceManager: _preferencesApi.instanceManager,
);
}
}
/// Manages cookies, disk and memory caches, and other types of data for a web view.
///
/// Wraps [WKWebsiteDataStore](https://developer.apple.com/documentation/webkit/wkwebsitedatastore?language=objc).
@immutable
class WKWebsiteDataStore extends NSObject {
/// Constructs a [WKWebsiteDataStore] without creating the associated
/// Objective-C object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
WKWebsiteDataStore.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _websiteDataStoreApi = WKWebsiteDataStoreHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
factory WKWebsiteDataStore._defaultDataStore() {
final WKWebsiteDataStore websiteDataStore = WKWebsiteDataStore.detached();
websiteDataStore._websiteDataStoreApi.createDefaultDataStoreForInstances(
websiteDataStore,
);
return websiteDataStore;
}
/// Constructs a [WKWebsiteDataStore] that is owned by [configuration].
factory WKWebsiteDataStore.fromWebViewConfiguration(
WKWebViewConfiguration configuration, {
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
final WKWebsiteDataStore websiteDataStore = WKWebsiteDataStore.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
websiteDataStore._websiteDataStoreApi
.createFromWebViewConfigurationForInstances(
websiteDataStore,
configuration,
);
return websiteDataStore;
}
/// Default data store that stores data persistently to disk.
static final WKWebsiteDataStore defaultDataStore =
WKWebsiteDataStore._defaultDataStore();
final WKWebsiteDataStoreHostApiImpl _websiteDataStoreApi;
/// Manages the HTTP cookies associated with a particular web view.
late final WKHttpCookieStore httpCookieStore =
WKHttpCookieStore.fromWebsiteDataStore(this);
/// Removes website data that changed after the specified date.
///
/// Returns whether any data was removed.
Future<bool> removeDataOfTypes(
Set<WKWebsiteDataType> dataTypes,
DateTime since,
) {
return _websiteDataStoreApi.removeDataOfTypesForInstances(
this,
dataTypes,
secondsModifiedSinceEpoch: since.millisecondsSinceEpoch / 1000,
);
}
@override
WKWebsiteDataStore copy() {
return WKWebsiteDataStore.detached(
observeValue: observeValue,
binaryMessenger: _websiteDataStoreApi.binaryMessenger,
instanceManager: _websiteDataStoreApi.instanceManager,
);
}
}
/// An object that manages the HTTP cookies associated with a particular web view.
///
/// Wraps [WKHTTPCookieStore](https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc).
@immutable
class WKHttpCookieStore extends NSObject {
/// Constructs a [WKHttpCookieStore] without creating the associated
/// Objective-C object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
WKHttpCookieStore.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _httpCookieStoreApi = WKHttpCookieStoreHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
/// Constructs a [WKHttpCookieStore] that is owned by [dataStore].
factory WKHttpCookieStore.fromWebsiteDataStore(
WKWebsiteDataStore dataStore, {
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
final WKHttpCookieStore cookieStore = WKHttpCookieStore.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
cookieStore._httpCookieStoreApi.createFromWebsiteDataStoreForInstances(
cookieStore,
dataStore,
);
return cookieStore;
}
final WKHttpCookieStoreHostApiImpl _httpCookieStoreApi;
/// Adds a cookie to the cookie store.
Future<void> setCookie(NSHttpCookie cookie) {
return _httpCookieStoreApi.setCookieForInstances(this, cookie);
}
@override
WKHttpCookieStore copy() {
return WKHttpCookieStore.detached(
observeValue: observeValue,
binaryMessenger: _httpCookieStoreApi.binaryMessenger,
instanceManager: _httpCookieStoreApi.instanceManager,
);
}
}
/// An interface for receiving messages from JavaScript code running in a webpage.
///
/// Wraps [WKScriptMessageHandler](https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc).
@immutable
class WKScriptMessageHandler extends NSObject {
/// Constructs a [WKScriptMessageHandler].
WKScriptMessageHandler({
required this.didReceiveScriptMessage,
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _scriptMessageHandlerApi = WKScriptMessageHandlerHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached() {
// Ensures FlutterApis for the WebKit library are set up.
WebKitFlutterApis.instance.ensureSetUp();
_scriptMessageHandlerApi.createForInstances(this);
}
/// Constructs a [WKScriptMessageHandler] without creating the associated
/// Objective-C object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
WKScriptMessageHandler.detached({
required this.didReceiveScriptMessage,
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _scriptMessageHandlerApi = WKScriptMessageHandlerHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final WKScriptMessageHandlerHostApiImpl _scriptMessageHandlerApi;
/// Tells the handler that a webpage sent a script message.
///
/// Use this method to respond to a message sent from the webpage’s
/// JavaScript code. Use the [message] parameter to get the message contents and
/// to determine the originating web view.
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final void Function(
WKUserContentController userContentController,
WKScriptMessage message,
) didReceiveScriptMessage;
@override
WKScriptMessageHandler copy() {
return WKScriptMessageHandler.detached(
didReceiveScriptMessage: didReceiveScriptMessage,
observeValue: observeValue,
binaryMessenger: _scriptMessageHandlerApi.binaryMessenger,
instanceManager: _scriptMessageHandlerApi.instanceManager,
);
}
}
/// Manages interactions between JavaScript code and your web view.
///
/// Use this object to do the following:
///
/// * Inject JavaScript code into webpages running in your web view.
/// * Install custom JavaScript functions that call through to your app’s native
/// code.
///
/// Wraps [WKUserContentController](https://developer.apple.com/documentation/webkit/wkusercontentcontroller?language=objc).
@immutable
class WKUserContentController extends NSObject {
/// Constructs a [WKUserContentController] that is owned by [configuration].
factory WKUserContentController.fromWebViewConfiguration(
WKWebViewConfiguration configuration, {
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
final WKUserContentController userContentController =
WKUserContentController.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
userContentController._userContentControllerApi
.createFromWebViewConfigurationForInstances(
userContentController,
configuration,
);
return userContentController;
}
/// Constructs a [WKUserContentController] without creating the associated
/// Objective-C object.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an InstanceManager.
WKUserContentController.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _userContentControllerApi = WKUserContentControllerHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final WKUserContentControllerHostApiImpl _userContentControllerApi;
/// Installs a message handler that you can call from your JavaScript code.
///
/// This name of the parameter must be unique within the user content
/// controller and must not be an empty string. The user content controller
/// uses this parameter to define a JavaScript function for your message
/// handler in the page’s main content world. The name of this function is
/// `window.webkit.messageHandlers.<name>.postMessage(<messageBody>)`, where
/// `<name>` corresponds to the value of this parameter. For example, if you
/// specify the string `MyFunction`, the user content controller defines the `
/// `window.webkit.messageHandlers.MyFunction.postMessage()` function in
/// JavaScript.
Future<void> addScriptMessageHandler(
WKScriptMessageHandler handler,
String name,
) {
assert(name.isNotEmpty);
return _userContentControllerApi.addScriptMessageHandlerForInstances(
this,
handler,
name,
);
}
/// Uninstalls the custom message handler with the specified name from your JavaScript code.
///
/// If no message handler with this name exists in the user content
/// controller, this method does nothing.
///
/// Use this method to remove a message handler that you previously installed
/// using the [addScriptMessageHandler] method. This method removes the
/// message handler from the page content world. If you installed the message
/// handler in a different content world, this method doesn’t remove it.
Future<void> removeScriptMessageHandler(String name) {
return _userContentControllerApi.removeScriptMessageHandlerForInstances(
this,
name,
);
}
/// Uninstalls all custom message handlers associated with the user content
/// controller.
///
/// Only supported on iOS version 14+.
Future<void> removeAllScriptMessageHandlers() {
return _userContentControllerApi.removeAllScriptMessageHandlersForInstances(
this,
);
}
/// Injects the specified script into the webpage’s content.
Future<void> addUserScript(WKUserScript userScript) {
return _userContentControllerApi.addUserScriptForInstances(
this, userScript);
}
/// Removes all user scripts from the web view.
Future<void> removeAllUserScripts() {
return _userContentControllerApi.removeAllUserScriptsForInstances(this);
}
@override
WKUserContentController copy() {
return WKUserContentController.detached(
observeValue: observeValue,
binaryMessenger: _userContentControllerApi.binaryMessenger,
instanceManager: _userContentControllerApi.instanceManager,
);
}
}
/// A collection of properties that you use to initialize a web view.
///
/// Wraps [WKWebViewConfiguration](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc).
@immutable
class WKWebViewConfiguration extends NSObject {
/// Constructs a [WKWebViewConfiguration].
WKWebViewConfiguration({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _webViewConfigurationApi = WKWebViewConfigurationHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached() {
// Ensures FlutterApis for the WebKit library are set up.
WebKitFlutterApis.instance.ensureSetUp();
_webViewConfigurationApi.createForInstances(this);
}
/// A WKWebViewConfiguration that is owned by webView.
@visibleForTesting
factory WKWebViewConfiguration.fromWebView(
WKWebView webView, {
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
final WKWebViewConfiguration configuration =
WKWebViewConfiguration.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
configuration._webViewConfigurationApi.createFromWebViewForInstances(
configuration,
webView,
);
return configuration;
}
/// Constructs a [WKWebViewConfiguration] without creating the associated
/// Objective-C object.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an InstanceManager.
WKWebViewConfiguration.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _webViewConfigurationApi = WKWebViewConfigurationHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
late final WKWebViewConfigurationHostApiImpl _webViewConfigurationApi;
/// Coordinates interactions between your app’s code and the webpage’s scripts and other content.
late final WKUserContentController userContentController =
WKUserContentController.fromWebViewConfiguration(
this,
binaryMessenger: _webViewConfigurationApi.binaryMessenger,
instanceManager: _webViewConfigurationApi.instanceManager,
);
/// Manages the preference-related settings for the web view.
late final WKPreferences preferences = WKPreferences.fromWebViewConfiguration(
this,
binaryMessenger: _webViewConfigurationApi.binaryMessenger,
instanceManager: _webViewConfigurationApi.instanceManager,
);
/// Used to get and set the site’s cookies and to track the cached data objects.
///
/// Represents [WKWebViewConfiguration.webSiteDataStore](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/1395661-websitedatastore?language=objc).
late final WKWebsiteDataStore websiteDataStore =
WKWebsiteDataStore.fromWebViewConfiguration(
this,
binaryMessenger: _webViewConfigurationApi.binaryMessenger,
instanceManager: _webViewConfigurationApi.instanceManager,
);
/// Indicates whether HTML5 videos play inline or use the native full-screen controller.
///
/// Sets [WKWebViewConfiguration.allowsInlineMediaPlayback](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/1614793-allowsinlinemediaplayback?language=objc).
Future<void> setAllowsInlineMediaPlayback(bool allow) {
return _webViewConfigurationApi.setAllowsInlineMediaPlaybackForInstances(
this,
allow,
);
}
/// The media types that require a user gesture to begin playing.
///
/// Use [WKAudiovisualMediaType.none] to indicate that no user gestures are
/// required to begin playing media.
///
/// Sets [WKWebViewConfiguration.mediaTypesRequiringUserActionForPlayback](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/1851524-mediatypesrequiringuseractionfor?language=objc).
Future<void> setMediaTypesRequiringUserActionForPlayback(
Set<WKAudiovisualMediaType> types,
) {
assert(types.isNotEmpty);
return _webViewConfigurationApi
.setMediaTypesRequiringUserActionForPlaybackForInstances(
this,
types,
);
}
@override
WKWebViewConfiguration copy() {
return WKWebViewConfiguration.detached(
observeValue: observeValue,
binaryMessenger: _webViewConfigurationApi.binaryMessenger,
instanceManager: _webViewConfigurationApi.instanceManager,
);
}
}
/// The methods for presenting native user interface elements on behalf of a webpage.
///
/// Wraps [WKUIDelegate](https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc).
@immutable
class WKUIDelegate extends NSObject {
/// Constructs a [WKUIDelegate].
WKUIDelegate({
this.onCreateWebView,
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _uiDelegateApi = WKUIDelegateHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached() {
// Ensures FlutterApis for the WebKit library are set up.
WebKitFlutterApis.instance.ensureSetUp();
_uiDelegateApi.createForInstances(this);
}
/// Constructs a [WKUIDelegate] without creating the associated Objective-C
/// object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
WKUIDelegate.detached({
this.onCreateWebView,
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _uiDelegateApi = WKUIDelegateHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final WKUIDelegateHostApiImpl _uiDelegateApi;
/// Indicates a new [WKWebView] was requested to be created with [configuration].
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final void Function(
WKWebView webView,
WKWebViewConfiguration configuration,
WKNavigationAction navigationAction,
)? onCreateWebView;
@override
WKUIDelegate copy() {
return WKUIDelegate.detached(
onCreateWebView: onCreateWebView,
observeValue: observeValue,
binaryMessenger: _uiDelegateApi.binaryMessenger,
instanceManager: _uiDelegateApi.instanceManager,
);
}
}
/// Methods for handling navigation changes and tracking navigation requests.
///
/// Set the methods of the [WKNavigationDelegate] in the object you use to
/// coordinate changes in your web view’s main frame.
///
/// Wraps [WKNavigationDelegate](https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc).
@immutable
class WKNavigationDelegate extends NSObject {
/// Constructs a [WKNavigationDelegate].
WKNavigationDelegate({
this.didFinishNavigation,
this.didStartProvisionalNavigation,
this.decidePolicyForNavigationAction,
this.didFailNavigation,
this.didFailProvisionalNavigation,
this.webViewWebContentProcessDidTerminate,
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _navigationDelegateApi = WKNavigationDelegateHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached() {
// Ensures FlutterApis for the WebKit library are set up.
WebKitFlutterApis.instance.ensureSetUp();
_navigationDelegateApi.createForInstances(this);
}
/// Constructs a [WKNavigationDelegate] without creating the associated
/// Objective-C object.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an InstanceManager.
WKNavigationDelegate.detached({
this.didFinishNavigation,
this.didStartProvisionalNavigation,
this.decidePolicyForNavigationAction,
this.didFailNavigation,
this.didFailProvisionalNavigation,
this.webViewWebContentProcessDidTerminate,
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _navigationDelegateApi = WKNavigationDelegateHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final WKNavigationDelegateHostApiImpl _navigationDelegateApi;
/// Called when navigation is complete.
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final void Function(WKWebView webView, String? url)? didFinishNavigation;
/// Called when navigation from the main frame has started.
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final void Function(WKWebView webView, String? url)?
didStartProvisionalNavigation;
/// Called when permission is needed to navigate to new content.
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final Future<WKNavigationActionPolicy> Function(
WKWebView webView,
WKNavigationAction navigationAction,
)? decidePolicyForNavigationAction;
/// Called when an error occurred during navigation.
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final void Function(WKWebView webView, NSError error)? didFailNavigation;
/// Called when an error occurred during the early navigation process.
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final void Function(WKWebView webView, NSError error)?
didFailProvisionalNavigation;
/// Called when the web view’s content process was terminated.
///
/// {@macro webview_flutter_wkwebview.foundation.callbacks}
final void Function(WKWebView webView)? webViewWebContentProcessDidTerminate;
@override
WKNavigationDelegate copy() {
return WKNavigationDelegate.detached(
didFinishNavigation: didFinishNavigation,
didStartProvisionalNavigation: didStartProvisionalNavigation,
decidePolicyForNavigationAction: decidePolicyForNavigationAction,
didFailNavigation: didFailNavigation,
didFailProvisionalNavigation: didFailProvisionalNavigation,
webViewWebContentProcessDidTerminate:
webViewWebContentProcessDidTerminate,
observeValue: observeValue,
binaryMessenger: _navigationDelegateApi.binaryMessenger,
instanceManager: _navigationDelegateApi.instanceManager,
);
}
}
/// Object that displays interactive web content, such as for an in-app browser.
///
/// Wraps [WKWebView](https://developer.apple.com/documentation/webkit/wkwebview?language=objc).
@immutable
class WKWebView extends UIView {
/// Constructs a [WKWebView].
///
/// [configuration] contains the configuration details for the web view. This
/// method saves a copy of your configuration object. Changes you make to your
/// original object after calling this method have no effect on the web view’s
/// configuration. For a list of configuration options and their default
/// values, see [WKWebViewConfiguration]. If you didn’t create your web view
/// using the `configuration` parameter, this value uses a default
/// configuration object.
WKWebView(
WKWebViewConfiguration configuration, {
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _webViewApi = WKWebViewHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached() {
// Ensures FlutterApis for the WebKit library are set up.
WebKitFlutterApis.instance.ensureSetUp();
_webViewApi.createForInstances(this, configuration);
}
/// Constructs a [WKWebView] without creating the associated Objective-C
/// object.
///
/// This should only be used outside of tests by subclasses created by this
/// library or to create a copy for an InstanceManager.
WKWebView.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _webViewApi = WKWebViewHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final WKWebViewHostApiImpl _webViewApi;
/// Contains the configuration details for the web view.
///
/// Use the object in this property to obtain information about your web
/// view’s configuration. Because this property returns a copy of the
/// configuration object, changes you make to that object don’t affect the web
/// view’s configuration.
///
/// If you didn’t create your web view with a [WKWebViewConfiguration] this
/// property contains a default configuration object.
late final WKWebViewConfiguration configuration =
WKWebViewConfiguration.fromWebView(
this,
binaryMessenger: _webViewApi.binaryMessenger,
instanceManager: _webViewApi.instanceManager,
);
/// The scrollable view associated with the web view.
late final UIScrollView scrollView = UIScrollView.fromWebView(
this,
binaryMessenger: _webViewApi.binaryMessenger,
instanceManager: _webViewApi.instanceManager,
);
/// Used to integrate custom user interface elements into web view interactions.
///
/// Sets [WKWebView.UIDelegate](https://developer.apple.com/documentation/webkit/wkwebview/1415009-uidelegate?language=objc).
Future<void> setUIDelegate(WKUIDelegate? delegate) {
return _webViewApi.setUIDelegateForInstances(this, delegate);
}
/// The object you use to manage navigation behavior for the web view.
///
/// Sets [WKWebView.navigationDelegate](https://developer.apple.com/documentation/webkit/wkwebview/1414971-navigationdelegate?language=objc).
Future<void> setNavigationDelegate(WKNavigationDelegate? delegate) {
return _webViewApi.setNavigationDelegateForInstances(this, delegate);
}
/// The URL for the current webpage.
///
/// Represents [WKWebView.URL](https://developer.apple.com/documentation/webkit/wkwebview/1415005-url?language=objc).
Future<String?> getUrl() {
return _webViewApi.getUrlForInstances(this);
}
/// An estimate of what fraction of the current navigation has been loaded.
///
/// This value ranges from 0.0 to 1.0.
///
/// Represents [WKWebView.estimatedProgress](https://developer.apple.com/documentation/webkit/wkwebview/1415007-estimatedprogress?language=objc).
Future<double> getEstimatedProgress() {
return _webViewApi.getEstimatedProgressForInstances(this);
}
/// Loads the web content referenced by the specified URL request object and navigates to it.
///
/// Use this method to load a page from a local or network-based URL. For
/// example, you might use it to navigate to a network-based webpage.
Future<void> loadRequest(NSUrlRequest request) {
return _webViewApi.loadRequestForInstances(this, request);
}
/// Loads the contents of the specified HTML string and navigates to it.
Future<void> loadHtmlString(String string, {String? baseUrl}) {
return _webViewApi.loadHtmlStringForInstances(this, string, baseUrl);
}
/// Loads the web content from the specified file and navigates to it.
Future<void> loadFileUrl(String url, {required String readAccessUrl}) {
return _webViewApi.loadFileUrlForInstances(this, url, readAccessUrl);
}
/// Loads the Flutter asset specified in the pubspec.yaml file.
///
/// This method is not a part of WebKit and is only a Flutter specific helper
/// method.
Future<void> loadFlutterAsset(String key) {
return _webViewApi.loadFlutterAssetForInstances(this, key);
}
/// Indicates whether there is a valid back item in the back-forward list.
Future<bool> canGoBack() {
return _webViewApi.canGoBackForInstances(this);
}
/// Indicates whether there is a valid forward item in the back-forward list.
Future<bool> canGoForward() {
return _webViewApi.canGoForwardForInstances(this);
}
/// Navigates to the back item in the back-forward list.
Future<void> goBack() {
return _webViewApi.goBackForInstances(this);
}
/// Navigates to the forward item in the back-forward list.
Future<void> goForward() {
return _webViewApi.goForwardForInstances(this);
}
/// Reloads the current webpage.
Future<void> reload() {
return _webViewApi.reloadForInstances(this);
}
/// The page title.
///
/// Represents [WKWebView.title](https://developer.apple.com/documentation/webkit/wkwebview/1415015-title?language=objc).
Future<String?> getTitle() {
return _webViewApi.getTitleForInstances(this);
}
/// Indicates whether horizontal swipe gestures trigger page navigation.
///
/// The default value is false.
///
/// Sets [WKWebView.allowsBackForwardNavigationGestures](https://developer.apple.com/documentation/webkit/wkwebview/1414995-allowsbackforwardnavigationgestu?language=objc).
Future<void> setAllowsBackForwardNavigationGestures(bool allow) {
return _webViewApi.setAllowsBackForwardNavigationGesturesForInstances(
this,
allow,
);
}
/// The custom user agent string.
///
/// The default value of this property is null.
///
/// Sets [WKWebView.customUserAgent](https://developer.apple.com/documentation/webkit/wkwebview/1414950-customuseragent?language=objc).
Future<void> setCustomUserAgent(String? userAgent) {
return _webViewApi.setCustomUserAgentForInstances(this, userAgent);
}
/// Evaluates the specified JavaScript string.
///
/// Throws a `PlatformException` if an error occurs or return value is not
/// supported.
Future<Object?> evaluateJavaScript(String javaScriptString) {
return _webViewApi.evaluateJavaScriptForInstances(
this,
javaScriptString,
);
}
@override
WKWebView copy() {
return WKWebView.detached(
observeValue: observeValue,
binaryMessenger: _webViewApi.binaryMessenger,
instanceManager: _webViewApi.instanceManager,
);
}
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/web_kit/web_kit.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/web_kit/web_kit.dart",
"repo_id": "plugins",
"token_count": 11998
} | 1,288 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart';
import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart';
import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart';
import 'package:webview_flutter_wkwebview/src/foundation/foundation_api_impls.dart';
import '../common/test_web_kit.g.dart';
import 'foundation_test.mocks.dart';
@GenerateMocks(<Type>[
TestNSObjectHostApi,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Foundation', () {
late InstanceManager instanceManager;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
});
group('NSObject', () {
late MockTestNSObjectHostApi mockPlatformHostApi;
late NSObject object;
setUp(() {
mockPlatformHostApi = MockTestNSObjectHostApi();
TestNSObjectHostApi.setup(mockPlatformHostApi);
object = NSObject.detached(instanceManager: instanceManager);
instanceManager.addDartCreatedInstance(object);
});
tearDown(() {
TestNSObjectHostApi.setup(null);
});
test('addObserver', () async {
final NSObject observer = NSObject.detached(
instanceManager: instanceManager,
);
instanceManager.addDartCreatedInstance(observer);
await object.addObserver(
observer,
keyPath: 'aKeyPath',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.initialValue,
NSKeyValueObservingOptions.priorNotification,
},
);
final List<NSKeyValueObservingOptionsEnumData?> optionsData =
verify(mockPlatformHostApi.addObserver(
instanceManager.getIdentifier(object),
instanceManager.getIdentifier(observer),
'aKeyPath',
captureAny,
)).captured.single as List<NSKeyValueObservingOptionsEnumData?>;
expect(optionsData, hasLength(2));
expect(
optionsData[0]!.value,
NSKeyValueObservingOptionsEnum.initialValue,
);
expect(
optionsData[1]!.value,
NSKeyValueObservingOptionsEnum.priorNotification,
);
});
test('removeObserver', () async {
final NSObject observer = NSObject.detached(
instanceManager: instanceManager,
);
instanceManager.addDartCreatedInstance(observer);
await object.removeObserver(observer, keyPath: 'aKeyPath');
verify(mockPlatformHostApi.removeObserver(
instanceManager.getIdentifier(object),
instanceManager.getIdentifier(observer),
'aKeyPath',
));
});
test('NSObjectHostApi.dispose', () async {
int? callbackIdentifier;
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (int identifier) {
callbackIdentifier = identifier;
});
final NSObject object = NSObject.detached(
instanceManager: instanceManager,
);
final int identifier = instanceManager.addDartCreatedInstance(object);
NSObject.dispose(object);
expect(callbackIdentifier, identifier);
});
test('observeValue', () async {
final Completer<List<Object?>> argsCompleter =
Completer<List<Object?>>();
FoundationFlutterApis.instance = FoundationFlutterApis(
instanceManager: instanceManager,
);
object = NSObject.detached(
instanceManager: instanceManager,
observeValue: (
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) {
argsCompleter.complete(<Object?>[keyPath, object, change]);
},
);
instanceManager.addHostCreatedInstance(object, 1);
FoundationFlutterApis.instance.object.observeValue(
1,
'keyPath',
1,
<NSKeyValueChangeKeyEnumData>[
NSKeyValueChangeKeyEnumData(value: NSKeyValueChangeKeyEnum.oldValue)
],
<Object?>['value'],
);
expect(
argsCompleter.future,
completion(<Object?>[
'keyPath',
object,
<NSKeyValueChangeKey, Object?>{
NSKeyValueChangeKey.oldValue: 'value',
},
]),
);
});
test('NSObjectFlutterApi.dispose', () {
FoundationFlutterApis.instance = FoundationFlutterApis(
instanceManager: instanceManager,
);
object = NSObject.detached(instanceManager: instanceManager);
instanceManager.addHostCreatedInstance(object, 1);
instanceManager.removeWeakReference(object);
FoundationFlutterApis.instance.object.dispose(1);
expect(instanceManager.containsIdentifier(1), isFalse);
});
});
});
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/foundation/foundation_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/foundation/foundation_test.dart",
"repo_id": "plugins",
"token_count": 2223
} | 1,289 |
# This list should be kept as short as possible, and things should remain here
# only as long as necessary, since in general the goal is for all of the latest
# versions of plugins to be mutually compatible.
#
# An example use case for this list would be to temporarily add plugins while
# updating multiple plugins for a breaking change in a common dependency in
# cases where using a relaxed version constraint isn't possible.
# This is a permament entry, as it should never be a direct app dependency.
- plugin_platform_interface
| plugins/script/configs/exclude_all_packages_app.yaml/0 | {
"file_path": "plugins/script/configs/exclude_all_packages_app.yaml",
"repo_id": "plugins",
"token_count": 118
} | 1,290 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:colorize/colorize.dart';
import 'package:file/file.dart';
/// The signature for a print handler for commands that allow overriding the
/// print destination.
typedef Print = void Function(Object? object);
/// Key for APK (Android) platform.
const String platformAndroid = 'android';
/// Key for IPA (iOS) platform.
const String platformIOS = 'ios';
/// Key for linux platform.
const String platformLinux = 'linux';
/// Key for macos platform.
const String platformMacOS = 'macos';
/// Key for Web platform.
const String platformWeb = 'web';
/// Key for windows platform.
const String platformWindows = 'windows';
/// Key for enable experiment.
const String kEnableExperiment = 'enable-experiment';
/// Target platforms supported by Flutter.
// ignore: public_member_api_docs
enum FlutterPlatform { android, ios, linux, macos, web, windows }
/// Returns whether the given directory is a Dart package.
bool isPackage(FileSystemEntity entity) {
if (entity is! Directory) {
return false;
}
// According to
// https://dart.dev/guides/libraries/create-library-packages#what-makes-a-library-package
// a package must also have a `lib/` directory, but in practice that's not
// always true. flutter/plugins has some special cases (espresso, some
// federated implementation packages) that don't have any source, so this
// deliberately doesn't check that there's a lib directory.
return entity.childFile('pubspec.yaml').existsSync();
}
/// Prints `successMessage` in green.
void printSuccess(String successMessage) {
print(Colorize(successMessage)..green());
}
/// Prints `errorMessage` in red.
void printError(String errorMessage) {
print(Colorize(errorMessage)..red());
}
/// Error thrown when a command needs to exit with a non-zero exit code.
///
/// While there is no specific definition of the meaning of different non-zero
/// exit codes for this tool, commands should follow the general convention:
/// 1: The command ran correctly, but found errors.
/// 2: The command failed to run because the arguments were invalid.
/// >2: The command failed to run correctly for some other reason. Ideally,
/// each such failure should have a unique exit code within the context of
/// that command.
class ToolExit extends Error {
/// Creates a tool exit with the given [exitCode].
ToolExit(this.exitCode);
/// The code that the process should exit with.
final int exitCode;
}
/// A exit code for [ToolExit] for a successful run that found errors.
const int exitCommandFoundErrors = 1;
/// A exit code for [ToolExit] for a failure to run due to invalid arguments.
const int exitInvalidArguments = 2;
| plugins/script/tool/lib/src/common/core.dart/0 | {
"file_path": "plugins/script/tool/lib/src/common/core.dart",
"repo_id": "plugins",
"token_count": 769
} | 1,291 |
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.FlutterViewIntegration" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources> | samples/add_to_app/android_view/android_view/app/src/main/res/values-night/themes.xml/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/values-night/themes.xml",
"repo_id": "samples",
"token_count": 318
} | 1,292 |
<resources>
<string name="app_name">Books</string>
<string name="edit">Edit</string>
<string name="author_prefix">By: %1$s</string>
</resources> | samples/add_to_app/books/android_books/app/src/main/res/values/strings.xml/0 | {
"file_path": "samples/add_to_app/books/android_books/app/src/main/res/values/strings.xml",
"repo_id": "samples",
"token_count": 58
} | 1,293 |
#!/bin/sh
flutter pub run pigeon --input pigeon/schema.dart \
--dart_out lib/api.dart \
--objc_header_out ../ios_books/IosBooks/api.h \
--objc_source_out ../ios_books/IosBooks/api.m \
--objc_prefix BK \
--java_out ../android_books/app/src/main/java/dev/flutter/example/books/Api.java \
--java_package "dev.flutter.example.books"
| samples/add_to_app/books/flutter_module_books/run_pigeon.sh/0 | {
"file_path": "samples/add_to_app/books/flutter_module_books/run_pigeon.sh",
"repo_id": "samples",
"token_count": 142
} | 1,294 |
// 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.
package dev.flutter.example.androidfullscreen
import androidx.multidex.MultiDexApplication
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
const val ENGINE_ID = "1"
class MyApplication : MultiDexApplication() {
var count = 0
private lateinit var channel: MethodChannel
override fun onCreate() {
super.onCreate()
val flutterEngine = FlutterEngine(this)
flutterEngine
.dartExecutor
.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache.getInstance().put(ENGINE_ID, flutterEngine)
channel = MethodChannel(flutterEngine.dartExecutor, "dev.flutter.example/counter")
channel.setMethodCallHandler { call, _ ->
when (call.method) {
"incrementCounter" -> {
count++
reportCounter()
}
"requestCounter" -> {
reportCounter()
}
}
}
}
private fun reportCounter() {
channel.invokeMethod("reportCounter", count)
}
}
| samples/add_to_app/fullscreen/android_fullscreen/app/src/main/java/dev/flutter/example/androidfullscreen/MyApplication.kt/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/java/dev/flutter/example/androidfullscreen/MyApplication.kt",
"repo_id": "samples",
"token_count": 609
} | 1,295 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
</resources>
| samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/values/colors.xml/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/values/colors.xml",
"repo_id": "samples",
"token_count": 81
} | 1,296 |
name: flutter_module
description: An example Flutter module.
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
provider: ^6.0.2
dev_dependencies:
analysis_defaults:
path: ../../../analysis_defaults
flutter_test:
sdk: flutter
flutter_driver:
sdk: flutter
espresso: ">=0.2.0 <0.4.0"
flutter:
uses-material-design: true
# This section identifies your Flutter project as a module meant for
# embedding in a native host app. These identifiers should _not_ ordinarily
# be changed after generation - they are used to ensure that the tooling can
# maintain consistency when adding or modifying assets and plugins.
# They also do not have any bearing on your native host application's
# identifiers, which may be completely independent or the same as these.
module:
androidX: true
androidPackage: dev.flutter.example.flutter_module
iosBundleIdentifier: dev.flutter.example.flutterModule
| samples/add_to_app/fullscreen/flutter_module/pubspec.yaml/0 | {
"file_path": "samples/add_to_app/fullscreen/flutter_module/pubspec.yaml",
"repo_id": "samples",
"token_count": 312
} | 1,297 |
package dev.flutter.multipleflutters
import java.lang.ref.WeakReference
/**
* Interface for getting notifications when the DataModel is updated.
*/
interface DataModelObserver {
fun onCountUpdate(newCount: Int)
}
/**
* A singleton/observable data model for the data shared between Flutter and the host platform.
*
* This is the definitive source of truth for all data.
*/
class DataModel {
companion object {
val instance = DataModel()
}
private val observers = mutableListOf<WeakReference<DataModelObserver>>()
public var counter = 0
set(value) {
field = value
for (observer in observers) {
observer.get()?.onCountUpdate(value)
}
}
fun addObserver(observer: DataModelObserver) {
observers.add(WeakReference(observer))
}
fun removeObserver(observer: DataModelObserver) {
observers.removeIf {
if (it.get() != null) it.get() == observer else true
}
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/DataModel.kt/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/DataModel.kt",
"repo_id": "samples",
"token_count": 382
} | 1,298 |
// 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 Flutter
import FlutterPluginRegistrant
import Foundation
/// A FlutterViewController intended for the MyApp widget in the Flutter module.
///
/// This view controller maintains a connection to the Flutter instance and syncs it with the
/// datamodel. In practice you should override the other init methods or switch to composition
/// instead of inheritence.
class SingleFlutterViewController: FlutterViewController, DataModelObserver {
private var channel: FlutterMethodChannel?
init(withEntrypoint entryPoint: String?) {
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let newEngine = appDelegate.engines.makeEngine(withEntrypoint: entryPoint, libraryURI: nil)
GeneratedPluginRegistrant.register(with: newEngine)
super.init(engine: newEngine, nibName: nil, bundle: nil)
DataModel.shared.addObserver(observer: self)
}
deinit {
DataModel.shared.removeObserver(observer: self)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func onCountUpdate(newCount: Int64) {
if let channel = channel {
channel.invokeMethod("setCount", arguments: newCount)
}
}
override func viewDidLoad() {
super.viewDidLoad()
channel = FlutterMethodChannel(
name: "multiple-flutters", binaryMessenger: self.engine!.binaryMessenger)
channel!.invokeMethod("setCount", arguments: DataModel.shared.count)
let navController = self.navigationController!
channel!.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
if call.method == "incrementCount" {
DataModel.shared.count = DataModel.shared.count + 1
result(nil)
} else if call.method == "next" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NativeViewCount")
navController.pushViewController(vc, animated: true)
result(nil)
} else {
result(FlutterMethodNotImplemented)
}
}
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/SingleFlutterViewController.swift/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/SingleFlutterViewController.swift",
"repo_id": "samples",
"token_count": 721
} | 1,299 |
<!--
~ Copyright (C) 2021 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!-- This layout is the final frame of the interpolation animation. -->
<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:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<ImageView
android:id="@+id/icon_background"
android:layout_width="72dp"
android:layout_height="72dp"
app:layout_constraintBottom_toBottomOf="@+id/imageView"
app:layout_constraintEnd_toEndOf="@+id/imageView"
app:layout_constraintStart_toStartOf="@+id/imageView"
app:layout_constraintTop_toTopOf="@+id/imageView"
android:src="@drawable/android_background" />
<ImageView
android:id="@+id/imageView"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="24dp"
android:layout_marginStart="24dp"
android:src="@drawable/android"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/android" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Super Splash Screen Demo"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="@+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toEndOf="@+id/imageView"
app:layout_constraintTop_toTopOf="@+id/imageView" />
<androidx.constraintlayout.helper.widget.Flow
android:id="@+id/flow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
app:constraint_referenced_ids="imageView2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/icon_background" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="@+id/icon_background"
app:layout_constraintTop_toBottomOf="@+id/icon_background"
tools:srcCompat="@tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>
| samples/android_splash_screen/android/app/src/main/res/layout/main_activity_2.xml/0 | {
"file_path": "samples/android_splash_screen/android/app/src/main/res/layout/main_activity_2.xml",
"repo_id": "samples",
"token_count": 1204
} | 1,300 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'package:flutter/material.dart';
Future<void> main() async {
runApp(const MyApp());
}
/* Main widget that contains the Flutter starter app. */
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(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;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
const Padding(
padding: EdgeInsets.only(top: 42, bottom: 250),
child: Align(
alignment: Alignment.topCenter, child: CustomAppBar())),
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
/* A Flutter implementation of the last frame of the splashscreen animation */
class CustomAppBar extends StatelessWidget {
const CustomAppBar({super.key});
@override
Widget build(BuildContext context) {
Widget titleSection = Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 12, right: 4),
child: ClipRRect(
borderRadius: BorderRadius.circular(36.0),
child: Image.asset(
'images/androidIcon.png',
width: 72.0,
height: 72.0,
fit: BoxFit.fill,
),
),
),
const Padding(
padding: EdgeInsets.only(top: 3),
child: Text("Super Splash Screen Demo",
style: TextStyle(color: Colors.black54, fontSize: 24)),
),
],
);
return titleSection;
}
}
| samples/android_splash_screen/lib/main.dart/0 | {
"file_path": "samples/android_splash_screen/lib/main.dart",
"repo_id": "samples",
"token_count": 1255
} | 1,301 |
// 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';
class TweenSequenceDemo extends StatefulWidget {
const TweenSequenceDemo({super.key});
static const String routeName = 'basics/chaining_tweens';
@override
State<TweenSequenceDemo> createState() => _TweenSequenceDemoState();
}
class _TweenSequenceDemoState extends State<TweenSequenceDemo>
with SingleTickerProviderStateMixin {
static const Duration duration = Duration(seconds: 3);
late final AnimationController controller;
late final Animation<Color?> animation;
static final colors = [
Colors.red,
Colors.orange,
Colors.yellow,
Colors.green,
Colors.blue,
Colors.indigo,
Colors.purple,
];
@override
void initState() {
super.initState();
final sequenceItems = <TweenSequenceItem<Color?>>[];
for (var i = 0; i < colors.length; i++) {
final beginColor = colors[i];
final endColor = colors[(i + 1) % colors.length];
final weight = 1 / colors.length;
sequenceItems.add(
TweenSequenceItem<Color?>(
tween: ColorTween(begin: beginColor, end: endColor),
weight: weight,
),
);
}
controller = AnimationController(duration: duration, vsync: this);
animation = TweenSequence<Color?>(sequenceItems).animate(controller);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Tween Sequences'),
),
body: Center(
child: AnimatedBuilder(
animation: animation,
builder: (context, child) {
return MaterialButton(
color: animation.value,
onPressed: () async {
await controller.forward();
controller.reset();
},
child: child,
);
},
child: const Text('Animate', style: TextStyle(color: Colors.white)),
),
),
);
}
}
| samples/animations/lib/src/basics/tween_sequence.dart/0 | {
"file_path": "samples/animations/lib/src/basics/tween_sequence.dart",
"repo_id": "samples",
"token_count": 870
} | 1,302 |
import 'package:shared/shared.dart';
import 'package:test/test.dart';
void main() {
test('Increment serialization', () {
expect(Increment(by: 3).toJson(), <String, dynamic>{'by': 3});
});
test('Increment derialization', () {
expect(Increment.fromJson(<String, dynamic>{'by': 5}), Increment(by: 5));
});
test('Count serialization', () {
expect(Count(3).toJson(), <String, dynamic>{'value': 3});
});
test('Count derialization', () {
expect(Count.fromJson(<String, dynamic>{'value': 5}), Count(5));
});
}
| samples/code_sharing/shared/test/shared_test.dart/0 | {
"file_path": "samples/code_sharing/shared/test/shared_test.dart",
"repo_id": "samples",
"token_count": 201
} | 1,303 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'context_menu_region.dart';
import 'platform_selector.dart';
class AnywherePage extends StatelessWidget {
AnywherePage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'anywhere';
static const String title = 'Context Menu Anywhere Example';
static const String subtitle = 'A context menu outside of a text field';
final PlatformCallback onChangedPlatform;
final TextEditingController _materialController = TextEditingController(
text: 'TextField shows the default menu still.',
);
final TextEditingController _cupertinoController = TextEditingController(
text: 'CupertinoTextField shows the default menu still.',
);
final TextEditingController _editableController = TextEditingController(
text: 'EditableText has no default menu, so it shows the custom one.',
);
static const String url = '$kCodeUrl/anywhere_page.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(AnywherePage.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: ContextMenuRegion(
contextMenuBuilder: (context, primaryAnchor, [secondaryAnchor]) {
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: TextSelectionToolbarAnchors(
primaryAnchor: primaryAnchor,
secondaryAnchor: secondaryAnchor as Offset?,
),
buttonItems: <ContextMenuButtonItem>[
ContextMenuButtonItem(
onPressed: () {
ContextMenuController.removeAny();
Navigator.of(context).pop();
},
label: 'Back',
),
],
);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 64.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(height: 20.0),
const Text(
'Right click anywhere outside of a field to show a custom menu.',
),
Container(height: 140.0),
CupertinoTextField(controller: _cupertinoController),
Container(height: 40.0),
TextField(controller: _materialController),
Container(height: 40.0),
Container(
color: Colors.white,
child: EditableText(
controller: _editableController,
focusNode: FocusNode(),
style: Typography.material2021().black.displayMedium!,
cursorColor: Colors.blue,
backgroundCursorColor: Colors.white,
),
),
],
),
),
),
);
}
}
| samples/context_menus/lib/anywhere_page.dart/0 | {
"file_path": "samples/context_menus/lib/anywhere_page.dart",
"repo_id": "samples",
"token_count": 1507
} | 1,304 |
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'platform_selector.dart';
class ReorderedButtonsPage extends StatelessWidget {
ReorderedButtonsPage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'reordered-buttons';
static const String title = 'Reordered Buttons';
static const String subtitle = 'The usual buttons, but in a different order.';
static const String url = '$kCodeUrl/reordered_buttons_page.dart';
final PlatformCallback onChangedPlatform;
final TextEditingController _controllerNormal = TextEditingController(
text: 'This button has the default buttons for reference.',
);
final TextEditingController _controllerReordered = TextEditingController(
text: 'This field has reordered buttons.',
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(ReorderedButtonsPage.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.center,
children: <Widget>[
TextField(
maxLines: 2,
controller: _controllerNormal,
),
const SizedBox(height: 20.0),
TextField(
controller: _controllerReordered,
maxLines: 2,
contextMenuBuilder: (context, editableTextState) {
// Reorder the button datas by type.
final HashMap<ContextMenuButtonType, ContextMenuButtonItem>
buttonItemsMap =
HashMap<ContextMenuButtonType, ContextMenuButtonItem>();
for (ContextMenuButtonItem buttonItem
in editableTextState.contextMenuButtonItems) {
buttonItemsMap[buttonItem.type] = buttonItem;
}
final List<ContextMenuButtonItem> reorderedButtonItems =
<ContextMenuButtonItem>[
if (buttonItemsMap
.containsKey(ContextMenuButtonType.selectAll))
buttonItemsMap[ContextMenuButtonType.selectAll]!,
if (buttonItemsMap.containsKey(ContextMenuButtonType.paste))
buttonItemsMap[ContextMenuButtonType.paste]!,
if (buttonItemsMap.containsKey(ContextMenuButtonType.copy))
buttonItemsMap[ContextMenuButtonType.copy]!,
if (buttonItemsMap.containsKey(ContextMenuButtonType.cut))
buttonItemsMap[ContextMenuButtonType.cut]!,
];
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: editableTextState.contextMenuAnchors,
buttonItems: reorderedButtonItems,
);
},
),
],
),
),
),
);
}
}
| samples/context_menus/lib/reordered_buttons_page.dart/0 | {
"file_path": "samples/context_menus/lib/reordered_buttons_page.dart",
"repo_id": "samples",
"token_count": 1634
} | 1,305 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/context_menus/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/context_menus/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,306 |
import 'package:context_menus/default_values_page.dart';
import 'package:context_menus/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Gives correct behavior for all values of contextMenuBuilder',
(tester) async {
await tester.pumpWidget(const MyApp());
// Navigate to the DefaultValuesPage example.
await tester.dragUntilVisible(
find.text(DefaultValuesPage.title),
find.byType(ListView),
const Offset(0.0, -100.0),
);
await tester.pumpAndSettle();
await tester.tap(find.text(DefaultValuesPage.title));
await tester.pumpAndSettle();
expect(
find.descendant(
of: find.byType(AppBar),
matching: find.text(DefaultValuesPage.title),
),
findsOneWidget,
);
// Right click on the text field where contextMenuBuilder isn't passed.
TestGesture gesture = await tester.startGesture(
tester.getCenter(find.byType(EditableText).first),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The default context menu is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(
find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(2));
case TargetPlatform.macOS:
expect(find.byType(CupertinoDesktopTextSelectionToolbarButton),
findsNWidgets(2));
case TargetPlatform.android:
case TargetPlatform.fuchsia:
expect(find.byType(TextSelectionToolbarTextButton), findsNWidgets(1));
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(
find.byType(DesktopTextSelectionToolbarButton), findsNWidgets(1));
}
// Tap the next field to hide the context menu.
await tester.tap(find.byType(EditableText).at(1));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Right click on the text field where contextMenuBuilder is given null.
gesture = await tester.startGesture(
tester.getCenter(find.byType(EditableText).at(1)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// No context menu is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Tap the next field to hide the context menu.
await tester.tap(find.byType(EditableText).at(2));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Right click on the text field with the custom contextMenuBuilder.
gesture = await tester.startGesture(
tester.getCenter(find.byType(EditableText).at(2)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The custom context menu is shown.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
expect(find.text('Custom button'), findsOneWidget);
});
}
| samples/context_menus/test/default_values_page_test.dart/0 | {
"file_path": "samples/context_menus/test/default_values_page_test.dart",
"repo_id": "samples",
"token_count": 1307
} | 1,307 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled.
version:
revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
channel: issues/120405
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
base_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
- platform: android
create_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
base_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
- platform: ios
create_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
base_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
- platform: linux
create_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
base_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
- platform: macos
create_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
base_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
- platform: web
create_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
base_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
- platform: windows
create_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
base_revision: 9d49bc6f8521b9f1119c6b05088154f7c95dbcd8
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| samples/deeplink_store_example/.metadata/0 | {
"file_path": "samples/deeplink_store_example/.metadata",
"repo_id": "samples",
"token_count": 776
} | 1,308 |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'model/products_repository.dart';
import 'row_item.dart';
import 'styles.dart';
class ProductCategoryList extends StatelessWidget {
const ProductCategoryList({super.key});
@override
Widget build(BuildContext context) {
final GoRouterState state = GoRouterState.of(context);
final Category category = Category.values.firstWhere(
(Category value) =>
value.toString().contains(state.pathParameters['category']!),
orElse: () => Category.all,
);
final List<Widget> children =
ProductsRepository.loadProducts(category: category)
.map<Widget>((Product p) => RowItem(product: p))
.toList();
return Scaffold(
backgroundColor: Styles.scaffoldBackground,
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Text(getCategoryTitle(category),
style: Styles.productListTitle),
backgroundColor: Styles.scaffoldAppBarBackground,
pinned: true,
),
SliverList(
delegate: SliverChildListDelegate(children),
),
],
),
);
}
}
| samples/deeplink_store_example/lib/product_category_list.dart/0 | {
"file_path": "samples/deeplink_store_example/lib/product_category_list.dart",
"repo_id": "samples",
"token_count": 655
} | 1,309 |
#include "ephemeral/Flutter-Generated.xcconfig"
| samples/deeplink_store_example/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "samples/deeplink_store_example/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "samples",
"token_count": 19
} | 1,310 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'serializers.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializers _$serializers = (new Serializers().toBuilder()
..add(ApiError.serializer)
..add(CurrentUserCollections.serializer)
..add(Exif.serializer)
..add(Links.serializer)
..add(Location.serializer)
..add(Photo.serializer)
..add(Position.serializer)
..add(Search.serializer)
..add(SearchPhotosResponse.serializer)
..add(Tags.serializer)
..add(Urls.serializer)
..add(User.serializer)
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(Photo)]),
() => new ListBuilder<Photo>())
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(Photo)]),
() => new ListBuilder<Photo>())
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(String)]),
() => new ListBuilder<String>())
..addBuilderFactory(
const FullType(BuiltList, const [const FullType(Tags)]),
() => new ListBuilder<Tags>())
..addBuilderFactory(
const FullType(
BuiltList, const [const FullType(CurrentUserCollections)]),
() => new ListBuilder<CurrentUserCollections>()))
.build();
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/serializers.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/serializers.g.dart",
"repo_id": "samples",
"token_count": 614
} | 1,311 |
// 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 'search_photos_response.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<SearchPhotosResponse> _$searchPhotosResponseSerializer =
new _$SearchPhotosResponseSerializer();
class _$SearchPhotosResponseSerializer
implements StructuredSerializer<SearchPhotosResponse> {
@override
final Iterable<Type> types = const [
SearchPhotosResponse,
_$SearchPhotosResponse
];
@override
final String wireName = 'SearchPhotosResponse';
@override
Iterable<Object?> serialize(
Serializers serializers, SearchPhotosResponse object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'results',
serializers.serialize(object.results,
specifiedType:
const FullType(BuiltList, const [const FullType(Photo)])),
];
Object? value;
value = object.total;
if (value != null) {
result
..add('total')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.totalPages;
if (value != null) {
result
..add('total_pages')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
return result;
}
@override
SearchPhotosResponse deserialize(
Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new SearchPhotosResponseBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'total':
result.total = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'total_pages':
result.totalPages = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'results':
result.results.replace(serializers.deserialize(value,
specifiedType:
const FullType(BuiltList, const [const FullType(Photo)]))!
as BuiltList<Object?>);
break;
}
}
return result.build();
}
}
class _$SearchPhotosResponse extends SearchPhotosResponse {
@override
final int? total;
@override
final int? totalPages;
@override
final BuiltList<Photo> results;
factory _$SearchPhotosResponse(
[void Function(SearchPhotosResponseBuilder)? updates]) =>
(new SearchPhotosResponseBuilder()..update(updates))._build();
_$SearchPhotosResponse._({this.total, this.totalPages, required this.results})
: super._() {
BuiltValueNullFieldError.checkNotNull(
results, r'SearchPhotosResponse', 'results');
}
@override
SearchPhotosResponse rebuild(
void Function(SearchPhotosResponseBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
SearchPhotosResponseBuilder toBuilder() =>
new SearchPhotosResponseBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is SearchPhotosResponse &&
total == other.total &&
totalPages == other.totalPages &&
results == other.results;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, total.hashCode);
_$hash = $jc(_$hash, totalPages.hashCode);
_$hash = $jc(_$hash, results.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'SearchPhotosResponse')
..add('total', total)
..add('totalPages', totalPages)
..add('results', results))
.toString();
}
}
class SearchPhotosResponseBuilder
implements Builder<SearchPhotosResponse, SearchPhotosResponseBuilder> {
_$SearchPhotosResponse? _$v;
int? _total;
int? get total => _$this._total;
set total(int? total) => _$this._total = total;
int? _totalPages;
int? get totalPages => _$this._totalPages;
set totalPages(int? totalPages) => _$this._totalPages = totalPages;
ListBuilder<Photo>? _results;
ListBuilder<Photo> get results =>
_$this._results ??= new ListBuilder<Photo>();
set results(ListBuilder<Photo>? results) => _$this._results = results;
SearchPhotosResponseBuilder();
SearchPhotosResponseBuilder get _$this {
final $v = _$v;
if ($v != null) {
_total = $v.total;
_totalPages = $v.totalPages;
_results = $v.results.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(SearchPhotosResponse other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$SearchPhotosResponse;
}
@override
void update(void Function(SearchPhotosResponseBuilder)? updates) {
if (updates != null) updates(this);
}
@override
SearchPhotosResponse build() => _build();
_$SearchPhotosResponse _build() {
_$SearchPhotosResponse _$result;
try {
_$result = _$v ??
new _$SearchPhotosResponse._(
total: total, totalPages: totalPages, results: results.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'results';
results.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'SearchPhotosResponse', _$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/search_photos_response.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/search_photos_response.g.dart",
"repo_id": "samples",
"token_count": 2193
} | 1,312 |
// 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/foundation.dart';
import '../unsplash/photo.dart';
import '../unsplash/unsplash.dart';
import 'search.dart';
class SearchEntry {
const SearchEntry(this.query, this.photos, this.model);
final String query;
final List<Photo> photos;
final PhotoSearchModel model;
}
class PhotoSearchModel extends ChangeNotifier {
PhotoSearchModel(this._client);
final Unsplash _client;
List<SearchEntry> get entries => List.unmodifiable(_entries);
final List<SearchEntry> _entries = [];
Photo? get selectedPhoto => _selectedPhoto;
set selectedPhoto(Photo? photo) {
_selectedPhoto = photo;
notifyListeners();
}
Photo? _selectedPhoto;
Future<void> addSearch(String query) async {
final result = await _client.searchPhotos(
query: query,
orientation: SearchPhotosOrientation.portrait,
);
final search = Search((s) {
s
..query = query
..results.addAll(result!.results);
});
_entries.add(SearchEntry(query, search.results.toList(), this));
notifyListeners();
}
Future<Uint8List> download({required Photo photo}) => _client.download(photo);
}
| samples/desktop_photo_search/material/lib/src/model/photo_search_model.dart/0 | {
"file_path": "samples/desktop_photo_search/material/lib/src/model/photo_search_model.dart",
"repo_id": "samples",
"token_count": 429
} | 1,313 |
// 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 'photo.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Photo> _$photoSerializer = new _$PhotoSerializer();
class _$PhotoSerializer implements StructuredSerializer<Photo> {
@override
final Iterable<Type> types = const [Photo, _$Photo];
@override
final String wireName = 'Photo';
@override
Iterable<Object?> serialize(Serializers serializers, Photo object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'id',
serializers.serialize(object.id, specifiedType: const FullType(String)),
];
Object? value;
value = object.createdAt;
if (value != null) {
result
..add('created_at')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.updatedAt;
if (value != null) {
result
..add('updated_at')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.width;
if (value != null) {
result
..add('width')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.height;
if (value != null) {
result
..add('height')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.color;
if (value != null) {
result
..add('color')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.downloads;
if (value != null) {
result
..add('downloads')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.likes;
if (value != null) {
result
..add('likes')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
value = object.likedByUser;
if (value != null) {
result
..add('liked_by_user')
..add(
serializers.serialize(value, specifiedType: const FullType(bool)));
}
value = object.description;
if (value != null) {
result
..add('description')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.exif;
if (value != null) {
result
..add('exif')
..add(
serializers.serialize(value, specifiedType: const FullType(Exif)));
}
value = object.location;
if (value != null) {
result
..add('location')
..add(serializers.serialize(value,
specifiedType: const FullType(Location)));
}
value = object.tags;
if (value != null) {
result
..add('tags')
..add(serializers.serialize(value,
specifiedType:
const FullType(BuiltList, const [const FullType(Tags)])));
}
value = object.currentUserCollections;
if (value != null) {
result
..add('current_user_collections')
..add(serializers.serialize(value,
specifiedType: const FullType(
BuiltList, const [const FullType(CurrentUserCollections)])));
}
value = object.urls;
if (value != null) {
result
..add('urls')
..add(
serializers.serialize(value, specifiedType: const FullType(Urls)));
}
value = object.links;
if (value != null) {
result
..add('links')
..add(
serializers.serialize(value, specifiedType: const FullType(Links)));
}
value = object.user;
if (value != null) {
result
..add('user')
..add(
serializers.serialize(value, specifiedType: const FullType(User)));
}
return result;
}
@override
Photo deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new PhotoBuilder();
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 'created_at':
result.createdAt = 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 'width':
result.width = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'height':
result.height = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'color':
result.color = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'downloads':
result.downloads = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'likes':
result.likes = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
case 'liked_by_user':
result.likedByUser = serializers.deserialize(value,
specifiedType: const FullType(bool)) as bool?;
break;
case 'description':
result.description = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'exif':
result.exif.replace(serializers.deserialize(value,
specifiedType: const FullType(Exif))! as Exif);
break;
case 'location':
result.location.replace(serializers.deserialize(value,
specifiedType: const FullType(Location))! as Location);
break;
case 'tags':
result.tags.replace(serializers.deserialize(value,
specifiedType:
const FullType(BuiltList, const [const FullType(Tags)]))!
as BuiltList<Object?>);
break;
case 'current_user_collections':
result.currentUserCollections.replace(serializers.deserialize(value,
specifiedType: const FullType(BuiltList, const [
const FullType(CurrentUserCollections)
]))! as BuiltList<Object?>);
break;
case 'urls':
result.urls.replace(serializers.deserialize(value,
specifiedType: const FullType(Urls))! as Urls);
break;
case 'links':
result.links.replace(serializers.deserialize(value,
specifiedType: const FullType(Links))! as Links);
break;
case 'user':
result.user.replace(serializers.deserialize(value,
specifiedType: const FullType(User))! as User);
break;
}
}
return result.build();
}
}
class _$Photo extends Photo {
@override
final String id;
@override
final String? createdAt;
@override
final String? updatedAt;
@override
final int? width;
@override
final int? height;
@override
final String? color;
@override
final int? downloads;
@override
final int? likes;
@override
final bool? likedByUser;
@override
final String? description;
@override
final Exif? exif;
@override
final Location? location;
@override
final BuiltList<Tags>? tags;
@override
final BuiltList<CurrentUserCollections>? currentUserCollections;
@override
final Urls? urls;
@override
final Links? links;
@override
final User? user;
factory _$Photo([void Function(PhotoBuilder)? updates]) =>
(new PhotoBuilder()..update(updates))._build();
_$Photo._(
{required this.id,
this.createdAt,
this.updatedAt,
this.width,
this.height,
this.color,
this.downloads,
this.likes,
this.likedByUser,
this.description,
this.exif,
this.location,
this.tags,
this.currentUserCollections,
this.urls,
this.links,
this.user})
: super._() {
BuiltValueNullFieldError.checkNotNull(id, r'Photo', 'id');
}
@override
Photo rebuild(void Function(PhotoBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
PhotoBuilder toBuilder() => new PhotoBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Photo &&
id == other.id &&
createdAt == other.createdAt &&
updatedAt == other.updatedAt &&
width == other.width &&
height == other.height &&
color == other.color &&
downloads == other.downloads &&
likes == other.likes &&
likedByUser == other.likedByUser &&
description == other.description &&
exif == other.exif &&
location == other.location &&
tags == other.tags &&
currentUserCollections == other.currentUserCollections &&
urls == other.urls &&
links == other.links &&
user == other.user;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, id.hashCode);
_$hash = $jc(_$hash, createdAt.hashCode);
_$hash = $jc(_$hash, updatedAt.hashCode);
_$hash = $jc(_$hash, width.hashCode);
_$hash = $jc(_$hash, height.hashCode);
_$hash = $jc(_$hash, color.hashCode);
_$hash = $jc(_$hash, downloads.hashCode);
_$hash = $jc(_$hash, likes.hashCode);
_$hash = $jc(_$hash, likedByUser.hashCode);
_$hash = $jc(_$hash, description.hashCode);
_$hash = $jc(_$hash, exif.hashCode);
_$hash = $jc(_$hash, location.hashCode);
_$hash = $jc(_$hash, tags.hashCode);
_$hash = $jc(_$hash, currentUserCollections.hashCode);
_$hash = $jc(_$hash, urls.hashCode);
_$hash = $jc(_$hash, links.hashCode);
_$hash = $jc(_$hash, user.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'Photo')
..add('id', id)
..add('createdAt', createdAt)
..add('updatedAt', updatedAt)
..add('width', width)
..add('height', height)
..add('color', color)
..add('downloads', downloads)
..add('likes', likes)
..add('likedByUser', likedByUser)
..add('description', description)
..add('exif', exif)
..add('location', location)
..add('tags', tags)
..add('currentUserCollections', currentUserCollections)
..add('urls', urls)
..add('links', links)
..add('user', user))
.toString();
}
}
class PhotoBuilder implements Builder<Photo, PhotoBuilder> {
_$Photo? _$v;
String? _id;
String? get id => _$this._id;
set id(String? id) => _$this._id = id;
String? _createdAt;
String? get createdAt => _$this._createdAt;
set createdAt(String? createdAt) => _$this._createdAt = createdAt;
String? _updatedAt;
String? get updatedAt => _$this._updatedAt;
set updatedAt(String? updatedAt) => _$this._updatedAt = updatedAt;
int? _width;
int? get width => _$this._width;
set width(int? width) => _$this._width = width;
int? _height;
int? get height => _$this._height;
set height(int? height) => _$this._height = height;
String? _color;
String? get color => _$this._color;
set color(String? color) => _$this._color = color;
int? _downloads;
int? get downloads => _$this._downloads;
set downloads(int? downloads) => _$this._downloads = downloads;
int? _likes;
int? get likes => _$this._likes;
set likes(int? likes) => _$this._likes = likes;
bool? _likedByUser;
bool? get likedByUser => _$this._likedByUser;
set likedByUser(bool? likedByUser) => _$this._likedByUser = likedByUser;
String? _description;
String? get description => _$this._description;
set description(String? description) => _$this._description = description;
ExifBuilder? _exif;
ExifBuilder get exif => _$this._exif ??= new ExifBuilder();
set exif(ExifBuilder? exif) => _$this._exif = exif;
LocationBuilder? _location;
LocationBuilder get location => _$this._location ??= new LocationBuilder();
set location(LocationBuilder? location) => _$this._location = location;
ListBuilder<Tags>? _tags;
ListBuilder<Tags> get tags => _$this._tags ??= new ListBuilder<Tags>();
set tags(ListBuilder<Tags>? tags) => _$this._tags = tags;
ListBuilder<CurrentUserCollections>? _currentUserCollections;
ListBuilder<CurrentUserCollections> get currentUserCollections =>
_$this._currentUserCollections ??=
new ListBuilder<CurrentUserCollections>();
set currentUserCollections(
ListBuilder<CurrentUserCollections>? currentUserCollections) =>
_$this._currentUserCollections = currentUserCollections;
UrlsBuilder? _urls;
UrlsBuilder get urls => _$this._urls ??= new UrlsBuilder();
set urls(UrlsBuilder? urls) => _$this._urls = urls;
LinksBuilder? _links;
LinksBuilder get links => _$this._links ??= new LinksBuilder();
set links(LinksBuilder? links) => _$this._links = links;
UserBuilder? _user;
UserBuilder get user => _$this._user ??= new UserBuilder();
set user(UserBuilder? user) => _$this._user = user;
PhotoBuilder();
PhotoBuilder get _$this {
final $v = _$v;
if ($v != null) {
_id = $v.id;
_createdAt = $v.createdAt;
_updatedAt = $v.updatedAt;
_width = $v.width;
_height = $v.height;
_color = $v.color;
_downloads = $v.downloads;
_likes = $v.likes;
_likedByUser = $v.likedByUser;
_description = $v.description;
_exif = $v.exif?.toBuilder();
_location = $v.location?.toBuilder();
_tags = $v.tags?.toBuilder();
_currentUserCollections = $v.currentUserCollections?.toBuilder();
_urls = $v.urls?.toBuilder();
_links = $v.links?.toBuilder();
_user = $v.user?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(Photo other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Photo;
}
@override
void update(void Function(PhotoBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Photo build() => _build();
_$Photo _build() {
_$Photo _$result;
try {
_$result = _$v ??
new _$Photo._(
id: BuiltValueNullFieldError.checkNotNull(id, r'Photo', 'id'),
createdAt: createdAt,
updatedAt: updatedAt,
width: width,
height: height,
color: color,
downloads: downloads,
likes: likes,
likedByUser: likedByUser,
description: description,
exif: _exif?.build(),
location: _location?.build(),
tags: _tags?.build(),
currentUserCollections: _currentUserCollections?.build(),
urls: _urls?.build(),
links: _links?.build(),
user: _user?.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'exif';
_exif?.build();
_$failedField = 'location';
_location?.build();
_$failedField = 'tags';
_tags?.build();
_$failedField = 'currentUserCollections';
_currentUserCollections?.build();
_$failedField = 'urls';
_urls?.build();
_$failedField = 'links';
_links?.build();
_$failedField = 'user';
_user?.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'Photo', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/material/lib/src/unsplash/photo.g.dart/0 | {
"file_path": "samples/desktop_photo_search/material/lib/src/unsplash/photo.g.dart",
"repo_id": "samples",
"token_count": 6987
} | 1,314 |
// Copyright 2022 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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../unsplash_access_key.dart';
final _unsplashHomepage = Uri.parse(
'https://unsplash.com/?utm_source=${Uri.encodeFull(unsplashAppName)}&utm_medium=referral');
final _unsplashPrivacyPolicy = Uri.parse(
'https://unsplash.com/privacy?utm_source=${Uri.encodeFull(unsplashAppName)}&utm_medium=referral');
class UnsplashNotice extends StatefulWidget {
const UnsplashNotice({super.key, required this.child});
final Widget child;
@override
State<UnsplashNotice> createState() => _UnsplashNoticeState();
}
class _UnsplashNoticeState extends State<UnsplashNotice> {
bool noticeAccepted = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
showDialog<void>(
barrierDismissible: false,
context: context,
builder: (context) {
return _UnsplashDialog(accepted: () {
setState(() {
noticeAccepted = true;
});
});
});
});
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}
class _UnsplashDialog extends StatelessWidget {
const _UnsplashDialog({required this.accepted});
final Function accepted;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Unsplash Notice'),
content: RichText(
text: TextSpan(
text: 'This is a sample desktop application provided by Google'
' that enables you to search ',
style: const TextStyle(color: Colors.grey),
children: [
TextSpan(
text: 'Unsplash',
recognizer: TapGestureRecognizer()
..onTap = () async {
if (!await launchUrl(_unsplashHomepage)) {
throw 'Could not launch $_unsplashHomepage';
}
},
style: const TextStyle(color: Colors.blue),
),
const TextSpan(
text: ' for photographs that interest you. When you search'
' for and interact with photos, Unsplash will collect'
' information about you and your use of the Unsplash'
' services. Learn more about ',
style: TextStyle(color: Colors.grey),
),
TextSpan(
text: 'how Unsplash collects and uses data',
recognizer: TapGestureRecognizer()
..onTap = () async {
if (!await launchUrl(_unsplashPrivacyPolicy)) {
throw 'Could not launch $_unsplashPrivacyPolicy';
}
},
style: const TextStyle(color: Colors.blue),
),
const TextSpan(
text: '.',
style: TextStyle(color: Colors.grey),
),
]),
),
actions: [
TextButton(
child: const Text('GOT IT'),
onPressed: () {
accepted();
Navigator.pop(context);
})
],
);
}
}
| samples/desktop_photo_search/material/lib/src/widgets/unsplash_notice.dart/0 | {
"file_path": "samples/desktop_photo_search/material/lib/src/widgets/unsplash_notice.dart",
"repo_id": "samples",
"token_count": 1638
} | 1,315 |
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <file_selector_windows/file_selector_windows.h>
#include <menubar/menubar_plugin.h>
#include <url_launcher_windows/url_launcher_windows.h>
#include <window_size/window_size_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
FileSelectorWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FileSelectorWindows"));
MenubarPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("MenubarPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
WindowSizePluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("WindowSizePlugin"));
}
| samples/desktop_photo_search/material/windows/flutter/generated_plugin_registrant.cc/0 | {
"file_path": "samples/desktop_photo_search/material/windows/flutter/generated_plugin_registrant.cc",
"repo_id": "samples",
"token_count": 261
} | 1,316 |
# Custom Context Menus
The [Custom Context Menus](https://github.com/flutter/samples/tree/main/context_menus)
app has been moved out of the experimental directory of this repository as it now
works on stable channel of Flutter.
| samples/experimental/context_menus/README.md/0 | {
"file_path": "samples/experimental/context_menus/README.md",
"repo_id": "samples",
"token_count": 62
} | 1,317 |
// The federated_plugin_macos uses the default BatteryMethodChannel used by
// federated_plugin_platform_interface to do platform calls.
| samples/experimental/federated_plugin/federated_plugin_macos/lib/federated_plugin_macos.dart/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_macos/lib/federated_plugin_macos.dart",
"repo_id": "samples",
"token_count": 33
} | 1,318 |
name: federated_plugin_web
description: Web implementation of federated_plugin to retrieve current battery level.
version: 0.0.1
publish_to: none
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
federated_plugin_platform_interface:
path: ../federated_plugin_platform_interface
dev_dependencies:
analysis_defaults:
path: ../../../analysis_defaults
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: ^5.0.2
flutter:
plugin:
platforms:
web:
pluginClass: FederatedPlugin
fileName: federated_plugin_web.dart
| samples/experimental/federated_plugin/federated_plugin_web/pubspec.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_web/pubspec.yaml",
"repo_id": "samples",
"token_count": 247
} | 1,319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.