text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/google_maps_flutter/google_maps_flutter/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,020 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Google Maps Demo',
home: MapSample(),
);
}
}
// #docregion MapSample
class MapSample extends StatefulWidget {
const MapSample({super.key});
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> {
final Completer<GoogleMapController> _controller =
Completer<GoogleMapController>();
static const CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
);
static const CameraPosition _kLake = CameraPosition(
bearing: 192.8334901395799,
target: LatLng(37.43296265331129, -122.08832357078792),
tilt: 59.440717697143555,
zoom: 19.151926040649414);
@override
Widget build(BuildContext context) {
return Scaffold(
body: GoogleMap(
mapType: MapType.hybrid,
initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _goToTheLake,
label: const Text('To the lake!'),
icon: const Icon(Icons.directions_boat),
),
);
}
Future<void> _goToTheLake() async {
final GoogleMapController controller = await _controller.future;
await controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));
}
}
// #enddocregion MapSample
| packages/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample.dart",
"repo_id": "packages",
"token_count": 716
} | 1,021 |
name: google_maps_flutter
description: A Flutter plugin for integrating Google Maps in iOS and Android applications.
repository: https://github.com/flutter/packages/tree/main/packages/google_maps_flutter/google_maps_flutter
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22
version: 2.6.0
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
flutter:
plugin:
platforms:
android:
default_package: google_maps_flutter_android
ios:
default_package: google_maps_flutter_ios
web:
default_package: google_maps_flutter_web
dependencies:
flutter:
sdk: flutter
google_maps_flutter_android: ^2.7.0
google_maps_flutter_ios: ^2.5.0
google_maps_flutter_platform_interface: ^2.5.0
google_maps_flutter_web: ^0.5.6
dev_dependencies:
flutter_test:
sdk: flutter
plugin_platform_interface: ^2.1.7
stream_transform: ^2.0.0
topics:
- google-maps
- google-maps-flutter
- map
# The example deliberately includes limited-use secrets.
false_secrets:
- /example/web/index.html
| packages/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml",
"repo_id": "packages",
"token_count": 437
} | 1,022 |
// 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.googlemaps;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
class CircleBuilder implements CircleOptionsSink {
private final CircleOptions circleOptions;
private final float density;
private boolean consumeTapEvents;
CircleBuilder(float density) {
this.circleOptions = new CircleOptions();
this.density = density;
}
CircleOptions build() {
return circleOptions;
}
boolean consumeTapEvents() {
return consumeTapEvents;
}
@Override
public void setFillColor(int color) {
circleOptions.fillColor(color);
}
@Override
public void setStrokeColor(int color) {
circleOptions.strokeColor(color);
}
@Override
public void setCenter(LatLng center) {
circleOptions.center(center);
}
@Override
public void setRadius(double radius) {
circleOptions.radius(radius);
}
@Override
public void setConsumeTapEvents(boolean consumeTapEvents) {
this.consumeTapEvents = consumeTapEvents;
circleOptions.clickable(consumeTapEvents);
}
@Override
public void setVisible(boolean visible) {
circleOptions.visible(visible);
}
@Override
public void setStrokeWidth(float strokeWidth) {
circleOptions.strokeWidth(strokeWidth * density);
}
@Override
public void setZIndex(float zIndex) {
circleOptions.zIndex(zIndex);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CircleBuilder.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CircleBuilder.java",
"repo_id": "packages",
"token_count": 483
} | 1,023 |
// 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.googlemaps;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import io.flutter.plugin.common.MethodChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class MarkersController {
private final Map<String, MarkerController> markerIdToController;
private final Map<String, String> googleMapsMarkerIdToDartMarkerId;
private final MethodChannel methodChannel;
private GoogleMap googleMap;
MarkersController(MethodChannel methodChannel) {
this.markerIdToController = new HashMap<>();
this.googleMapsMarkerIdToDartMarkerId = new HashMap<>();
this.methodChannel = methodChannel;
}
void setGoogleMap(GoogleMap googleMap) {
this.googleMap = googleMap;
}
void addMarkers(List<Object> markersToAdd) {
if (markersToAdd != null) {
for (Object markerToAdd : markersToAdd) {
addMarker(markerToAdd);
}
}
}
void changeMarkers(List<Object> markersToChange) {
if (markersToChange != null) {
for (Object markerToChange : markersToChange) {
changeMarker(markerToChange);
}
}
}
void removeMarkers(List<Object> markerIdsToRemove) {
if (markerIdsToRemove == null) {
return;
}
for (Object rawMarkerId : markerIdsToRemove) {
if (rawMarkerId == null) {
continue;
}
String markerId = (String) rawMarkerId;
final MarkerController markerController = markerIdToController.remove(markerId);
if (markerController != null) {
markerController.remove();
googleMapsMarkerIdToDartMarkerId.remove(markerController.getGoogleMapsMarkerId());
}
}
}
void showMarkerInfoWindow(String markerId, MethodChannel.Result result) {
MarkerController markerController = markerIdToController.get(markerId);
if (markerController != null) {
markerController.showInfoWindow();
result.success(null);
} else {
result.error("Invalid markerId", "showInfoWindow called with invalid markerId", null);
}
}
void hideMarkerInfoWindow(String markerId, MethodChannel.Result result) {
MarkerController markerController = markerIdToController.get(markerId);
if (markerController != null) {
markerController.hideInfoWindow();
result.success(null);
} else {
result.error("Invalid markerId", "hideInfoWindow called with invalid markerId", null);
}
}
void isInfoWindowShown(String markerId, MethodChannel.Result result) {
MarkerController markerController = markerIdToController.get(markerId);
if (markerController != null) {
result.success(markerController.isInfoWindowShown());
} else {
result.error("Invalid markerId", "isInfoWindowShown called with invalid markerId", null);
}
}
boolean onMarkerTap(String googleMarkerId) {
String markerId = googleMapsMarkerIdToDartMarkerId.get(googleMarkerId);
if (markerId == null) {
return false;
}
methodChannel.invokeMethod("marker#onTap", Convert.markerIdToJson(markerId));
MarkerController markerController = markerIdToController.get(markerId);
if (markerController != null) {
return markerController.consumeTapEvents();
}
return false;
}
void onMarkerDragStart(String googleMarkerId, LatLng latLng) {
String markerId = googleMapsMarkerIdToDartMarkerId.get(googleMarkerId);
if (markerId == null) {
return;
}
final Map<String, Object> data = new HashMap<>();
data.put("markerId", markerId);
data.put("position", Convert.latLngToJson(latLng));
methodChannel.invokeMethod("marker#onDragStart", data);
}
void onMarkerDrag(String googleMarkerId, LatLng latLng) {
String markerId = googleMapsMarkerIdToDartMarkerId.get(googleMarkerId);
if (markerId == null) {
return;
}
final Map<String, Object> data = new HashMap<>();
data.put("markerId", markerId);
data.put("position", Convert.latLngToJson(latLng));
methodChannel.invokeMethod("marker#onDrag", data);
}
void onMarkerDragEnd(String googleMarkerId, LatLng latLng) {
String markerId = googleMapsMarkerIdToDartMarkerId.get(googleMarkerId);
if (markerId == null) {
return;
}
final Map<String, Object> data = new HashMap<>();
data.put("markerId", markerId);
data.put("position", Convert.latLngToJson(latLng));
methodChannel.invokeMethod("marker#onDragEnd", data);
}
void onInfoWindowTap(String googleMarkerId) {
String markerId = googleMapsMarkerIdToDartMarkerId.get(googleMarkerId);
if (markerId == null) {
return;
}
methodChannel.invokeMethod("infoWindow#onTap", Convert.markerIdToJson(markerId));
}
private void addMarker(Object marker) {
if (marker == null) {
return;
}
MarkerBuilder markerBuilder = new MarkerBuilder();
String markerId = Convert.interpretMarkerOptions(marker, markerBuilder);
MarkerOptions options = markerBuilder.build();
addMarker(markerId, options, markerBuilder.consumeTapEvents());
}
private void addMarker(String markerId, MarkerOptions markerOptions, boolean consumeTapEvents) {
final Marker marker = googleMap.addMarker(markerOptions);
MarkerController controller = new MarkerController(marker, consumeTapEvents);
markerIdToController.put(markerId, controller);
googleMapsMarkerIdToDartMarkerId.put(marker.getId(), markerId);
}
private void changeMarker(Object marker) {
if (marker == null) {
return;
}
String markerId = getMarkerId(marker);
MarkerController markerController = markerIdToController.get(markerId);
if (markerController != null) {
Convert.interpretMarkerOptions(marker, markerController);
}
}
@SuppressWarnings("unchecked")
private static String getMarkerId(Object marker) {
Map<String, Object> markerMap = (Map<String, Object>) marker;
return (String) markerMap.get("markerId");
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/MarkersController.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/MarkersController.java",
"repo_id": "packages",
"token_count": 2193
} | 1,024 |
// 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.googlemaps;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class ConvertTest {
@Test
public void ConvertToPointsConvertsThePointsWithFullPrecision() {
double latitude = 43.03725568057;
double longitude = -87.90466904649;
ArrayList<Double> point = new ArrayList<Double>();
point.add(latitude);
point.add(longitude);
ArrayList<ArrayList<Double>> pointsList = new ArrayList<>();
pointsList.add(point);
List<LatLng> latLngs = Convert.toPoints(pointsList);
LatLng latLng = latLngs.get(0);
Assert.assertEquals(latitude, latLng.latitude, 1e-15);
Assert.assertEquals(longitude, latLng.longitude, 1e-15);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/ConvertTest.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/ConvertTest.java",
"repo_id": "packages",
"token_count": 343
} | 1,025 |
// 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 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
class MoveCameraPage extends GoogleMapExampleAppPage {
const MoveCameraPage({Key? key})
: super(const Icon(Icons.map), 'Camera control', key: key);
@override
Widget build(BuildContext context) {
return const MoveCamera();
}
}
class MoveCamera extends StatefulWidget {
const MoveCamera({super.key});
@override
State createState() => MoveCameraState();
}
class MoveCameraState extends State<MoveCamera> {
ExampleGoogleMapController? mapController;
// ignore: use_setters_to_change_properties
void _onMapCreated(ExampleGoogleMapController controller) {
mapController = controller;
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: ExampleGoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition:
const CameraPosition(target: LatLng(0.0, 0.0)),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: <Widget>[
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.newCameraPosition(
const CameraPosition(
bearing: 270.0,
target: LatLng(51.5160895, -0.1294527),
tilt: 30.0,
zoom: 17.0,
),
),
);
},
child: const Text('newCameraPosition'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.newLatLng(
const LatLng(56.1725505, 10.1850512),
),
);
},
child: const Text('newLatLng'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: const LatLng(-38.483935, 113.248673),
northeast: const LatLng(-8.982446, 153.823821),
),
10.0,
),
);
},
child: const Text('newLatLngBounds'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.newLatLngZoom(
const LatLng(37.4231613, -122.087159),
11.0,
),
);
},
child: const Text('newLatLngZoom'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.scrollBy(150.0, -225.0),
);
},
child: const Text('scrollBy'),
),
],
),
Column(
children: <Widget>[
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.zoomBy(
-0.5,
const Offset(30.0, 20.0),
),
);
},
child: const Text('zoomBy with focus'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.zoomBy(-0.5),
);
},
child: const Text('zoomBy'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.zoomIn(),
);
},
child: const Text('zoomIn'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.zoomOut(),
);
},
child: const Text('zoomOut'),
),
TextButton(
onPressed: () {
mapController?.moveCamera(
CameraUpdate.zoomTo(16.0),
);
},
child: const Text('zoomTo'),
),
],
),
],
)
],
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/move_camera.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/move_camera.dart",
"repo_id": "packages",
"token_count": 3299
} | 1,026 |
// 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 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
const CameraPosition _kInitialPosition =
CameraPosition(target: LatLng(-33.852, 151.211), zoom: 11.0);
class LiteModePage extends GoogleMapExampleAppPage {
const LiteModePage({Key? key})
: super(const Icon(Icons.map), 'Lite mode', key: key);
@override
Widget build(BuildContext context) {
return const _LiteModeBody();
}
}
class _LiteModeBody extends StatelessWidget {
const _LiteModeBody();
@override
Widget build(BuildContext context) {
return const Card(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 30.0),
child: Center(
child: SizedBox(
width: 300.0,
height: 300.0,
child: ExampleGoogleMap(
initialCameraPosition: _kInitialPosition,
liteModeEnabled: true,
),
),
),
),
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/lite_mode.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/lite_mode.dart",
"repo_id": "packages",
"token_count": 501
} | 1,027 |
// 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:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
class TileOverlayPage extends GoogleMapExampleAppPage {
const TileOverlayPage({Key? key})
: super(const Icon(Icons.map), 'Tile overlay', key: key);
@override
Widget build(BuildContext context) {
return const TileOverlayBody();
}
}
class TileOverlayBody extends StatefulWidget {
const TileOverlayBody({super.key});
@override
State<StatefulWidget> createState() => TileOverlayBodyState();
}
class TileOverlayBodyState extends State<TileOverlayBody> {
TileOverlayBodyState();
ExampleGoogleMapController? controller;
TileOverlay? _tileOverlay;
// ignore: use_setters_to_change_properties
void _onMapCreated(ExampleGoogleMapController controller) {
this.controller = controller;
}
@override
void dispose() {
super.dispose();
}
void _removeTileOverlay() {
setState(() {
_tileOverlay = null;
});
}
void _addTileOverlay() {
final TileOverlay tileOverlay = TileOverlay(
tileOverlayId: const TileOverlayId('tile_overlay_1'),
tileProvider: _DebugTileProvider(),
);
setState(() {
_tileOverlay = tileOverlay;
});
}
void _clearTileCache() {
if (_tileOverlay != null && controller != null) {
controller!.clearTileCache(_tileOverlay!.tileOverlayId);
}
}
@override
Widget build(BuildContext context) {
final Set<TileOverlay> overlays = <TileOverlay>{
if (_tileOverlay != null) _tileOverlay!,
};
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: SizedBox(
width: 350.0,
height: 300.0,
child: ExampleGoogleMap(
initialCameraPosition: const CameraPosition(
target: LatLng(59.935460, 30.325177),
zoom: 7.0,
),
tileOverlays: overlays,
onMapCreated: _onMapCreated,
),
),
),
TextButton(
onPressed: _addTileOverlay,
child: const Text('Add tile overlay'),
),
TextButton(
onPressed: _removeTileOverlay,
child: const Text('Remove tile overlay'),
),
TextButton(
onPressed: _clearTileCache,
child: const Text('Clear tile cache'),
),
],
);
}
}
class _DebugTileProvider implements TileProvider {
_DebugTileProvider() {
boxPaint.isAntiAlias = true;
boxPaint.color = Colors.blue;
boxPaint.strokeWidth = 2.0;
boxPaint.style = PaintingStyle.stroke;
}
static const int width = 100;
static const int height = 100;
static final Paint boxPaint = Paint();
static const TextStyle textStyle = TextStyle(
color: Colors.red,
fontSize: 20,
);
@override
Future<Tile> getTile(int x, int y, int? zoom) async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
final TextSpan textSpan = TextSpan(
text: '$x,$y',
style: textStyle,
);
final TextPainter textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout(
maxWidth: width.toDouble(),
);
textPainter.paint(canvas, Offset.zero);
canvas.drawRect(
Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint);
final ui.Picture picture = recorder.endRecording();
final Uint8List byteData = await picture
.toImage(width, height)
.then((ui.Image image) =>
image.toByteData(format: ui.ImageByteFormat.png))
.then((ByteData? byteData) => byteData!.buffer.asUint8List());
return Tile(width, height, byteData);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/tile_overlay.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/tile_overlay.dart",
"repo_id": "packages",
"token_count": 1700
} | 1,028 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
#import <GoogleMaps/GoogleMaps.h>
#import "GoogleMapController.h"
NS_ASSUME_NONNULL_BEGIN
// Defines marker controllable by Flutter.
@interface FLTGoogleMapMarkerController : NSObject
@property(assign, nonatomic, readonly) BOOL consumeTapEvents;
- (instancetype)initMarkerWithPosition:(CLLocationCoordinate2D)position
identifier:(NSString *)identifier
mapView:(GMSMapView *)mapView;
- (void)showInfoWindow;
- (void)hideInfoWindow;
- (BOOL)isInfoWindowShown;
- (void)removeMarker;
@end
@interface FLTMarkersController : NSObject
- (instancetype)initWithMethodChannel:(FlutterMethodChannel *)methodChannel
mapView:(GMSMapView *)mapView
registrar:(NSObject<FlutterPluginRegistrar> *)registrar;
- (void)addMarkers:(NSArray *)markersToAdd;
- (void)changeMarkers:(NSArray *)markersToChange;
- (void)removeMarkersWithIdentifiers:(NSArray *)identifiers;
- (BOOL)didTapMarkerWithIdentifier:(NSString *)identifier;
- (void)didStartDraggingMarkerWithIdentifier:(NSString *)identifier
location:(CLLocationCoordinate2D)coordinate;
- (void)didEndDraggingMarkerWithIdentifier:(NSString *)identifier
location:(CLLocationCoordinate2D)coordinate;
- (void)didDragMarkerWithIdentifier:(NSString *)identifier
location:(CLLocationCoordinate2D)coordinate;
- (void)didTapInfoWindowOfMarkerWithIdentifier:(NSString *)identifier;
- (void)showMarkerInfoWindowWithIdentifier:(NSString *)identifier result:(FlutterResult)result;
- (void)hideMarkerInfoWindowWithIdentifier:(NSString *)identifier result:(FlutterResult)result;
- (void)isInfoWindowShownForMarkerWithIdentifier:(NSString *)identifier
result:(FlutterResult)result;
@end
NS_ASSUME_NONNULL_END
| packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapMarkerController.h/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapMarkerController.h",
"repo_id": "packages",
"token_count": 823
} | 1,029 |
## 2.6.0
* Adds support for marker clustering.
## 2.5.0
* Adds `style` to the `MapConfiguration` to allow setting style as part of
map creation.
* Adds `getStyleError` to the platform interface, to allow asynchronous access
to style errors that occur during initialization.
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 2.4.3
* Updates minimum required plugin_platform_interface version to 2.1.7.
## 2.4.2
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Fixes new lint warnings.
## 2.4.1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.4.0
* Adds options for gesture handling and tilt controls on web.
## 2.3.0
* Adds a `cloudMapId` parameter to support cloud-based map styling.
## 2.2.7
* Removes obsolete null checks on non-nullable values.
* Updates minimum Flutter version to 3.3.
* Aligns Dart and Flutter SDK constraints.
## 2.2.6
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.2.5
* Updates code for stricter lint checks.
## 2.2.4
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
## 2.2.3
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 2.2.2
* Adds a `size` parameter to `BitmapDescriptor.fromBytes`, so **web** applications
can specify the actual *physical size* of the bitmap. The parameter is not needed
(and ignored) in other platforms. Issue [#73789](https://github.com/flutter/flutter/issues/73789).
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.2.1
* Adds a new interface for inspecting the platform map state in tests.
## 2.2.0
* Adds new versions of `buildView` and `updateOptions` that take a new option
class instead of a dictionary, to remove the cross-package dependency on
magic string keys.
* Adopts several parameter objects in the new `buildView` variant to
future-proof it against future changes.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231).
## 2.1.7
* Updates code for stricter analysis options.
* Removes unnecessary imports.
## 2.1.6
* Migrates from `ui.hash*` to `Object.hash*`.
* Updates minimum Flutter version to 2.5.0.
## 2.1.5
* Removes dependency on `meta`.
## 2.1.4
* Update to use the `verify` method introduced in plugin_platform_interface 2.1.0.
## 2.1.3
* `LatLng` constructor maintains longitude precision when given within
acceptable range
## 2.1.2
* Add additional marker drag events
## 2.1.1
* Method `buildViewWithTextDirection` has been added to the platform interface.
## 2.1.0
* Add support for Hybrid Composition when building the Google Maps widget on Android. Set
`MethodChannelGoogleMapsFlutter.useAndroidViewSurface` to `true` to build with Hybrid Composition.
## 2.0.4
* Preserve the `TileProvider` when copying `TileOverlay`, fixing a
regression with tile overlays introduced in the null safety migration.
## 2.0.3
* Fix type issues in `isMarkerInfoWindowShown` and `getZoomLevel` introduced
in the null safety migration.
## 2.0.2
* Mark constructors for CameraUpdate, CircleId, MapsObjectId, MarkerId, PolygonId, PolylineId and TileOverlayId as const
## 2.0.1
* Update platform_plugin_interface version requirement.
## 2.0.0
* Migrated to null-safety.
* BREAKING CHANGE: Removed deprecated APIs.
* BREAKING CHANGE: Many sets in APIs that used to treat null and empty set as
equivalent now require passing an empty set.
* BREAKING CHANGE: toJson now always returns an `Object`; the details of the
object type and structure should be treated as an implementation detail.
## 1.2.0
* Add TileOverlay support.
## 1.1.0
* Add support for holes in Polygons.
## 1.0.6
* Update Flutter SDK constraint.
## 1.0.5
* Temporarily add a `fromJson` constructor to `BitmapDescriptor` so serialized descriptors can be synchronously re-hydrated. This will be removed when a fix for [this issue](https://github.com/flutter/flutter/issues/70330) lands.
## 1.0.4
* Add a `dispose` method to the interface, so implementations may cleanup resources acquired on `init`.
## 1.0.3
* Pass icon width/height if present on `fromAssetImage` BitmapDescriptors (web only)
## 1.0.2
* Update lower bound of dart dependency to 2.1.0.
## 1.0.1
* Initial open source release.
## 1.0.0 ... 1.0.0+5
* Development.
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/CHANGELOG.md/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1403
} | 1,030 |
// 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';
/// [ClusterManager] update events to be applied to the [GoogleMap].
///
/// Used in [GoogleMapController] when the map is updated.
// (Do not re-export)
class ClusterManagerUpdates extends MapsObjectUpdates<ClusterManager> {
/// Computes [ClusterManagerUpdates] given previous and current [ClusterManager]s.
ClusterManagerUpdates.from(super.previous, super.current)
: super.from(objectName: 'clusterManager');
/// Set of Clusters to be added in this update.
Set<ClusterManager> get clusterManagersToAdd => objectsToAdd;
/// Set of ClusterManagerIds to be removed in this update.
Set<ClusterManagerId> get clusterManagerIdsToRemove =>
objectIdsToRemove.cast<ClusterManagerId>();
/// Set of Clusters to be changed in this update.
Set<ClusterManager> get clusterManagersToChange => objectsToChange;
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager_updates.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager_updates.dart",
"repo_id": "packages",
"token_count": 293
} | 1,031 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show immutable;
/// Contains information about a Tile that is returned by a [TileProvider].
@immutable
class Tile {
/// Creates an immutable representation of a [Tile] to draw by [TileProvider].
const Tile(this.width, this.height, this.data);
/// The width of the image encoded by data in logical pixels.
final int width;
/// The height of the image encoded by data in logical pixels.
final int height;
/// A byte array containing the image data.
///
/// The image data format must be natively supported for decoding by the platform.
/// e.g on Android it can only be one of the [supported image formats for decoding](https://developer.android.com/guide/topics/media/media-formats#image-formats).
final Uint8List? data;
/// Converts this object to JSON.
Object toJson() {
final Map<String, Object> json = <String, Object>{};
void addIfPresent(String fieldName, Object? value) {
if (value != null) {
json[fieldName] = value;
}
}
addIfPresent('width', width);
addIfPresent('height', height);
addIfPresent('data', data);
return json;
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile.dart",
"repo_id": "packages",
"token_count": 408
} | 1,032 |
// 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_maps_flutter_platform_interface/src/types/types.dart';
void main() {
group('keyByClusterManagerId', () {
test('returns a Map keyed by clusterManagerId', () {
const ClusterManagerId id1 = ClusterManagerId('id1');
const ClusterManagerId id2 = ClusterManagerId('id2');
const ClusterManagerId id3 = ClusterManagerId('id3');
final List<ClusterManager> clusterManagers = <ClusterManager>[
const ClusterManager(clusterManagerId: id1),
const ClusterManager(clusterManagerId: id2),
const ClusterManager(clusterManagerId: id3),
];
final Map<ClusterManagerId, ClusterManager> result =
keyByClusterManagerId(clusterManagers);
expect(result, isA<Map<ClusterManagerId, ClusterManager>>());
expect(result[id1], equals(clusterManagers[0]));
expect(result[id2], equals(clusterManagers[1]));
expect(result[id3], equals(clusterManagers[2]));
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/cluster_manager_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/cluster_manager_test.dart",
"repo_id": "packages",
"token_count": 416
} | 1,033 |
// Mocks generated by Mockito 5.4.4 from annotations
// in google_maps_flutter_web_integration_tests/integration_test/overlays_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:google_maps_flutter_platform_interface/src/types/types.dart'
as _i2;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeTile_0 extends _i1.SmartFake implements _i2.Tile {
_FakeTile_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [TileProvider].
///
/// See the documentation for Mockito's code generation for more information.
class MockTileProvider extends _i1.Mock implements _i2.TileProvider {
@override
_i3.Future<_i2.Tile> getTile(
int? x,
int? y,
int? zoom,
) =>
(super.noSuchMethod(
Invocation.method(
#getTile,
[
x,
y,
zoom,
],
),
returnValue: _i3.Future<_i2.Tile>.value(_FakeTile_0(
this,
Invocation.method(
#getTile,
[
x,
y,
zoom,
],
),
)),
returnValueForMissingStub: _i3.Future<_i2.Tile>.value(_FakeTile_0(
this,
Invocation.method(
#getTile,
[
x,
y,
zoom,
],
),
)),
) as _i3.Future<_i2.Tile>);
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.mocks.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.mocks.dart",
"repo_id": "packages",
"token_count": 993
} | 1,034 |
// 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.dart';
/// The web implementation of [GoogleMapsFlutterPlatform].
///
/// This class implements the `package:google_maps_flutter` functionality for the web.
class GoogleMapsPlugin extends GoogleMapsFlutterPlatform {
/// Registers this class as the default instance of [GoogleMapsFlutterPlatform].
static void registerWith(Registrar registrar) {
GoogleMapsFlutterPlatform.instance = GoogleMapsPlugin();
}
// A cache of map controllers by map Id.
Map<int, GoogleMapController> _mapById = <int, GoogleMapController>{};
/// Allows tests to inject controllers without going through the buildView flow.
@visibleForTesting
// ignore: use_setters_to_change_properties
void debugSetMapById(Map<int, GoogleMapController> mapById) {
_mapById = mapById;
}
// Convenience getter for a stream of events filtered by their mapId.
Stream<MapEvent<Object?>> _events(int mapId) => _map(mapId).events;
/// Retrieve a map controller by its mapId.
GoogleMapController _map(int mapId) {
final GoogleMapController? controller = _mapById[mapId];
assert(controller != null,
'Maps cannot be retrieved before calling buildView!');
return controller!;
}
@override
Future<void> init(int mapId) async {
// The internal instance of our controller is initialized eagerly in `buildView`,
// so we don't have to do anything in this method, which is left intentionally
// blank.
assert(_mapById[mapId] != null, 'Must call buildWidget before init!');
}
/// Updates the options of a given `mapId`.
///
/// This attempts to merge the new `optionsUpdate` passed in, with the previous
/// options passed to the map (in other updates, or when creating it).
@override
Future<void> updateMapConfiguration(
MapConfiguration update, {
required int mapId,
}) async {
_map(mapId).updateMapConfiguration(update);
}
/// Applies the passed in `markerUpdates` to the `mapId`.
@override
Future<void> updateMarkers(
MarkerUpdates markerUpdates, {
required int mapId,
}) async {
_map(mapId).updateMarkers(markerUpdates);
}
/// Applies the passed in `polygonUpdates` to the `mapId`.
@override
Future<void> updatePolygons(
PolygonUpdates polygonUpdates, {
required int mapId,
}) async {
_map(mapId).updatePolygons(polygonUpdates);
}
/// Applies the passed in `polylineUpdates` to the `mapId`.
@override
Future<void> updatePolylines(
PolylineUpdates polylineUpdates, {
required int mapId,
}) async {
_map(mapId).updatePolylines(polylineUpdates);
}
/// Applies the passed in `circleUpdates` to the `mapId`.
@override
Future<void> updateCircles(
CircleUpdates circleUpdates, {
required int mapId,
}) async {
_map(mapId).updateCircles(circleUpdates);
}
@override
Future<void> updateTileOverlays({
required Set<TileOverlay> newTileOverlays,
required int mapId,
}) async {
_map(mapId).updateTileOverlays(newTileOverlays);
}
@override
Future<void> clearTileCache(
TileOverlayId tileOverlayId, {
required int mapId,
}) async {
_map(mapId).clearTileCache(tileOverlayId);
}
/// Applies the given `cameraUpdate` to the current viewport (with animation).
@override
Future<void> animateCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {
return moveCamera(cameraUpdate, mapId: mapId);
}
/// Applies the given `cameraUpdate` to the current viewport.
@override
Future<void> moveCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {
return _map(mapId).moveCamera(cameraUpdate);
}
/// Sets the passed-in `mapStyle` to the map.
///
/// This function just adds a 'styles' option to the current map options.
///
/// Subsequent calls to this method override previous calls, you need to
/// pass full styles.
@override
Future<void> setMapStyle(
String? mapStyle, {
required int mapId,
}) async {
_map(mapId).updateStyles(_mapStyles(mapStyle));
}
/// Returns the bounds of the current viewport.
@override
Future<LatLngBounds> getVisibleRegion({
required int mapId,
}) {
return _map(mapId).getVisibleRegion();
}
/// Returns the screen coordinate (in pixels) of a given `latLng`.
@override
Future<ScreenCoordinate> getScreenCoordinate(
LatLng latLng, {
required int mapId,
}) {
return _map(mapId).getScreenCoordinate(latLng);
}
/// Returns the [LatLng] of a [ScreenCoordinate] of the viewport.
@override
Future<LatLng> getLatLng(
ScreenCoordinate screenCoordinate, {
required int mapId,
}) {
return _map(mapId).getLatLng(screenCoordinate);
}
/// Shows the [InfoWindow] (if any) of the [Marker] identified by `markerId`.
///
/// See also:
/// * [hideMarkerInfoWindow] to hide the info window.
/// * [isMarkerInfoWindowShown] to check if the info window is visible/hidden.
@override
Future<void> showMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {
_map(mapId).showInfoWindow(markerId);
}
/// Hides the [InfoWindow] (if any) of the [Marker] identified by `markerId`.
///
/// See also:
/// * [showMarkerInfoWindow] to show the info window.
/// * [isMarkerInfoWindowShown] to check if the info window is shown.
@override
Future<void> hideMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {
_map(mapId).hideInfoWindow(markerId);
}
/// Returns true if the [InfoWindow] of the [Marker] identified by `markerId` is shown.
///
/// See also:
/// * [showMarkerInfoWindow] to show the info window.
/// * [hideMarkerInfoWindow] to hide the info window.
@override
Future<bool> isMarkerInfoWindowShown(
MarkerId markerId, {
required int mapId,
}) async {
return _map(mapId).isInfoWindowShown(markerId);
}
/// Returns the zoom level of the `mapId`.
@override
Future<double> getZoomLevel({
required int mapId,
}) {
return _map(mapId).getZoomLevel();
}
// The following are the 11 possible streams of data from the native side
// into the plugin
@override
Stream<CameraMoveStartedEvent> onCameraMoveStarted({required int mapId}) {
return _events(mapId).whereType<CameraMoveStartedEvent>();
}
@override
Stream<CameraMoveEvent> onCameraMove({required int mapId}) {
return _events(mapId).whereType<CameraMoveEvent>();
}
@override
Stream<CameraIdleEvent> onCameraIdle({required int mapId}) {
return _events(mapId).whereType<CameraIdleEvent>();
}
@override
Stream<MarkerTapEvent> onMarkerTap({required int mapId}) {
return _events(mapId).whereType<MarkerTapEvent>();
}
@override
Stream<InfoWindowTapEvent> onInfoWindowTap({required int mapId}) {
return _events(mapId).whereType<InfoWindowTapEvent>();
}
@override
Stream<MarkerDragStartEvent> onMarkerDragStart({required int mapId}) {
return _events(mapId).whereType<MarkerDragStartEvent>();
}
@override
Stream<MarkerDragEvent> onMarkerDrag({required int mapId}) {
return _events(mapId).whereType<MarkerDragEvent>();
}
@override
Stream<MarkerDragEndEvent> onMarkerDragEnd({required int mapId}) {
return _events(mapId).whereType<MarkerDragEndEvent>();
}
@override
Stream<PolylineTapEvent> onPolylineTap({required int mapId}) {
return _events(mapId).whereType<PolylineTapEvent>();
}
@override
Stream<PolygonTapEvent> onPolygonTap({required int mapId}) {
return _events(mapId).whereType<PolygonTapEvent>();
}
@override
Stream<CircleTapEvent> onCircleTap({required int mapId}) {
return _events(mapId).whereType<CircleTapEvent>();
}
@override
Stream<MapTapEvent> onTap({required int mapId}) {
return _events(mapId).whereType<MapTapEvent>();
}
@override
Stream<MapLongPressEvent> onLongPress({required int mapId}) {
return _events(mapId).whereType<MapLongPressEvent>();
}
@override
Future<String?> getStyleError({required int mapId}) async {
return _map(mapId).lastStyleError;
}
/// Disposes of the current map. It can't be used afterwards!
@override
void dispose({required int mapId}) {
_map(mapId).dispose();
_mapById.remove(mapId);
}
@override
Widget buildViewWithConfiguration(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required MapWidgetConfiguration widgetConfiguration,
MapObjects mapObjects = const MapObjects(),
MapConfiguration mapConfiguration = const MapConfiguration(),
}) {
// Bail fast if we've already rendered this map ID...
if (_mapById[creationId]?.widget != null) {
return _mapById[creationId]!.widget!;
}
final StreamController<MapEvent<Object?>> controller =
StreamController<MapEvent<Object?>>.broadcast();
final GoogleMapController mapController = GoogleMapController(
mapId: creationId,
streamController: controller,
widgetConfiguration: widgetConfiguration,
mapObjects: mapObjects,
mapConfiguration: mapConfiguration,
)..init(); // Initialize the controller
_mapById[creationId] = mapController;
mapController.events
.whereType<WebMapReadyEvent>()
.first
.then((WebMapReadyEvent event) {
assert(creationId == event.mapId,
'Received WebMapReadyEvent for the wrong map');
// Notify the plugin now that there's a fully initialized controller.
onPlatformViewCreated.call(event.mapId);
});
assert(mapController.widget != null,
'The widget of a GoogleMapController cannot be null before calling dispose on it.');
return mapController.widget!;
}
/// Populates [GoogleMapsFlutterInspectorPlatform.instance] to allow
/// inspecting the platform map state.
@override
void enableDebugInspection() {
GoogleMapsInspectorPlatform.instance = GoogleMapsInspectorWeb(
(int mapId) => _map(mapId).configuration,
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart",
"repo_id": "packages",
"token_count": 3390
} | 1,035 |
name: google_maps_flutter_web
description: Web platform implementation of google_maps_flutter
repository: https://github.com/flutter/packages/tree/main/packages/google_maps_flutter/google_maps_flutter_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22
version: 0.5.6+2
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
flutter:
plugin:
implements: google_maps_flutter
platforms:
web:
pluginClass: GoogleMapsPlugin
fileName: google_maps_flutter_web.dart
dependencies:
collection: ^1.16.0
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
google_maps: ^7.1.0
google_maps_flutter_platform_interface: ^2.5.0
sanitize_html: ^2.0.0
stream_transform: ^2.0.0
web: ^0.5.1
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- google-maps
- google-maps-flutter
- map
# The example deliberately includes limited-use secrets.
false_secrets:
- /example/web/index.html
| packages/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml",
"repo_id": "packages",
"token_count": 409
} | 1,036 |
// 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:google_sign_in_web/web_only.dart' as web;
import 'stub.dart';
/// Renders a web-only SIGN IN button.
Widget buildSignInButton({HandleSignInFn? onPressed}) {
return web.renderButton();
}
| packages/packages/google_sign_in/google_sign_in/example/lib/src/sign_in_button/web.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/example/lib/src/sign_in_button/web.dart",
"repo_id": "packages",
"token_count": 129
} | 1,037 |
// 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.
/// Encapsulation of the fields that represent a Google user's identity.
abstract class GoogleIdentity {
/// The unique ID for the Google account.
///
/// This is the preferred unique key to use for a user record.
///
/// _Important_: Do not use this returned Google ID to communicate the
/// currently signed in user to your backend server. Instead, send an ID token
/// which can be securely validated on the server.
/// `GoogleSignInAccount.authentication.idToken` provides such an ID token.
String get id;
/// The email address of the signed in user.
///
/// Applications should not key users by email address since a Google
/// account's email address can change. Use [id] as a key instead.
///
/// _Important_: Do not use this returned email address to communicate the
/// currently signed in user to your backend server. Instead, send an ID token
/// which can be securely validated on the server.
/// `GoogleSignInAccount.authentication.idToken` provides such an ID token.
String get email;
/// The display name of the signed in user.
///
/// Not guaranteed to be present for all users, even when configured.
String? get displayName;
/// The photo url of the signed in user if the user has a profile picture.
///
/// Not guaranteed to be present for all users, even when configured.
String? get photoUrl;
/// Server auth code used to access Google Login
String? get serverAuthCode;
}
| packages/packages/google_sign_in/google_sign_in/lib/src/common.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/lib/src/common.dart",
"repo_id": "packages",
"token_count": 405
} | 1,038 |
rootProject.name = 'google_sign_in_android'
| packages/packages/google_sign_in/google_sign_in_android/android/settings.gradle/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_android/android/settings.gradle",
"repo_id": "packages",
"token_count": 15
} | 1,039 |
// 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.googlesigninexample;
import static org.junit.Assert.assertTrue;
import androidx.test.core.app.ActivityScenario;
import io.flutter.plugins.googlesignin.GoogleSignInPlugin;
import org.junit.Ignore;
import org.junit.Test;
public class GoogleSignInTest {
@Test
@Ignore(
"This is failing on Firebase Test Lab. See https://github.com/flutter/flutter/issues/135683")
public void googleSignInPluginIsAdded() {
final ActivityScenario<GoogleSignInTestActivity> scenario =
ActivityScenario.launch(GoogleSignInTestActivity.class);
scenario.onActivity(
activity -> {
assertTrue(activity.engine.getPlugins().has(GoogleSignInPlugin.class));
});
}
}
| packages/packages/google_sign_in/google_sign_in_android/example/android/app/src/androidTest/java/io/flutter/plugins/googlesigninexample/GoogleSignInTest.java/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_android/example/android/app/src/androidTest/java/io/flutter/plugins/googlesigninexample/GoogleSignInTest.java",
"repo_id": "packages",
"token_count": 297
} | 1,040 |
// 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 "FLTGoogleSignInPlugin.h"
#import "FLTGoogleSignInPlugin_Test.h"
#import <GoogleSignIn/GoogleSignIn.h>
// The key within `GoogleService-Info.plist` used to hold the application's
// client id. See https://developers.google.com/identity/sign-in/ios/start
// for more info.
static NSString *const kClientIdKey = @"CLIENT_ID";
static NSString *const kServerClientIdKey = @"SERVER_CLIENT_ID";
static NSDictionary<NSString *, id> *loadGoogleServiceInfo(void) {
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info"
ofType:@"plist"];
if (plistPath) {
return [[NSDictionary alloc] initWithContentsOfFile:plistPath];
}
return nil;
}
// These error codes must match with ones declared on Android and Dart sides.
static NSString *const kErrorReasonSignInRequired = @"sign_in_required";
static NSString *const kErrorReasonSignInCanceled = @"sign_in_canceled";
static NSString *const kErrorReasonNetworkError = @"network_error";
static NSString *const kErrorReasonSignInFailed = @"sign_in_failed";
static FlutterError *getFlutterError(NSError *error) {
NSString *errorCode;
if (error.code == kGIDSignInErrorCodeHasNoAuthInKeychain) {
errorCode = kErrorReasonSignInRequired;
} else if (error.code == kGIDSignInErrorCodeCanceled) {
errorCode = kErrorReasonSignInCanceled;
} else if ([error.domain isEqualToString:NSURLErrorDomain]) {
errorCode = kErrorReasonNetworkError;
} else {
errorCode = kErrorReasonSignInFailed;
}
return [FlutterError errorWithCode:errorCode
message:error.domain
details:error.localizedDescription];
}
@interface FLTGoogleSignInPlugin ()
// The contents of GoogleService-Info.plist, if it exists.
@property(strong, nullable) NSDictionary<NSString *, id> *googleServiceProperties;
// The plugin registrar, for querying views.
@property(strong, nonnull) id<FlutterPluginRegistrar> registrar;
@end
@implementation FLTGoogleSignInPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FLTGoogleSignInPlugin *instance = [[FLTGoogleSignInPlugin alloc] initWithRegistrar:registrar];
[registrar addApplicationDelegate:instance];
FSIGoogleSignInApiSetup(registrar.messenger, instance);
}
- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
return [self initWithSignIn:GIDSignIn.sharedInstance registrar:registrar];
}
- (instancetype)initWithSignIn:(GIDSignIn *)signIn
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
return [self initWithSignIn:signIn
registrar:registrar
googleServiceProperties:loadGoogleServiceInfo()];
}
- (instancetype)initWithSignIn:(GIDSignIn *)signIn
registrar:(NSObject<FlutterPluginRegistrar> *)registrar
googleServiceProperties:(nullable NSDictionary<NSString *, id> *)googleServiceProperties {
self = [super init];
if (self) {
_signIn = signIn;
_registrar = registrar;
_googleServiceProperties = googleServiceProperties;
// On the iOS simulator, we get "Broken pipe" errors after sign-in for some
// unknown reason. We can avoid crashing the app by ignoring them.
signal(SIGPIPE, SIG_IGN);
_requestedScopes = [[NSSet alloc] init];
}
return self;
}
#pragma mark - <FlutterPlugin> protocol
#if TARGET_OS_IOS
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
return [self.signIn handleURL:url];
}
#else
- (BOOL)handleOpenURLs:(NSArray<NSURL *> *)urls {
BOOL handled = NO;
for (NSURL *url in urls) {
handled = handled || [self.signIn handleURL:url];
}
return handled;
}
#endif
#pragma mark - FSIGoogleSignInApi
- (void)initializeSignInWithParameters:(nonnull FSIInitParams *)params
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
GIDConfiguration *configuration = [self configurationWithClientIdentifier:params.clientId
serverClientIdentifier:params.serverClientId
hostedDomain:params.hostedDomain];
self.requestedScopes = [NSSet setWithArray:params.scopes];
if (configuration != nil) {
self.configuration = configuration;
}
}
- (void)signInSilentlyWithCompletion:(nonnull void (^)(FSIUserData *_Nullable,
FlutterError *_Nullable))completion {
[self.signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser *_Nullable user,
NSError *_Nullable error) {
[self didSignInForUser:user withServerAuthCode:nil completion:completion error:error];
}];
}
- (nullable NSNumber *)isSignedInWithError:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return @([self.signIn hasPreviousSignIn]);
}
- (void)signInWithCompletion:(nonnull void (^)(FSIUserData *_Nullable,
FlutterError *_Nullable))completion {
@try {
// If the configuration settings are passed from the Dart API, use those.
// Otherwise, use settings from the GoogleService-Info.plist if available.
// If neither are available, do not set the configuration - GIDSignIn will automatically use
// settings from the Info.plist (which is the recommended method).
if (!self.configuration && self.googleServiceProperties) {
self.configuration = [self configurationWithClientIdentifier:nil
serverClientIdentifier:nil
hostedDomain:nil];
}
if (self.configuration) {
self.signIn.configuration = self.configuration;
}
[self signInWithHint:nil
additionalScopes:self.requestedScopes.allObjects
completion:^(GIDSignInResult *_Nullable signInResult, NSError *_Nullable error) {
GIDGoogleUser *user;
NSString *serverAuthCode;
if (signInResult) {
user = signInResult.user;
serverAuthCode = signInResult.serverAuthCode;
}
[self didSignInForUser:user
withServerAuthCode:serverAuthCode
completion:completion
error:error];
}];
} @catch (NSException *e) {
completion(nil, [FlutterError errorWithCode:@"google_sign_in" message:e.reason details:e.name]);
[e raise];
}
}
- (void)getAccessTokenWithCompletion:(nonnull void (^)(FSITokenData *_Nullable,
FlutterError *_Nullable))completion {
GIDGoogleUser *currentUser = self.signIn.currentUser;
[currentUser refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *_Nullable user,
NSError *_Nullable error) {
if (error) {
completion(nil, getFlutterError(error));
} else {
completion([FSITokenData makeWithIdToken:user.idToken.tokenString
accessToken:user.accessToken.tokenString],
nil);
}
}];
}
- (void)signOutWithError:(FlutterError *_Nullable *_Nonnull)error {
[self.signIn signOut];
}
- (void)disconnectWithCompletion:(nonnull void (^)(FlutterError *_Nullable))completion {
[self.signIn disconnectWithCompletion:^(NSError *_Nullable error) {
// TODO(stuartmorgan): This preserves the pre-Pigeon-migration behavior, but it's unclear why
// 'error' is being ignored here.
completion(nil);
}];
}
- (void)requestScopes:(nonnull NSArray<NSString *> *)scopes
completion:(nonnull void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
self.requestedScopes = [self.requestedScopes setByAddingObjectsFromArray:scopes];
NSSet<NSString *> *requestedScopes = self.requestedScopes;
@try {
GIDGoogleUser *currentUser = self.signIn.currentUser;
if (currentUser == nil) {
completion(nil, [FlutterError errorWithCode:@"sign_in_required"
message:@"No account to grant scopes."
details:nil]);
}
[self addScopes:requestedScopes.allObjects
completion:^(GIDSignInResult *_Nullable signInResult, NSError *_Nullable addedScopeError) {
BOOL granted = NO;
FlutterError *error = nil;
if ([addedScopeError.domain isEqualToString:kGIDSignInErrorDomain] &&
addedScopeError.code == kGIDSignInErrorCodeMismatchWithCurrentUser) {
error = [FlutterError errorWithCode:@"mismatch_user"
message:@"There is an operation on a previous "
@"user. Try signing in again."
details:nil];
} else if ([addedScopeError.domain isEqualToString:kGIDSignInErrorDomain] &&
addedScopeError.code == kGIDSignInErrorCodeScopesAlreadyGranted) {
// Scopes already granted, report success.
granted = YES;
} else if (signInResult.user) {
NSSet<NSString *> *grantedScopes =
[NSSet setWithArray:signInResult.user.grantedScopes];
granted = [requestedScopes isSubsetOfSet:grantedScopes];
}
completion(error == nil ? @(granted) : nil, error);
}];
} @catch (NSException *e) {
completion(nil, [FlutterError errorWithCode:@"request_scopes" message:e.reason details:e.name]);
}
}
#pragma mark - private methods
// Wraps the iOS and macOS sign in display methods.
- (void)signInWithHint:(nullable NSString *)hint
additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
completion:(nullable void (^)(GIDSignInResult *_Nullable signInResult,
NSError *_Nullable error))completion {
#if TARGET_OS_OSX
[self.signIn signInWithPresentingWindow:self.registrar.view.window
hint:hint
additionalScopes:additionalScopes
completion:completion];
#else
[self.signIn signInWithPresentingViewController:[self topViewController]
hint:hint
additionalScopes:additionalScopes
completion:completion];
#endif
}
// Wraps the iOS and macOS scope addition methods.
- (void)addScopes:(NSArray<NSString *> *)scopes
completion:(nullable void (^)(GIDSignInResult *_Nullable signInResult,
NSError *_Nullable error))completion {
GIDGoogleUser *currentUser = self.signIn.currentUser;
#if TARGET_OS_OSX
[currentUser addScopes:scopes presentingWindow:self.registrar.view.window completion:completion];
#else
[currentUser addScopes:scopes
presentingViewController:[self topViewController]
completion:completion];
#endif
}
/// @return @c nil if GoogleService-Info.plist not found and runtimeClientIdentifier is not
/// provided.
- (GIDConfiguration *)configurationWithClientIdentifier:(NSString *)runtimeClientIdentifier
serverClientIdentifier:(NSString *)runtimeServerClientIdentifier
hostedDomain:(NSString *)hostedDomain {
NSString *clientID = runtimeClientIdentifier ?: self.googleServiceProperties[kClientIdKey];
if (!clientID) {
// Creating a GIDConfiguration requires a client identifier.
return nil;
}
NSString *serverClientID =
runtimeServerClientIdentifier ?: self.googleServiceProperties[kServerClientIdKey];
return [[GIDConfiguration alloc] initWithClientID:clientID
serverClientID:serverClientID
hostedDomain:hostedDomain
openIDRealm:nil];
}
- (void)didSignInForUser:(GIDGoogleUser *)user
withServerAuthCode:(NSString *_Nullable)serverAuthCode
completion:(nonnull void (^)(FSIUserData *_Nullable,
FlutterError *_Nullable))completion
error:(NSError *)error {
if (error != nil) {
// Forward all errors and let Dart side decide how to handle.
completion(nil, getFlutterError(error));
} else {
NSURL *photoUrl;
if (user.profile.hasImage) {
// Placeholder that will be replaced by on the Dart side based on screen size.
photoUrl = [user.profile imageURLWithDimension:1337];
}
NSString *idToken;
if (user.idToken) {
idToken = user.idToken.tokenString;
}
completion([FSIUserData makeWithDisplayName:user.profile.name
email:user.profile.email
userId:user.userID
photoUrl:[photoUrl absoluteString]
serverAuthCode:serverAuthCode
idToken:idToken],
nil);
}
}
#if TARGET_OS_IOS
- (UIViewController *)topViewController {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// TODO(stuartmorgan) Provide a non-deprecated codepath. See
// https://github.com/flutter/flutter/issues/104117
return [self topViewControllerFromViewController:[UIApplication sharedApplication]
.keyWindow.rootViewController];
#pragma clang diagnostic pop
}
/// This method recursively iterate through the view hierarchy
/// to return the top most view controller.
///
/// It supports the following scenarios:
///
/// - The view controller is presenting another view.
/// - The view controller is a UINavigationController.
/// - The view controller is a UITabBarController.
///
/// @return The top most view controller.
- (UIViewController *)topViewControllerFromViewController:(UIViewController *)viewController {
if ([viewController isKindOfClass:[UINavigationController class]]) {
UINavigationController *navigationController = (UINavigationController *)viewController;
return [self
topViewControllerFromViewController:[navigationController.viewControllers lastObject]];
}
if ([viewController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tabController = (UITabBarController *)viewController;
return [self topViewControllerFromViewController:tabController.selectedViewController];
}
if (viewController.presentedViewController) {
return [self topViewControllerFromViewController:viewController.presentedViewController];
}
return viewController;
}
#endif
@end
| packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/FLTGoogleSignInPlugin.m/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_ios/darwin/Classes/FLTGoogleSignInPlugin.m",
"repo_id": "packages",
"token_count": 6380
} | 1,041 |
name: google_sign_in_ios
description: iOS implementation of the google_sign_in plugin.
repository: https://github.com/flutter/packages/tree/main/packages/google_sign_in/google_sign_in_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22
version: 5.7.4
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: google_sign_in
platforms:
ios:
dartPluginClass: GoogleSignInIOS
pluginClass: FLTGoogleSignInPlugin
sharedDarwinSource: true
macos:
dartPluginClass: GoogleSignInIOS
pluginClass: FLTGoogleSignInPlugin
sharedDarwinSource: true
dependencies:
flutter:
sdk: flutter
google_sign_in_platform_interface: ^2.2.0
dev_dependencies:
build_runner: ^2.4.6
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: 5.4.4
pigeon: ^11.0.1
topics:
- authentication
- google-sign-in
# The example deliberately includes limited-use secrets.
false_secrets:
- /darwin/Tests/GoogleService-Info.plist
- /darwin/Tests/GoogleSignInTests.m
- /example/ios/Runner/Info.plist
- /example/lib/main.dart
- /example/macos/Runner/Info.plist
| packages/packages/google_sign_in/google_sign_in_ios/pubspec.yaml/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_ios/pubspec.yaml",
"repo_id": "packages",
"token_count": 505
} | 1,042 |
// 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:google_sign_in_web/google_sign_in_web.dart';
/// Type of the onChange function for `ButtonConfiguration`.
typedef OnWebConfigChangeFn = void Function(GSIButtonConfiguration newConfig);
/// (Incomplete) List of the locales that can be used to configure the button.
const List<String> availableLocales = <String>[
'en_US',
'es_ES',
'pt_BR',
'fr_FR',
'it_IT',
'de_DE',
];
/// Renders a Scrollable Column widget that allows the user to see (and change) a ButtonConfiguration.
Widget renderWebButtonConfiguration(
GSIButtonConfiguration? currentConfig, {
OnWebConfigChangeFn? onChange,
}) {
final ScrollController scrollController = ScrollController();
return Scrollbar(
controller: scrollController,
thumbVisibility: true,
interactive: true,
child: SingleChildScrollView(
controller: scrollController,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_renderLocaleCard(
value: currentConfig?.locale,
locales: availableLocales,
onChanged: _onChanged<String>(currentConfig, onChange),
),
_renderMinimumWidthCard(
value: currentConfig?.minimumWidth,
max: 500,
actualMax: 400,
onChanged: _onChanged<double>(currentConfig, onChange),
),
_renderRadioListTileCard<GSIButtonType>(
title: 'ButtonType',
values: GSIButtonType.values,
selected: currentConfig?.type,
onChanged: _onChanged<GSIButtonType>(currentConfig, onChange),
),
_renderRadioListTileCard<GSIButtonShape>(
title: 'ButtonShape',
values: GSIButtonShape.values,
selected: currentConfig?.shape,
onChanged: _onChanged<GSIButtonShape>(currentConfig, onChange),
),
_renderRadioListTileCard<GSIButtonSize>(
title: 'ButtonSize',
values: GSIButtonSize.values,
selected: currentConfig?.size,
onChanged: _onChanged<GSIButtonSize>(currentConfig, onChange),
),
_renderRadioListTileCard<GSIButtonTheme>(
title: 'ButtonTheme',
values: GSIButtonTheme.values,
selected: currentConfig?.theme,
onChanged: _onChanged<GSIButtonTheme>(currentConfig, onChange),
),
_renderRadioListTileCard<GSIButtonText>(
title: 'ButtonText',
values: GSIButtonText.values,
selected: currentConfig?.text,
onChanged: _onChanged<GSIButtonText>(currentConfig, onChange),
),
_renderRadioListTileCard<GSIButtonLogoAlignment>(
title: 'ButtonLogoAlignment',
values: GSIButtonLogoAlignment.values,
selected: currentConfig?.logoAlignment,
onChanged:
_onChanged<GSIButtonLogoAlignment>(currentConfig, onChange),
),
],
)));
}
/// Renders a Config card with a dropdown of locales.
Widget _renderLocaleCard(
{String? value,
required List<String> locales,
void Function(String?)? onChanged}) {
return _renderConfigCard(title: 'locale', children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: DropdownButton<String>(
items: locales
.map((String locale) => DropdownMenuItem<String>(
value: locale,
child: Text(locale),
))
.toList(),
value: value,
onChanged: onChanged,
isExpanded: true,
// padding: const EdgeInsets.symmetric(horizontal: 16), // Prefer padding here!
),
),
]);
}
/// Renders a card with a slider
Widget _renderMinimumWidthCard(
{double? value,
double min = 0,
double actualMax = 10,
double max = 11,
void Function(double)? onChanged}) {
return _renderConfigCard(title: 'minimumWidth', children: <Widget>[
Slider(
label: value?.toString() ?? 'null',
value: value ?? 0,
min: min,
max: max,
secondaryTrackValue: actualMax,
onChanged: onChanged,
divisions: 10,
)
]);
}
/// Renders a Config Card with the values of an Enum as radio buttons.
Widget _renderRadioListTileCard<T extends Enum>(
{required String title,
required List<T> values,
T? selected,
void Function(T?)? onChanged}) {
return _renderConfigCard(
title: title,
children: values
.map((T value) => RadioListTile<T>(
value: value,
groupValue: selected,
onChanged: onChanged,
selected: value == selected,
title: Text(value.name),
dense: true,
))
.toList());
}
/// Renders a Card where we render some `children` that change config.
Widget _renderConfigCard(
{required String title, required List<Widget> children}) {
return Container(
constraints: const BoxConstraints(maxWidth: 200),
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text(
title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
dense: true,
),
...children,
],
)));
}
/// Sets a `value` into an `old` configuration object.
GSIButtonConfiguration _copyConfigWith(
GSIButtonConfiguration? old, Object? value) {
return GSIButtonConfiguration(
locale: value is String ? value : old?.locale,
minimumWidth:
value is double ? (value == 0 ? null : value) : old?.minimumWidth,
type: value is GSIButtonType ? value : old?.type,
theme: value is GSIButtonTheme ? value : old?.theme,
size: value is GSIButtonSize ? value : old?.size,
text: value is GSIButtonText ? value : old?.text,
shape: value is GSIButtonShape ? value : old?.shape,
logoAlignment: value is GSIButtonLogoAlignment ? value : old?.logoAlignment,
);
}
/// Returns a function that modifies the `current` configuration with a `value`, then calls `fn` with it.
void Function(T?)? _onChanged<T>(
GSIButtonConfiguration? current, OnWebConfigChangeFn? fn) {
if (fn == null) {
return null;
}
return (T? value) {
fn(_copyConfigWith(current, value));
};
}
| packages/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart",
"repo_id": "packages",
"token_count": 2983
} | 1,043 |
// 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:image_picker_example/readme_excerpts.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
ImagePickerPlatform.instance = FakeImagePicker();
});
test('sanity check readmePickExample', () async {
// Ensure that the snippet code runs successfully.
final List<XFile?> results = await readmePickExample();
// It should demonstrate a variety of calls.
expect(results.length, greaterThan(4));
// And the calls should all be different. This works since each fake call
// returns a different result.
expect(results.map((XFile? file) => file?.path).toSet().length,
results.length);
});
test('sanity check getLostData', () async {
// Ensure that the snippet code runs successfully.
await getLostData();
});
}
class FakeImagePicker extends ImagePickerPlatform {
@override
Future<XFile?> getImageFromSource(
{required ImageSource source,
ImagePickerOptions options = const ImagePickerOptions()}) async {
return XFile(source == ImageSource.camera ? 'cameraImage' : 'galleryImage');
}
@override
Future<LostDataResponse> getLostData() async {
return LostDataResponse.empty();
}
@override
Future<List<XFile>> getMultiImageWithOptions(
{MultiImagePickerOptions options =
const MultiImagePickerOptions()}) async {
return <XFile>[XFile('multiImage')];
}
@override
Future<List<XFile>> getMedia({required MediaOptions options}) async {
return options.allowMultiple
? <XFile>[XFile('medias'), XFile('medias')]
: <XFile>[XFile('media')];
}
@override
Future<XFile?> getVideo(
{required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration}) async {
return XFile(source == ImageSource.camera ? 'cameraVideo' : 'galleryVideo');
}
}
| packages/packages/image_picker/image_picker/example/test/readme_excerpts_test.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker/example/test/readme_excerpts_test.dart",
"repo_id": "packages",
"token_count": 710
} | 1,044 |
## For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
#
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx1024m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
#
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
#Fri Jan 27 08:52:19 CST 2023
org.gradle.jvmargs=-Xmx1536M -Dkotlin.daemon.jvm.options\="-Xmx1536M"
| packages/packages/image_picker/image_picker_android/android/gradle.properties/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/gradle.properties",
"repo_id": "packages",
"token_count": 263
} | 1,045 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.imagepicker;
import static io.flutter.plugins.imagepicker.ImagePickerCache.SHARED_PREFERENCES_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ImagePickerCacheTest {
@Mock Activity mockActivity;
@Mock SharedPreferences mockPreference;
@Mock SharedPreferences.Editor mockEditor;
static Map<String, Object> preferenceStorage;
AutoCloseable mockCloseable;
@Before
public void setUp() {
mockCloseable = MockitoAnnotations.openMocks(this);
preferenceStorage = new HashMap<String, Object>();
when(mockActivity.getPackageName()).thenReturn("com.example.test");
when(mockActivity.getPackageManager()).thenReturn(mock(PackageManager.class));
when(mockActivity.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE))
.thenReturn(mockPreference);
when(mockPreference.edit()).thenReturn(mockEditor);
when(mockEditor.putInt(any(String.class), any(int.class)))
.then(
i -> {
preferenceStorage.put(i.getArgument(0), i.getArgument(1));
return mockEditor;
});
when(mockEditor.putLong(any(String.class), any(long.class)))
.then(
i -> {
preferenceStorage.put(i.getArgument(0), i.getArgument(1));
return mockEditor;
});
when(mockEditor.putString(any(String.class), any(String.class)))
.then(
i -> {
preferenceStorage.put(i.getArgument(0), i.getArgument(1));
return mockEditor;
});
when(mockPreference.getInt(any(String.class), any(int.class)))
.then(
i -> {
int result =
(int)
((preferenceStorage.get(i.getArgument(0)) != null)
? preferenceStorage.get(i.getArgument(0))
: i.getArgument(1));
return result;
});
when(mockPreference.getLong(any(String.class), any(long.class)))
.then(
i -> {
long result =
(long)
((preferenceStorage.get(i.getArgument(0)) != null)
? preferenceStorage.get(i.getArgument(0))
: i.getArgument(1));
return result;
});
when(mockPreference.getString(any(String.class), any(String.class)))
.then(
i -> {
String result =
(String)
((preferenceStorage.get(i.getArgument(0)) != null)
? preferenceStorage.get(i.getArgument(0))
: i.getArgument(1));
return result;
});
when(mockPreference.contains(any(String.class))).thenReturn(true);
}
@After
public void tearDown() throws Exception {
mockCloseable.close();
}
@Test
public void imageCache_shouldBeAbleToSetAndGetQuality() {
final int quality = 90;
ImagePickerCache cache = new ImagePickerCache(mockActivity);
cache.saveDimensionWithOutputOptions(
new Messages.ImageSelectionOptions.Builder().setQuality((long) quality).build());
Map<String, Object> resultMap = cache.getCacheMap();
int imageQuality = (int) resultMap.get(ImagePickerCache.MAP_KEY_IMAGE_QUALITY);
assertThat(imageQuality, equalTo(quality));
cache.saveDimensionWithOutputOptions(
new Messages.ImageSelectionOptions.Builder().setQuality((long) 100).build());
Map<String, Object> resultMapWithDefaultQuality = cache.getCacheMap();
int defaultImageQuality =
(int) resultMapWithDefaultQuality.get(ImagePickerCache.MAP_KEY_IMAGE_QUALITY);
assertThat(defaultImageQuality, equalTo(100));
}
@Test
public void imageCache_shouldNotThrowIfPathIsNullInSaveResult() {
final ImagePickerCache cache = new ImagePickerCache(mockActivity);
cache.saveResult(null, "errorCode", "errorMessage");
assertTrue(
"No exception thrown when ImagePickerCache.saveResult() was passed a null path", true);
}
}
| packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerCacheTest.java/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerCacheTest.java",
"repo_id": "packages",
"token_count": 2024
} | 1,046 |
## 0.8.9+2
* Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6.
* Replaces deprecated UIGraphicsBeginImageContextWithOptions with UIGraphicsImageRenderer.
## 0.8.9+1
* Adds privacy manifest.
## 0.8.9
* Fixes resizing bug and updates rounding to be more accurate.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 0.8.8+4
* Updates to Pigeon 13.
## 0.8.8+3
* Fixes a possible crash when calling a picker method while another is waiting on permissions.
## 0.8.8+2
* Adds pub topics to package metadata.
## 0.8.8+1
* Fixes exception when canceling pickMultipleMedia.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.8.8
* Adds `getMedia` and `getMultipleMedia` methods.
## 0.8.7+4
* Fixes `BuildContext` handling in example.
* Updates metadata unit test to work on iOS 16.2.
## 0.8.7+3
* Updates pigeon to fix warnings with clang 15.
* Updates minimum Flutter version to 3.3.
## 0.8.7+2
* Updates to `pigeon` version 9.
## 0.8.7+1
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
## 0.8.7
* Updates minimum Flutter version to 3.3 and iOS 11.
## 0.8.6+9
* Updates links for the merge of flutter/plugins into flutter/packages.
## 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.
| packages/packages/image_picker/image_picker_ios/CHANGELOG.md/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1017
} | 1,047 |
// 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 (v13.0.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "messages.g.h"
#if TARGET_OS_OSX
#import <FlutterMacOS/FlutterMacOS.h>
#else
#import <Flutter/Flutter.h>
#endif
#if !__has_feature(objc_arc)
#error File requires ARC to be enabled.
#endif
@implementation FLTSourceCameraBox
- (instancetype)initWithValue:(FLTSourceCamera)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
@implementation FLTSourceTypeBox
- (instancetype)initWithValue:(FLTSourceType)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
static NSArray *wrapResult(id result, FlutterError *error) {
if (error) {
return @[
error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null]
];
}
return @[ result ?: [NSNull null] ];
}
static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) {
id result = array[key];
return (result == [NSNull null]) ? nil : result;
}
@interface FLTMaxSize ()
+ (FLTMaxSize *)fromList:(NSArray *)list;
+ (nullable FLTMaxSize *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FLTMediaSelectionOptions ()
+ (FLTMediaSelectionOptions *)fromList:(NSArray *)list;
+ (nullable FLTMediaSelectionOptions *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FLTSourceSpecification ()
+ (FLTSourceSpecification *)fromList:(NSArray *)list;
+ (nullable FLTSourceSpecification *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@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 *)fromList:(NSArray *)list {
FLTMaxSize *pigeonResult = [[FLTMaxSize alloc] init];
pigeonResult.width = GetNullableObjectAtIndex(list, 0);
pigeonResult.height = GetNullableObjectAtIndex(list, 1);
return pigeonResult;
}
+ (nullable FLTMaxSize *)nullableFromList:(NSArray *)list {
return (list) ? [FLTMaxSize fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.width ?: [NSNull null],
self.height ?: [NSNull null],
];
}
@end
@implementation FLTMediaSelectionOptions
+ (instancetype)makeWithMaxSize:(FLTMaxSize *)maxSize
imageQuality:(nullable NSNumber *)imageQuality
requestFullMetadata:(BOOL)requestFullMetadata
allowMultiple:(BOOL)allowMultiple {
FLTMediaSelectionOptions *pigeonResult = [[FLTMediaSelectionOptions alloc] init];
pigeonResult.maxSize = maxSize;
pigeonResult.imageQuality = imageQuality;
pigeonResult.requestFullMetadata = requestFullMetadata;
pigeonResult.allowMultiple = allowMultiple;
return pigeonResult;
}
+ (FLTMediaSelectionOptions *)fromList:(NSArray *)list {
FLTMediaSelectionOptions *pigeonResult = [[FLTMediaSelectionOptions alloc] init];
pigeonResult.maxSize = [FLTMaxSize nullableFromList:(GetNullableObjectAtIndex(list, 0))];
pigeonResult.imageQuality = GetNullableObjectAtIndex(list, 1);
pigeonResult.requestFullMetadata = [GetNullableObjectAtIndex(list, 2) boolValue];
pigeonResult.allowMultiple = [GetNullableObjectAtIndex(list, 3) boolValue];
return pigeonResult;
}
+ (nullable FLTMediaSelectionOptions *)nullableFromList:(NSArray *)list {
return (list) ? [FLTMediaSelectionOptions fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.maxSize ? [self.maxSize toList] : [NSNull null]),
self.imageQuality ?: [NSNull null],
@(self.requestFullMetadata),
@(self.allowMultiple),
];
}
@end
@implementation FLTSourceSpecification
+ (instancetype)makeWithType:(FLTSourceType)type camera:(FLTSourceCamera)camera {
FLTSourceSpecification *pigeonResult = [[FLTSourceSpecification alloc] init];
pigeonResult.type = type;
pigeonResult.camera = camera;
return pigeonResult;
}
+ (FLTSourceSpecification *)fromList:(NSArray *)list {
FLTSourceSpecification *pigeonResult = [[FLTSourceSpecification alloc] init];
pigeonResult.type = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.camera = [GetNullableObjectAtIndex(list, 1) integerValue];
return pigeonResult;
}
+ (nullable FLTSourceSpecification *)nullableFromList:(NSArray *)list {
return (list) ? [FLTSourceSpecification fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.type),
@(self.camera),
];
}
@end
@interface FLTImagePickerApiCodecReader : FlutterStandardReader
@end
@implementation FLTImagePickerApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FLTMaxSize fromList:[self readValue]];
case 129:
return [FLTMediaSelectionOptions fromList:[self readValue]];
case 130:
return [FLTSourceSpecification fromList:[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 toList]];
} else if ([value isKindOfClass:[FLTMediaSelectionOptions class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FLTSourceSpecification class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} 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(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FLTImagePickerApiCodecReaderWriter *readerWriter =
[[FLTImagePickerApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFLTImagePickerApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FLTImagePickerApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.image_picker_ios.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);
BOOL arg_requestFullMetadata = [GetNullableObjectAtIndex(args, 3) boolValue];
[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.image_picker_ios.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);
BOOL arg_requestFullMetadata = [GetNullableObjectAtIndex(args, 2) boolValue];
[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.image_picker_ios.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];
}
}
/// Selects images and videos and returns their paths.
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMedia"
binaryMessenger:binaryMessenger
codec:FLTImagePickerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(pickMediaWithMediaSelectionOptions:completion:)],
@"FLTImagePickerApi api (%@) doesn't respond to "
@"@selector(pickMediaWithMediaSelectionOptions:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FLTMediaSelectionOptions *arg_mediaSelectionOptions = GetNullableObjectAtIndex(args, 0);
[api pickMediaWithMediaSelectionOptions:arg_mediaSelectionOptions
completion:^(NSArray<NSString *> *_Nullable output,
FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
}
| packages/packages/image_picker/image_picker_ios/ios/Classes/messages.g.m/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/messages.g.m",
"repo_id": "packages",
"token_count": 4830
} | 1,048 |
// 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:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker_macos/image_picker_macos.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'image_picker_macos_test.mocks.dart';
@GenerateMocks(<Type>[FileSelectorPlatform])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Returns the captured type groups from a mock call result, assuming that
// exactly one call was made and only the type groups were captured.
List<XTypeGroup> capturedTypeGroups(VerificationResult result) {
return result.captured.single as List<XTypeGroup>;
}
late ImagePickerMacOS plugin;
late MockFileSelectorPlatform mockFileSelectorPlatform;
setUp(() {
plugin = ImagePickerMacOS();
mockFileSelectorPlatform = MockFileSelectorPlatform();
when(mockFileSelectorPlatform.openFile(
acceptedTypeGroups: anyNamed('acceptedTypeGroups')))
.thenAnswer((_) async => null);
when(mockFileSelectorPlatform.openFiles(
acceptedTypeGroups: anyNamed('acceptedTypeGroups')))
.thenAnswer((_) async => List<XFile>.empty());
ImagePickerMacOS.fileSelector = mockFileSelectorPlatform;
});
test('registered instance', () {
ImagePickerMacOS.registerWith();
expect(ImagePickerPlatform.instance, isA<ImagePickerMacOS>());
});
group('images', () {
test('pickImage passes the accepted type groups correctly', () async {
await plugin.pickImage(source: ImageSource.gallery);
final VerificationResult result = verify(mockFileSelectorPlatform
.openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups')));
expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers,
<String>['public.image']);
});
test('getImage passes the accepted type groups correctly', () async {
await plugin.getImage(source: ImageSource.gallery);
final VerificationResult result = verify(mockFileSelectorPlatform
.openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups')));
expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers,
<String>['public.image']);
});
test('getImageFromSource passes the accepted type groups correctly',
() async {
await plugin.getImageFromSource(source: ImageSource.gallery);
final VerificationResult result = verify(mockFileSelectorPlatform
.openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups')));
expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers,
<String>['public.image']);
});
test('getImageFromSource calls delegate when source is camera', () async {
const String fakePath = '/tmp/foo';
plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath));
expect(
(await plugin.getImageFromSource(source: ImageSource.camera))!.path,
fakePath);
});
test(
'getImageFromSource throws StateError when source is camera with no delegate',
() async {
await expectLater(plugin.getImageFromSource(source: ImageSource.camera),
throwsStateError);
});
test('getMultiImage passes the accepted type groups correctly', () async {
await plugin.getMultiImage();
final VerificationResult result = verify(
mockFileSelectorPlatform.openFiles(
acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups')));
expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers,
<String>['public.image']);
});
});
group('videos', () {
test('pickVideo passes the accepted type groups correctly', () async {
await plugin.pickVideo(source: ImageSource.gallery);
final VerificationResult result = verify(mockFileSelectorPlatform
.openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups')));
expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers,
<String>['public.movie']);
});
test('getVideo passes the accepted type groups correctly', () async {
await plugin.getVideo(source: ImageSource.gallery);
final VerificationResult result = verify(mockFileSelectorPlatform
.openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups')));
expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers,
<String>['public.movie']);
});
test('getVideo calls delegate when source is camera', () async {
const String fakePath = '/tmp/foo';
plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath));
expect(
(await plugin.getVideo(source: ImageSource.camera))!.path, fakePath);
});
test('getVideo throws StateError when source is camera with no delegate',
() async {
await expectLater(
plugin.getVideo(source: ImageSource.camera), throwsStateError);
});
});
group('media', () {
test('getMedia passes the accepted type groups correctly', () async {
await plugin.getMedia(options: const MediaOptions(allowMultiple: true));
final VerificationResult result = verify(
mockFileSelectorPlatform.openFiles(
acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups')));
expect(capturedTypeGroups(result)[0].extensions,
<String>['public.image', 'public.movie']);
});
test('multiple media handles an empty path response gracefully', () async {
expect(
await plugin.getMedia(
options: const MediaOptions(
allowMultiple: true,
),
),
<String>[]);
});
test('single media handles an empty path response gracefully', () async {
expect(
await plugin.getMedia(
options: const MediaOptions(
allowMultiple: false,
),
),
<String>[]);
});
});
}
class FakeCameraDelegate extends ImagePickerCameraDelegate {
FakeCameraDelegate({this.result});
XFile? result;
@override
Future<XFile?> takePhoto(
{ImagePickerCameraDelegateOptions options =
const ImagePickerCameraDelegateOptions()}) async {
return result;
}
@override
Future<XFile?> takeVideo(
{ImagePickerCameraDelegateOptions options =
const ImagePickerCameraDelegateOptions()}) async {
return result;
}
}
| packages/packages/image_picker/image_picker_macos/test/image_picker_macos_test.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_macos/test/image_picker_macos_test.dart",
"repo_id": "packages",
"token_count": 2379
} | 1,049 |
// 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 'image_options.dart';
/// Specifies options for picking multiple images from the device's gallery.
class MultiImagePickerOptions {
/// Creates an instance with the given [imageOptions].
const MultiImagePickerOptions({
this.imageOptions = const ImageOptions(),
});
/// The image-specific options for picking.
final ImageOptions imageOptions;
}
| packages/packages/image_picker/image_picker_platform_interface/lib/src/types/multi_image_picker_options.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/multi_image_picker_options.dart",
"repo_id": "packages",
"token_count": 136
} | 1,050 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 0.2.1+1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 0.2.1
* Adds `getMedia` method.
## 0.2.0
* Updates minimum Flutter version to 3.3.
## 0.1.0+6
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
## 0.1.0+5
* Updates links for the merge of flutter/plugins into flutter/packages.
## 0.1.0+4
* Updates example code for `use_build_context_synchronously` lint.
* Updates minimum Flutter version to 3.0.
## 0.1.0+3
* Changes XTypeGroup initialization from final to const.
* Updates minimum Flutter version to 2.10.
## 0.1.0+2
* Minor fixes for new analysis options.
## 0.1.0+1
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.1.0
* Initial Windows support.
| packages/packages/image_picker/image_picker_windows/CHANGELOG.md/0 | {
"file_path": "packages/packages/image_picker/image_picker_windows/CHANGELOG.md",
"repo_id": "packages",
"token_count": 336
} | 1,051 |
name: in_app_purchase
description: A Flutter plugin for in-app purchases. Exposes APIs for making in-app purchases through the App Store and Google Play.
repository: https://github.com/flutter/packages/tree/main/packages/in_app_purchase/in_app_purchase
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22
version: 3.1.13
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
platforms:
android:
default_package: in_app_purchase_android
ios:
default_package: in_app_purchase_storekit
macos:
default_package: in_app_purchase_storekit
dependencies:
flutter:
sdk: flutter
in_app_purchase_android: ^0.3.0
in_app_purchase_platform_interface: ^1.0.0
in_app_purchase_storekit: ^0.3.4
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
plugin_platform_interface: ^2.1.7
test: ^1.16.0
topics:
- in-app-purchase
- payment
screenshots:
- description: 'Example of in-app purchase on ios'
path: doc/iap_ios.gif
- description: 'Example of in-app purchase on android'
path: doc/iap_android.gif
| packages/packages/in_app_purchase/in_app_purchase/pubspec.yaml/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase/pubspec.yaml",
"repo_id": "packages",
"token_count": 484
} | 1,052 |
// 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 android.util;
public class Log {
public static int d(String tag, String msg) {
System.out.println("DEBUG: " + tag + ": " + msg);
return 0;
}
public static int i(String tag, String msg) {
System.out.println("INFO: " + tag + ": " + msg);
return 0;
}
public static int w(String tag, String msg) {
System.out.println("WARN: " + tag + ": " + msg);
return 0;
}
public static int e(String tag, String msg) {
System.out.println("ERROR: " + tag + ": " + msg);
return 0;
}
}
| packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/android/util/Log.java/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/android/util/Log.java",
"repo_id": "packages",
"token_count": 240
} | 1,053 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'product_wrapper.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ProductWrapper _$ProductWrapperFromJson(Map json) => ProductWrapper(
productId: json['productId'] as String? ?? '',
productType: $enumDecode(_$ProductTypeEnumMap, json['productType']),
);
Map<String, dynamic> _$ProductWrapperToJson(ProductWrapper instance) =>
<String, dynamic>{
'productId': instance.productId,
'productType': _$ProductTypeEnumMap[instance.productType]!,
};
const _$ProductTypeEnumMap = {
ProductType.inapp: 'inapp',
ProductType.subs: 'subs',
};
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_wrapper.g.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_wrapper.g.dart",
"repo_id": "packages",
"token_count": 237
} | 1,054 |
// 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 '../../billing_client_wrappers.dart';
import 'google_play_user_choice_details.dart';
/// Class used to convert cross process object into api expose objects.
class Translator {
Translator._();
/// Converts from [UserChoiceDetailsWrapper] to [GooglePlayUserChoiceDetails].
static GooglePlayUserChoiceDetails convertToUserChoiceDetails(
UserChoiceDetailsWrapper detailsWrapper) {
return GooglePlayUserChoiceDetails(
originalExternalTransactionId:
detailsWrapper.originalExternalTransactionId,
externalTransactionToken: detailsWrapper.externalTransactionToken,
products: detailsWrapper.products
.map((UserChoiceDetailsProductWrapper e) =>
convertToUserChoiceDetailsProduct(e))
.toList());
}
/// Converts from [UserChoiceDetailsProductWrapper] to [GooglePlayUserChoiceDetailsProduct].
@visibleForTesting
static GooglePlayUserChoiceDetailsProduct convertToUserChoiceDetailsProduct(
UserChoiceDetailsProductWrapper productWrapper) {
return GooglePlayUserChoiceDetailsProduct(
id: productWrapper.id,
offerToken: productWrapper.offerToken,
productType: convertToPlayProductType(productWrapper.productType));
}
/// Coverts from [ProductType] to [GooglePlayProductType].
@visibleForTesting
static GooglePlayProductType convertToPlayProductType(ProductType type) {
switch (type) {
case ProductType.inapp:
return GooglePlayProductType.inapp;
case ProductType.subs:
return GooglePlayProductType.subs;
}
}
}
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/translator.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/translator.dart",
"repo_id": "packages",
"token_count": 568
} | 1,055 |
{
"identifier" : "6073E9A3",
"nonRenewingSubscriptions" : [
],
"products" : [
{
"displayPrice" : "0.99",
"familyShareable" : false,
"internalID" : "AE10D05D",
"localizations" : [
{
"description" : "A consumable product.",
"displayName" : "Consumable",
"locale" : "en_US"
}
],
"productID" : "consumable",
"referenceName" : "consumable",
"type" : "Consumable"
},
{
"displayPrice" : "10.99",
"familyShareable" : false,
"internalID" : "FABCF067",
"localizations" : [
{
"description" : "An non-consumable product.",
"displayName" : "Upgrade",
"locale" : "en_US"
}
],
"productID" : "upgrade",
"referenceName" : "upgrade",
"type" : "NonConsumable"
}
],
"settings" : {
"_failTransactionsEnabled" : false,
"_locale" : "en_US",
"_storefront" : "USA",
"_storeKitErrors" : [
{
"current" : null,
"enabled" : false,
"name" : "Load Products"
},
{
"current" : null,
"enabled" : false,
"name" : "Purchase"
},
{
"current" : null,
"enabled" : false,
"name" : "Verification"
},
{
"current" : null,
"enabled" : false,
"name" : "App Store Sync"
},
{
"current" : null,
"enabled" : false,
"name" : "Subscription Status"
},
{
"current" : null,
"enabled" : false,
"name" : "App Transaction"
},
{
"current" : null,
"enabled" : false,
"name" : "Manage Subscriptions Sheet"
},
{
"current" : null,
"enabled" : false,
"name" : "Refund Request Sheet"
},
{
"current" : null,
"enabled" : false,
"name" : "Offer Code Redeem Sheet"
}
]
},
"subscriptionGroups" : [
{
"id" : "D0FEE8D8",
"localizations" : [
],
"name" : "Example Subscriptions",
"subscriptions" : [
{
"adHocOffers" : [
],
"codeOffers" : [
],
"displayPrice" : "4.99",
"familyShareable" : false,
"groupNumber" : 1,
"internalID" : "922EB597",
"introductoryOffer" : null,
"localizations" : [
{
"description" : "A lower level subscription.",
"displayName" : "Subscription Silver",
"locale" : "en_US"
}
],
"productID" : "subscription_silver",
"recurringSubscriptionPeriod" : "P1W",
"referenceName" : "subscription_silver",
"subscriptionGroupID" : "D0FEE8D8",
"type" : "RecurringSubscription"
},
{
"adHocOffers" : [
],
"codeOffers" : [
],
"displayPrice" : "5.99",
"familyShareable" : false,
"groupNumber" : 2,
"internalID" : "0BC7FF5E",
"introductoryOffer" : null,
"localizations" : [
{
"description" : "A higher level subscription.",
"displayName" : "Subscription Gold",
"locale" : "en_US"
}
],
"productID" : "subscription_gold",
"recurringSubscriptionPeriod" : "P1M",
"referenceName" : "subscription_gold",
"subscriptionGroupID" : "D0FEE8D8",
"type" : "RecurringSubscription"
}
]
}
],
"version" : {
"major" : 3,
"minor" : 0
}
}
| packages/packages/in_app_purchase/in_app_purchase_storekit/example/ios/Runner/Configuration.storekit/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/ios/Runner/Configuration.storekit",
"repo_id": "packages",
"token_count": 1993
} | 1,056 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
@import in_app_purchase_storekit;
NS_ASSUME_NONNULL_BEGIN
API_AVAILABLE(ios(11.2), macos(10.13.2))
@interface SKProductSubscriptionPeriodStub : SKProductSubscriptionPeriod
- (instancetype)initWithMap:(NSDictionary *)map;
@end
API_AVAILABLE(ios(11.2), macos(10.13.2))
@interface SKProductDiscountStub : SKProductDiscount
- (instancetype)initWithMap:(NSDictionary *)map;
@end
@interface SKProductStub : SKProduct
- (instancetype)initWithMap:(NSDictionary *)map;
@end
@interface SKProductRequestStub : SKProductsRequest
@property(assign, nonatomic) BOOL returnError;
- (instancetype)initWithProductIdentifiers:(NSSet<NSString *> *)productIdentifiers;
- (instancetype)initWithFailureError:(NSError *)error;
@end
@interface SKProductsResponseStub : SKProductsResponse
- (instancetype)initWithMap:(NSDictionary *)map;
@end
@interface InAppPurchasePluginStub : InAppPurchasePlugin
@end
@interface SKRequestStub : SKRequest
@end
@interface SKPaymentQueueStub : SKPaymentQueue
@property(assign, nonatomic) SKPaymentTransactionState testState;
@property(strong, nonatomic, nullable) id<SKPaymentTransactionObserver> observer;
@end
@interface SKPaymentTransactionStub : SKPaymentTransaction
- (instancetype)initWithMap:(NSDictionary *)map;
- (instancetype)initWithState:(SKPaymentTransactionState)state;
- (instancetype)initWithState:(SKPaymentTransactionState)state payment:(SKPayment *)payment;
@end
@interface SKMutablePaymentStub : SKMutablePayment
- (instancetype)initWithMap:(NSDictionary *)map;
@end
@interface NSErrorStub : NSError
- (instancetype)initWithMap:(NSDictionary *)map;
@end
@interface FIAPReceiptManagerStub : FIAPReceiptManager
// Indicates whether getReceiptData of this stub is going to return an error.
// Setting this to true will let getReceiptData give a basic NSError and return nil.
@property(assign, nonatomic) BOOL returnError;
@end
@interface SKReceiptRefreshRequestStub : SKReceiptRefreshRequest
- (instancetype)initWithFailureError:(NSError *)error;
@end
API_AVAILABLE(ios(13.0), macos(10.15))
@interface SKStorefrontStub : SKStorefront
- (instancetype)initWithMap:(NSDictionary *)map;
@end
NS_ASSUME_NONNULL_END
| packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/Stubs.h/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/Stubs.h",
"repo_id": "packages",
"token_count": 798
} | 1,057 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'sk_payment_transaction_wrappers.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SKPaymentTransactionWrapper _$SKPaymentTransactionWrapperFromJson(Map json) =>
SKPaymentTransactionWrapper(
payment: SKPaymentWrapper.fromJson(
Map<String, dynamic>.from(json['payment'] as Map)),
transactionState: const SKTransactionStatusConverter()
.fromJson(json['transactionState'] as int?),
originalTransaction: json['originalTransaction'] == null
? null
: SKPaymentTransactionWrapper.fromJson(
Map<String, dynamic>.from(json['originalTransaction'] as Map)),
transactionTimeStamp: (json['transactionTimeStamp'] as num?)?.toDouble(),
transactionIdentifier: json['transactionIdentifier'] as String?,
error: json['error'] == null
? null
: SKError.fromJson(Map<String, dynamic>.from(json['error'] as Map)),
);
Map<String, dynamic> _$SKPaymentTransactionWrapperToJson(
SKPaymentTransactionWrapper instance) =>
<String, dynamic>{
'transactionState': const SKTransactionStatusConverter()
.toJson(instance.transactionState),
'payment': instance.payment,
'originalTransaction': instance.originalTransaction,
'transactionTimeStamp': instance.transactionTimeStamp,
'transactionIdentifier': instance.transactionIdentifier,
'error': instance.error,
};
| packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart",
"repo_id": "packages",
"token_count": 540
} | 1,058 |
// 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:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'fakes/fake_storekit_platform.dart';
import 'test_api.g.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform();
setUpAll(() {
TestInAppPurchaseApi.setup(fakeStoreKitPlatform);
});
group('present code redemption sheet', () {
test('null', () async {
expect(
InAppPurchaseStoreKitPlatformAddition().presentCodeRedemptionSheet(),
completes);
});
});
group('refresh receipt data', () {
test('should refresh receipt data', () async {
final PurchaseVerificationData? receiptData =
await InAppPurchaseStoreKitPlatformAddition()
.refreshPurchaseVerificationData();
expect(receiptData, isNotNull);
expect(receiptData!.source, kIAPSource);
expect(receiptData.localVerificationData, 'refreshed receipt data');
expect(receiptData.serverVerificationData, 'refreshed receipt data');
});
});
}
| packages/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart",
"repo_id": "packages",
"token_count": 469
} | 1,059 |
// 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
@testable import ios_platform_images
class IosPlatformImagesTests: XCTestCase {
let plugin = IosPlatformImagesPlugin()
func testLoadImage() {
let assetName = "flutter"
let imageData = plugin.loadImage(name: assetName)
XCTAssertNotNil(imageData)
XCTAssertNotNil(imageData?.data)
}
func testLoadImageNotFound() {
let assetName = "notFound"
let imageData = plugin.loadImage(name: assetName)
XCTAssertNil(imageData)
}
func testResolveURL() {
let resourceName = "textfile"
do {
let url = try plugin.resolveUrl(resourceName: resourceName, extension: nil)
XCTAssertNotNil(url)
XCTAssertTrue(url?.contains(resourceName) ?? false)
} catch {
XCTFail("Error while resolving URL: \(error)")
}
}
func testResolveURLNotFound() {
do {
let url = try plugin.resolveUrl(resourceName: "notFound", extension: nil)
XCTAssertNil(url)
} catch {
XCTFail("Error while resolving URL: \(error)")
}
}
}
| packages/packages/ios_platform_images/example/ios/RunnerTests/IosPlatformImagesTests.swift/0 | {
"file_path": "packages/packages/ios_platform_images/example/ios/RunnerTests/IosPlatformImagesTests.swift",
"repo_id": "packages",
"token_count": 443
} | 1,060 |
name: ios_platform_images
description: A plugin to share images between Flutter and iOS in add-to-app setups.
repository: https://github.com/flutter/packages/tree/main/packages/ios_platform_images
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+ios_platform_images%22
version: 0.2.3+2
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
platforms:
ios:
pluginClass: IosPlatformImagesPlugin
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
pigeon: ^11.0.0
topics:
- image
- assets
| packages/packages/ios_platform_images/pubspec.yaml/0 | {
"file_path": "packages/packages/ios_platform_images/pubspec.yaml",
"repo_id": "packages",
"token_count": 253
} | 1,061 |
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
namespace 'io.flutter.plugins.localauthexample'
compileSdk flutter.compileSdkVersion
defaultConfig {
applicationId "io.flutter.plugins.localauthexample"
minSdkVersion flutter.minSdkVersion
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
signingConfig signingConfigs.debug
}
}
lint {
disable 'InvalidPackage'
}
}
flutter {
source '../..'
}
dependencies {
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
| packages/packages/local_auth/local_auth_android/example/android/app/build.gradle/0 | {
"file_path": "packages/packages/local_auth/local_auth_android/example/android/app/build.gradle",
"repo_id": "packages",
"token_count": 619
} | 1,062 |
// 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:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
objcHeaderOut: 'darwin/Classes/messages.g.h',
objcSourceOut: 'darwin/Classes/messages.g.m',
objcOptions: ObjcOptions(
prefix: 'FLAD', // Avoid runtime collisions with old local_auth_ios classes.
),
copyrightHeader: 'pigeons/copyright.txt',
))
/// Pigeon version of IOSAuthMessages, plus the authorization reason.
///
/// See auth_messages_ios.dart for details.
class AuthStrings {
/// Constructs a new instance.
const AuthStrings({
required this.reason,
required this.lockOut,
required this.goToSettingsButton,
required this.goToSettingsDescription,
required this.cancelButton,
required this.localizedFallbackTitle,
});
final String reason;
final String lockOut;
final String goToSettingsButton;
final String goToSettingsDescription;
final String cancelButton;
final String? localizedFallbackTitle;
}
/// Possible outcomes of an authentication attempt.
enum AuthResult {
/// The user authenticated successfully.
success,
/// The user failed to successfully authenticate.
failure,
/// The authentication system was not available.
errorNotAvailable,
/// No biometrics are enrolled.
errorNotEnrolled,
/// No passcode is set.
errorPasscodeNotSet,
}
class AuthOptions {
AuthOptions(
{required this.biometricOnly,
required this.sticky,
required this.useErrorDialogs});
final bool biometricOnly;
final bool sticky;
final bool useErrorDialogs;
}
class AuthResultDetails {
AuthResultDetails(
{required this.result, this.errorMessage, this.errorDetails});
/// The result of authenticating.
final AuthResult result;
/// A system-provided error message, if any.
final String? errorMessage;
/// System-provided error details, if any.
// TODO(stuartmorgan): Remove this when standardizing errors plugin-wide in
// a breaking change. This is here only to preserve the existing error format
// exactly for compatibility, in case clients were checking PlatformException
// details.
final String? errorDetails;
}
/// Pigeon equivalent of the subset of BiometricType used by iOS.
enum AuthBiometric { face, fingerprint }
// TODO(stuartmorgan): Enums need be wrapped in a data class because thay can't
// be used as collection arguments. See https://github.com/flutter/flutter/issues/133728
class AuthBiometricWrapper {
AuthBiometricWrapper({required this.value});
final AuthBiometric value;
}
@HostApi()
abstract class LocalAuthApi {
/// Returns true if this device supports authentication.
bool isDeviceSupported();
/// Returns true if this device can support biometric authentication, whether
/// any biometrics are enrolled or not.
bool deviceCanSupportBiometrics();
/// Returns the biometric types that are enrolled, and can thus be used
/// without additional setup.
List<AuthBiometricWrapper> getEnrolledBiometrics();
/// Attempts to authenticate the user with the provided [options], and using
/// [strings] for any UI.
@async
@ObjCSelector('authenticateWithOptions:strings:')
AuthResultDetails authenticate(AuthOptions options, AuthStrings strings);
}
| packages/packages/local_auth/local_auth_darwin/pigeons/messages.dart/0 | {
"file_path": "packages/packages/local_auth/local_auth_darwin/pigeons/messages.dart",
"repo_id": "packages",
"token_count": 974
} | 1,063 |
name: local_auth_windows
description: Windows implementation of the local_auth plugin.
repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth_windows
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22
version: 1.0.10
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: local_auth
platforms:
windows:
pluginClass: LocalAuthPlugin
dartPluginClass: LocalAuthWindows
dependencies:
flutter:
sdk: flutter
local_auth_platform_interface: ^1.0.1
dev_dependencies:
flutter_test:
sdk: flutter
pigeon: ^10.1.2
topics:
- authentication
- biometrics
- local-auth
| packages/packages/local_auth/local_auth_windows/pubspec.yaml/0 | {
"file_path": "packages/packages/local_auth/local_auth_windows/pubspec.yaml",
"repo_id": "packages",
"token_count": 288
} | 1,064 |
test_on: vm
| packages/packages/metrics_center/dart_test.yaml/0 | {
"file_path": "packages/packages/metrics_center/dart_test.yaml",
"repo_id": "packages",
"token_count": 6
} | 1,065 |
// Mocks generated by Mockito 5.4.4 from annotations
// in metrics_center/test/skiaperf_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i2;
import 'package:gcloud/common.dart' as _i4;
import 'package:gcloud/storage.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i5;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeStreamSink_0<S> extends _i1.SmartFake implements _i2.StreamSink<S> {
_FakeStreamSink_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeObjectInfo_1 extends _i1.SmartFake implements _i3.ObjectInfo {
_FakeObjectInfo_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePage_2<T> extends _i1.SmartFake implements _i4.Page<T> {
_FakePage_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeDateTime_3 extends _i1.SmartFake implements DateTime {
_FakeDateTime_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeUri_4 extends _i1.SmartFake implements Uri {
_FakeUri_4(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeObjectGeneration_5 extends _i1.SmartFake
implements _i3.ObjectGeneration {
_FakeObjectGeneration_5(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeObjectMetadata_6 extends _i1.SmartFake
implements _i3.ObjectMetadata {
_FakeObjectMetadata_6(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [Bucket].
///
/// See the documentation for Mockito's code generation for more information.
class MockBucket extends _i1.Mock implements _i3.Bucket {
MockBucket() {
_i1.throwOnMissingStub(this);
}
@override
String get bucketName => (super.noSuchMethod(
Invocation.getter(#bucketName),
returnValue: _i5.dummyValue<String>(
this,
Invocation.getter(#bucketName),
),
) as String);
@override
String absoluteObjectName(String? objectName) => (super.noSuchMethod(
Invocation.method(
#absoluteObjectName,
[objectName],
),
returnValue: _i5.dummyValue<String>(
this,
Invocation.method(
#absoluteObjectName,
[objectName],
),
),
) as String);
@override
_i2.StreamSink<List<int>> write(
String? objectName, {
int? length,
_i3.ObjectMetadata? metadata,
_i3.Acl? acl,
_i3.PredefinedAcl? predefinedAcl,
String? contentType,
}) =>
(super.noSuchMethod(
Invocation.method(
#write,
[objectName],
{
#length: length,
#metadata: metadata,
#acl: acl,
#predefinedAcl: predefinedAcl,
#contentType: contentType,
},
),
returnValue: _FakeStreamSink_0<List<int>>(
this,
Invocation.method(
#write,
[objectName],
{
#length: length,
#metadata: metadata,
#acl: acl,
#predefinedAcl: predefinedAcl,
#contentType: contentType,
},
),
),
) as _i2.StreamSink<List<int>>);
@override
_i2.Future<_i3.ObjectInfo> writeBytes(
String? name,
List<int>? bytes, {
_i3.ObjectMetadata? metadata,
_i3.Acl? acl,
_i3.PredefinedAcl? predefinedAcl,
String? contentType,
}) =>
(super.noSuchMethod(
Invocation.method(
#writeBytes,
[
name,
bytes,
],
{
#metadata: metadata,
#acl: acl,
#predefinedAcl: predefinedAcl,
#contentType: contentType,
},
),
returnValue: _i2.Future<_i3.ObjectInfo>.value(_FakeObjectInfo_1(
this,
Invocation.method(
#writeBytes,
[
name,
bytes,
],
{
#metadata: metadata,
#acl: acl,
#predefinedAcl: predefinedAcl,
#contentType: contentType,
},
),
)),
) as _i2.Future<_i3.ObjectInfo>);
@override
_i2.Stream<List<int>> read(
String? objectName, {
int? offset,
int? length,
}) =>
(super.noSuchMethod(
Invocation.method(
#read,
[objectName],
{
#offset: offset,
#length: length,
},
),
returnValue: _i2.Stream<List<int>>.empty(),
) as _i2.Stream<List<int>>);
@override
_i2.Future<_i3.ObjectInfo> info(String? name) => (super.noSuchMethod(
Invocation.method(
#info,
[name],
),
returnValue: _i2.Future<_i3.ObjectInfo>.value(_FakeObjectInfo_1(
this,
Invocation.method(
#info,
[name],
),
)),
) as _i2.Future<_i3.ObjectInfo>);
@override
_i2.Future<dynamic> delete(String? name) => (super.noSuchMethod(
Invocation.method(
#delete,
[name],
),
returnValue: _i2.Future<dynamic>.value(),
) as _i2.Future<dynamic>);
@override
_i2.Future<dynamic> updateMetadata(
String? objectName,
_i3.ObjectMetadata? metadata,
) =>
(super.noSuchMethod(
Invocation.method(
#updateMetadata,
[
objectName,
metadata,
],
),
returnValue: _i2.Future<dynamic>.value(),
) as _i2.Future<dynamic>);
@override
_i2.Stream<_i3.BucketEntry> list({
String? prefix,
String? delimiter,
}) =>
(super.noSuchMethod(
Invocation.method(
#list,
[],
{
#prefix: prefix,
#delimiter: delimiter,
},
),
returnValue: _i2.Stream<_i3.BucketEntry>.empty(),
) as _i2.Stream<_i3.BucketEntry>);
@override
_i2.Future<_i4.Page<_i3.BucketEntry>> page({
String? prefix,
String? delimiter,
int? pageSize = 50,
}) =>
(super.noSuchMethod(
Invocation.method(
#page,
[],
{
#prefix: prefix,
#delimiter: delimiter,
#pageSize: pageSize,
},
),
returnValue: _i2.Future<_i4.Page<_i3.BucketEntry>>.value(
_FakePage_2<_i3.BucketEntry>(
this,
Invocation.method(
#page,
[],
{
#prefix: prefix,
#delimiter: delimiter,
#pageSize: pageSize,
},
),
)),
) as _i2.Future<_i4.Page<_i3.BucketEntry>>);
}
/// A class which mocks [ObjectInfo].
///
/// See the documentation for Mockito's code generation for more information.
class MockObjectInfo extends _i1.Mock implements _i3.ObjectInfo {
MockObjectInfo() {
_i1.throwOnMissingStub(this);
}
@override
String get name => (super.noSuchMethod(
Invocation.getter(#name),
returnValue: _i5.dummyValue<String>(
this,
Invocation.getter(#name),
),
) as String);
@override
int get length => (super.noSuchMethod(
Invocation.getter(#length),
returnValue: 0,
) as int);
@override
DateTime get updated => (super.noSuchMethod(
Invocation.getter(#updated),
returnValue: _FakeDateTime_3(
this,
Invocation.getter(#updated),
),
) as DateTime);
@override
String get etag => (super.noSuchMethod(
Invocation.getter(#etag),
returnValue: _i5.dummyValue<String>(
this,
Invocation.getter(#etag),
),
) as String);
@override
List<int> get md5Hash => (super.noSuchMethod(
Invocation.getter(#md5Hash),
returnValue: <int>[],
) as List<int>);
@override
int get crc32CChecksum => (super.noSuchMethod(
Invocation.getter(#crc32CChecksum),
returnValue: 0,
) as int);
@override
Uri get downloadLink => (super.noSuchMethod(
Invocation.getter(#downloadLink),
returnValue: _FakeUri_4(
this,
Invocation.getter(#downloadLink),
),
) as Uri);
@override
_i3.ObjectGeneration get generation => (super.noSuchMethod(
Invocation.getter(#generation),
returnValue: _FakeObjectGeneration_5(
this,
Invocation.getter(#generation),
),
) as _i3.ObjectGeneration);
@override
_i3.ObjectMetadata get metadata => (super.noSuchMethod(
Invocation.getter(#metadata),
returnValue: _FakeObjectMetadata_6(
this,
Invocation.getter(#metadata),
),
) as _i3.ObjectMetadata);
}
| packages/packages/metrics_center/test/skiaperf_test.mocks.dart/0 | {
"file_path": "packages/packages/metrics_center/test/skiaperf_test.mocks.dart",
"repo_id": "packages",
"token_count": 4827
} | 1,066 |
name: multicast_dns
description: Dart package for performing mDNS queries (e.g. Bonjour, Avahi).
repository: https://github.com/flutter/packages/tree/main/packages/multicast_dns
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+multicast_dns%22
version: 0.3.2+6
environment:
sdk: ^3.1.0
dependencies:
meta: ^1.3.0
dev_dependencies:
test: "^1.16.5"
topics:
- bonjour
- mdns
- network
| packages/packages/multicast_dns/pubspec.yaml/0 | {
"file_path": "packages/packages/multicast_dns/pubspec.yaml",
"repo_id": "packages",
"token_count": 191
} | 1,067 |
# path_provider_example
Demonstrates how to use the path_provider plugin.
| packages/packages/path_provider/path_provider/example/README.md/0 | {
"file_path": "packages/packages/path_provider/path_provider/example/README.md",
"repo_id": "packages",
"token_count": 23
} | 1,068 |
// 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:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Path Provider',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Path Provider'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<Directory?>? _tempDirectory;
Future<Directory?>? _appSupportDirectory;
Future<Directory?>? _appLibraryDirectory;
Future<Directory?>? _appDocumentsDirectory;
Future<Directory?>? _appCacheDirectory;
Future<Directory?>? _externalDocumentsDirectory;
Future<List<Directory>?>? _externalStorageDirectories;
Future<List<Directory>?>? _externalCacheDirectories;
Future<Directory?>? _downloadsDirectory;
void _requestTempDirectory() {
setState(() {
_tempDirectory = getTemporaryDirectory();
});
}
Widget _buildDirectory(
BuildContext context, AsyncSnapshot<Directory?> snapshot) {
Text text = const Text('');
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
text = Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
text = Text('path: ${snapshot.data!.path}');
} else {
text = const Text('path unavailable');
}
}
return Padding(padding: const EdgeInsets.all(16.0), child: text);
}
Widget _buildDirectories(
BuildContext context, AsyncSnapshot<List<Directory>?> snapshot) {
Text text = const Text('');
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
text = Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
final String combined =
snapshot.data!.map((Directory d) => d.path).join(', ');
text = Text('paths: $combined');
} else {
text = const Text('path unavailable');
}
}
return Padding(padding: const EdgeInsets.all(16.0), child: text);
}
void _requestAppDocumentsDirectory() {
setState(() {
_appDocumentsDirectory = getApplicationDocumentsDirectory();
});
}
void _requestAppSupportDirectory() {
setState(() {
_appSupportDirectory = getApplicationSupportDirectory();
});
}
void _requestAppLibraryDirectory() {
setState(() {
_appLibraryDirectory = getLibraryDirectory();
});
}
void _requestAppCacheDirectory() {
setState(() {
_appCacheDirectory = getApplicationCacheDirectory();
});
}
void _requestExternalStorageDirectory() {
setState(() {
_externalDocumentsDirectory = getExternalStorageDirectory();
});
}
void _requestExternalStorageDirectories(StorageDirectory type) {
setState(() {
_externalStorageDirectories = getExternalStorageDirectories(type: type);
});
}
void _requestExternalCacheDirectories() {
setState(() {
_externalCacheDirectories = getExternalCacheDirectories();
});
}
void _requestDownloadsDirectory() {
setState(() {
_downloadsDirectory = getDownloadsDirectory();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestTempDirectory,
child: const Text(
'Get Temporary Directory',
),
),
),
FutureBuilder<Directory?>(
future: _tempDirectory,
builder: _buildDirectory,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestAppDocumentsDirectory,
child: const Text(
'Get Application Documents Directory',
),
),
),
FutureBuilder<Directory?>(
future: _appDocumentsDirectory,
builder: _buildDirectory,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestAppSupportDirectory,
child: const Text(
'Get Application Support Directory',
),
),
),
FutureBuilder<Directory?>(
future: _appSupportDirectory,
builder: _buildDirectory,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed:
Platform.isAndroid ? null : _requestAppLibraryDirectory,
child: Text(
Platform.isAndroid
? 'Application Library Directory unavailable'
: 'Get Application Library Directory',
),
),
),
FutureBuilder<Directory?>(
future: _appLibraryDirectory,
builder: _buildDirectory,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: _requestAppCacheDirectory,
child: const Text(
'Get Application Cache Directory',
),
),
),
FutureBuilder<Directory?>(
future: _appCacheDirectory,
builder: _buildDirectory,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: !Platform.isAndroid
? null
: _requestExternalStorageDirectory,
child: Text(
!Platform.isAndroid
? 'External storage is unavailable'
: 'Get External Storage Directory',
),
),
),
FutureBuilder<Directory?>(
future: _externalDocumentsDirectory,
builder: _buildDirectory,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: !Platform.isAndroid
? null
: () {
_requestExternalStorageDirectories(
StorageDirectory.music,
);
},
child: Text(
!Platform.isAndroid
? 'External directories are unavailable'
: 'Get External Storage Directories',
),
),
),
FutureBuilder<List<Directory>?>(
future: _externalStorageDirectories,
builder: _buildDirectories,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: !Platform.isAndroid
? null
: _requestExternalCacheDirectories,
child: Text(
!Platform.isAndroid
? 'External directories are unavailable'
: 'Get External Cache Directories',
),
),
),
FutureBuilder<List<Directory>?>(
future: _externalCacheDirectories,
builder: _buildDirectories,
),
],
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: Platform.isAndroid || Platform.isIOS
? null
: _requestDownloadsDirectory,
child: Text(
Platform.isAndroid || Platform.isIOS
? 'Downloads directory is unavailable'
: 'Get Downloads Directory',
),
),
),
FutureBuilder<Directory?>(
future: _downloadsDirectory,
builder: _buildDirectory,
),
],
),
],
),
),
);
}
}
| packages/packages/path_provider/path_provider/example/lib/main.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider/example/lib/main.dart",
"repo_id": "packages",
"token_count": 5391
} | 1,069 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.pathprovider">
</manifest>
| packages/packages/path_provider/path_provider_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/path_provider/path_provider_android/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 46
} | 1,070 |
// 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:ffi';
import 'dart:io';
import 'package:ffi/ffi.dart';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:path/path.dart' as path;
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:win32/win32.dart';
import 'folders.dart';
/// Constant for en-US language used in VersionInfo keys.
@visibleForTesting
const String languageEn = '0409';
/// Constant for CP1252 encoding used in VersionInfo keys
@visibleForTesting
const String encodingCP1252 = '04e4';
/// Constant for Unicode encoding used in VersionInfo keys
@visibleForTesting
const String encodingUnicode = '04b0';
/// Wraps the Win32 VerQueryValue API call.
///
/// This class exists to allow injecting alternate metadata in tests without
/// building multiple custom test binaries.
@visibleForTesting
class VersionInfoQuerier {
/// Returns the value for [key] in [versionInfo]s in section with given
/// language and encoding, or null if there is no such entry,
/// or if versionInfo is null.
///
/// See https://docs.microsoft.com/en-us/windows/win32/menurc/versioninfo-resource
/// for list of possible language and encoding values.
String? getStringValue(
Pointer<Uint8>? versionInfo,
String key, {
required String language,
required String encoding,
}) {
assert(language.isNotEmpty);
assert(encoding.isNotEmpty);
if (versionInfo == null) {
return null;
}
final Pointer<Utf16> keyPath =
TEXT('\\StringFileInfo\\$language$encoding\\$key');
final Pointer<UINT> length = calloc<UINT>();
final Pointer<Pointer<Utf16>> valueAddress = calloc<Pointer<Utf16>>();
try {
if (VerQueryValue(versionInfo, keyPath, valueAddress, length) == 0) {
return null;
}
return valueAddress.value.toDartString();
} finally {
calloc.free(keyPath);
calloc.free(length);
calloc.free(valueAddress);
}
}
}
/// The Windows implementation of [PathProviderPlatform]
///
/// This class implements the `package:path_provider` functionality for Windows.
class PathProviderWindows extends PathProviderPlatform {
/// Registers the Windows implementation.
static void registerWith() {
PathProviderPlatform.instance = PathProviderWindows();
}
/// The object to use for performing VerQueryValue calls.
@visibleForTesting
VersionInfoQuerier versionInfoQuerier = VersionInfoQuerier();
/// This is typically the same as the TMP environment variable.
@override
Future<String?> getTemporaryPath() async {
final Pointer<Utf16> buffer = calloc<Uint16>(MAX_PATH + 1).cast<Utf16>();
String path;
try {
final int length = GetTempPath(MAX_PATH, buffer);
if (length == 0) {
final int error = GetLastError();
throw WindowsException(error);
} else {
path = buffer.toDartString();
// GetTempPath adds a trailing backslash, but SHGetKnownFolderPath does
// not. Strip off trailing backslash for consistency with other methods
// here.
if (path.endsWith(r'\')) {
path = path.substring(0, path.length - 1);
}
}
// Ensure that the directory exists, since GetTempPath doesn't.
final Directory directory = Directory(path);
if (!directory.existsSync()) {
await directory.create(recursive: true);
}
return path;
} finally {
calloc.free(buffer);
}
}
@override
Future<String?> getApplicationSupportPath() =>
_createApplicationSubdirectory(WindowsKnownFolder.RoamingAppData);
@override
Future<String?> getApplicationDocumentsPath() =>
getPath(WindowsKnownFolder.Documents);
@override
Future<String?> getApplicationCachePath() =>
_createApplicationSubdirectory(WindowsKnownFolder.LocalAppData);
@override
Future<String?> getDownloadsPath() => getPath(WindowsKnownFolder.Downloads);
/// Retrieve any known folder from Windows.
///
/// folderID is a GUID that represents a specific known folder ID, drawn from
/// [WindowsKnownFolder].
Future<String?> getPath(String folderID) {
final Pointer<Pointer<Utf16>> pathPtrPtr = calloc<Pointer<Utf16>>();
final Pointer<GUID> knownFolderID = calloc<GUID>()..ref.setGUID(folderID);
try {
final int hr = SHGetKnownFolderPath(
knownFolderID,
KF_FLAG_DEFAULT,
NULL,
pathPtrPtr,
);
if (FAILED(hr)) {
if (hr == E_INVALIDARG || hr == E_FAIL) {
throw WindowsException(hr);
}
return Future<String?>.value();
}
final String path = pathPtrPtr.value.toDartString();
return Future<String>.value(path);
} finally {
calloc.free(pathPtrPtr);
calloc.free(knownFolderID);
}
}
String? _getStringValue(Pointer<Uint8>? infoBuffer, String key) =>
versionInfoQuerier.getStringValue(infoBuffer, key,
language: languageEn, encoding: encodingCP1252) ??
versionInfoQuerier.getStringValue(infoBuffer, key,
language: languageEn, encoding: encodingUnicode);
/// Returns the relative path string to append to the root directory returned
/// by Win32 APIs for application storage (such as RoamingAppDir) to get a
/// directory that is unique to the application.
///
/// The convention is to use company-name\product-name\. This will use that if
/// possible, using the data in the VERSIONINFO resource, with the following
/// fallbacks:
/// - If the company name isn't there, that component will be dropped.
/// - If the product name isn't there, it will use the exe's filename (without
/// extension).
String _getApplicationSpecificSubdirectory() {
String? companyName;
String? productName;
final Pointer<Utf16> moduleNameBuffer = wsalloc(MAX_PATH + 1);
final Pointer<DWORD> unused = calloc<DWORD>();
Pointer<BYTE>? infoBuffer;
try {
// Get the module name.
final int moduleNameLength =
GetModuleFileName(0, moduleNameBuffer, MAX_PATH);
if (moduleNameLength == 0) {
final int error = GetLastError();
throw WindowsException(error);
}
// From that, load the VERSIONINFO resource
final int infoSize = GetFileVersionInfoSize(moduleNameBuffer, unused);
if (infoSize != 0) {
infoBuffer = calloc<BYTE>(infoSize);
if (GetFileVersionInfo(moduleNameBuffer, 0, infoSize, infoBuffer) ==
0) {
calloc.free(infoBuffer);
infoBuffer = null;
}
}
companyName =
_sanitizedDirectoryName(_getStringValue(infoBuffer, 'CompanyName'));
productName =
_sanitizedDirectoryName(_getStringValue(infoBuffer, 'ProductName'));
// If there was no product name, use the executable name.
productName ??=
path.basenameWithoutExtension(moduleNameBuffer.toDartString());
return companyName != null
? path.join(companyName, productName)
: productName;
} finally {
calloc.free(moduleNameBuffer);
calloc.free(unused);
if (infoBuffer != null) {
calloc.free(infoBuffer);
}
}
}
/// Makes [rawString] safe as a directory component. See
/// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
///
/// If after sanitizing the string is empty, returns null.
String? _sanitizedDirectoryName(String? rawString) {
if (rawString == null) {
return null;
}
String sanitized = rawString
// Replace banned characters.
.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_')
// Remove trailing whitespace.
.trimRight()
// Ensure that it does not end with a '.'.
.replaceAll(RegExp(r'[.]+$'), '');
const int kMaxComponentLength = 255;
if (sanitized.length > kMaxComponentLength) {
sanitized = sanitized.substring(0, kMaxComponentLength);
}
return sanitized.isEmpty ? null : sanitized;
}
Future<String?> _createApplicationSubdirectory(String folderId) async {
final String? baseDir = await getPath(folderId);
if (baseDir == null) {
return null;
}
final Directory directory =
Directory(path.join(baseDir, _getApplicationSpecificSubdirectory()));
// Ensure that the directory exists if possible, since it will on other
// platforms. If the name is longer than MAXPATH, creating will fail, so
// skip that step; it's up to the client to decide what to do with the path
// in that case (e.g., using a short path).
if (directory.path.length <= MAX_PATH) {
if (!directory.existsSync()) {
await directory.create(recursive: true);
}
}
return directory.path;
}
}
| packages/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart",
"repo_id": "packages",
"token_count": 3159
} | 1,071 |
@startuml
[*] -> LaunchIsolate
state LaunchIsolate {
[*] --> ParseCommandLineArguments
ParseCommandLineArguments --> WriteTemporarySourceCode
WriteTemporarySourceCode --> SpawnPigeonIsolate
SpawnPigeonIsolate --> WaitForPigeonIsolate
WaitForPigeonIsolate --> [*]
}
LaunchIsolate -> [*]
state PigeonIsolate {
[*] --> ParseCommandLineArguments2
ParseCommandLineArguments2 --> PrintUsage
PrintUsage --> [*]
ParseCommandLineArguments2 --> ExecuteConfigurePigeon
ExecuteConfigurePigeon --> GenerateAST
GenerateAST --> RunGenerators
RunGenerators --> PrintErrors
PrintErrors --> ReturnStatusCode
ReturnStatusCode --> [*]
state GenerateAST {
[*] --> CollectAnnotatedClasses
CollectAnnotatedClasses --> CollectAnnotatedClassesDependencies
CollectAnnotatedClassesDependencies --> BuildAST
BuildAST --> [*]
}
state RunGenerators {
state DartTestGeneratorFork <<fork>>
state DartTestGeneratorJoin <<join>>
[*] --> DartTestGeneratorFork
DartTestGeneratorFork --> DartTestGeneratorJoin
DartTestGeneratorFork --> DartTestGenerator
DartTestGenerator --> DartTestGeneratorJoin
DartTestGeneratorJoin --> [*]
||
state DartGeneratorFork <<fork>>
state DartGeneratorJoin <<join>>
[*] --> DartGeneratorFork
DartGeneratorFork --> DartGeneratorJoin
DartGeneratorFork --> DartGenerator
DartGenerator --> DartGeneratorJoin
DartGeneratorJoin --> [*]
||
state JavaGeneratorFork <<fork>>
state JavaGeneratorJoin <<join>>
[*] --> JavaGeneratorFork
JavaGeneratorFork --> JavaGeneratorJoin
JavaGeneratorFork --> JavaGenerator
JavaGenerator --> JavaGeneratorJoin
JavaGeneratorJoin --> [*]
}
}
@enduml | packages/packages/pigeon/doc/pigeon_state.puml/0 | {
"file_path": "packages/packages/pigeon/doc/pigeon_state.puml",
"repo_id": "packages",
"token_count": 554
} | 1,072 |
// 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, do not edit directly.
// See also: https://pub.dev/packages/pigeon
#undef _HAS_EXCEPTIONS
#include "messages.g.h"
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
namespace pigeon_example {
using flutter::BasicMessageChannel;
using flutter::CustomEncodableValue;
using flutter::EncodableList;
using flutter::EncodableMap;
using flutter::EncodableValue;
FlutterError CreateConnectionError(const std::string channel_name) {
return FlutterError(
"channel-error",
"Unable to establish connection on channel: '" + channel_name + "'.",
EncodableValue(""));
}
// MessageData
MessageData::MessageData(const Code& code, const EncodableMap& data)
: code_(code), data_(data) {}
MessageData::MessageData(const std::string* name,
const std::string* description, const Code& code,
const EncodableMap& data)
: name_(name ? std::optional<std::string>(*name) : std::nullopt),
description_(description ? std::optional<std::string>(*description)
: std::nullopt),
code_(code),
data_(data) {}
const std::string* MessageData::name() const {
return name_ ? &(*name_) : nullptr;
}
void MessageData::set_name(const std::string_view* value_arg) {
name_ = value_arg ? std::optional<std::string>(*value_arg) : std::nullopt;
}
void MessageData::set_name(std::string_view value_arg) { name_ = value_arg; }
const std::string* MessageData::description() const {
return description_ ? &(*description_) : nullptr;
}
void MessageData::set_description(const std::string_view* value_arg) {
description_ =
value_arg ? std::optional<std::string>(*value_arg) : std::nullopt;
}
void MessageData::set_description(std::string_view value_arg) {
description_ = value_arg;
}
const Code& MessageData::code() const { return code_; }
void MessageData::set_code(const Code& value_arg) { code_ = value_arg; }
const EncodableMap& MessageData::data() const { return data_; }
void MessageData::set_data(const EncodableMap& value_arg) { data_ = value_arg; }
EncodableList MessageData::ToEncodableList() const {
EncodableList list;
list.reserve(4);
list.push_back(name_ ? EncodableValue(*name_) : EncodableValue());
list.push_back(description_ ? EncodableValue(*description_)
: EncodableValue());
list.push_back(EncodableValue((int)code_));
list.push_back(EncodableValue(data_));
return list;
}
MessageData MessageData::FromEncodableList(const EncodableList& list) {
MessageData decoded((Code)(std::get<int32_t>(list[2])),
std::get<EncodableMap>(list[3]));
auto& encodable_name = list[0];
if (!encodable_name.IsNull()) {
decoded.set_name(std::get<std::string>(encodable_name));
}
auto& encodable_description = list[1];
if (!encodable_description.IsNull()) {
decoded.set_description(std::get<std::string>(encodable_description));
}
return decoded;
}
ExampleHostApiCodecSerializer::ExampleHostApiCodecSerializer() {}
EncodableValue ExampleHostApiCodecSerializer::ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const {
switch (type) {
case 128:
return CustomEncodableValue(MessageData::FromEncodableList(
std::get<EncodableList>(ReadValue(stream))));
default:
return flutter::StandardCodecSerializer::ReadValueOfType(type, stream);
}
}
void ExampleHostApiCodecSerializer::WriteValue(
const EncodableValue& value, flutter::ByteStreamWriter* stream) const {
if (const CustomEncodableValue* custom_value =
std::get_if<CustomEncodableValue>(&value)) {
if (custom_value->type() == typeid(MessageData)) {
stream->WriteByte(128);
WriteValue(
EncodableValue(
std::any_cast<MessageData>(*custom_value).ToEncodableList()),
stream);
return;
}
}
flutter::StandardCodecSerializer::WriteValue(value, stream);
}
/// The codec used by ExampleHostApi.
const flutter::StandardMessageCodec& ExampleHostApi::GetCodec() {
return flutter::StandardMessageCodec::GetInstance(
&ExampleHostApiCodecSerializer::GetInstance());
}
// Sets up an instance of `ExampleHostApi` to handle messages through the
// `binary_messenger`.
void ExampleHostApi::SetUp(flutter::BinaryMessenger* binary_messenger,
ExampleHostApi* api) {
{
BasicMessageChannel<> channel(binary_messenger,
"dev.flutter.pigeon.pigeon_example_package."
"ExampleHostApi.getHostLanguage",
&GetCodec());
if (api != nullptr) {
channel.SetMessageHandler(
[api](const EncodableValue& message,
const flutter::MessageReply<EncodableValue>& reply) {
try {
ErrorOr<std::string> output = api->GetHostLanguage();
if (output.has_error()) {
reply(WrapError(output.error()));
return;
}
EncodableList wrapped;
wrapped.push_back(EncodableValue(std::move(output).TakeValue()));
reply(EncodableValue(std::move(wrapped)));
} catch (const std::exception& exception) {
reply(WrapError(exception.what()));
}
});
} else {
channel.SetMessageHandler(nullptr);
}
}
{
BasicMessageChannel<> channel(
binary_messenger,
"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add",
&GetCodec());
if (api != nullptr) {
channel.SetMessageHandler(
[api](const EncodableValue& message,
const flutter::MessageReply<EncodableValue>& reply) {
try {
const auto& args = std::get<EncodableList>(message);
const auto& encodable_a_arg = args.at(0);
if (encodable_a_arg.IsNull()) {
reply(WrapError("a_arg unexpectedly null."));
return;
}
const int64_t a_arg = encodable_a_arg.LongValue();
const auto& encodable_b_arg = args.at(1);
if (encodable_b_arg.IsNull()) {
reply(WrapError("b_arg unexpectedly null."));
return;
}
const int64_t b_arg = encodable_b_arg.LongValue();
ErrorOr<int64_t> output = api->Add(a_arg, b_arg);
if (output.has_error()) {
reply(WrapError(output.error()));
return;
}
EncodableList wrapped;
wrapped.push_back(EncodableValue(std::move(output).TakeValue()));
reply(EncodableValue(std::move(wrapped)));
} catch (const std::exception& exception) {
reply(WrapError(exception.what()));
}
});
} else {
channel.SetMessageHandler(nullptr);
}
}
{
BasicMessageChannel<> channel(
binary_messenger,
"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage",
&GetCodec());
if (api != nullptr) {
channel.SetMessageHandler(
[api](const EncodableValue& message,
const flutter::MessageReply<EncodableValue>& reply) {
try {
const auto& args = std::get<EncodableList>(message);
const auto& encodable_message_arg = args.at(0);
if (encodable_message_arg.IsNull()) {
reply(WrapError("message_arg unexpectedly null."));
return;
}
const auto& message_arg = std::any_cast<const MessageData&>(
std::get<CustomEncodableValue>(encodable_message_arg));
api->SendMessage(message_arg, [reply](ErrorOr<bool>&& output) {
if (output.has_error()) {
reply(WrapError(output.error()));
return;
}
EncodableList wrapped;
wrapped.push_back(
EncodableValue(std::move(output).TakeValue()));
reply(EncodableValue(std::move(wrapped)));
});
} catch (const std::exception& exception) {
reply(WrapError(exception.what()));
}
});
} else {
channel.SetMessageHandler(nullptr);
}
}
}
EncodableValue ExampleHostApi::WrapError(std::string_view error_message) {
return EncodableValue(
EncodableList{EncodableValue(std::string(error_message)),
EncodableValue("Error"), EncodableValue()});
}
EncodableValue ExampleHostApi::WrapError(const FlutterError& error) {
return EncodableValue(EncodableList{EncodableValue(error.code()),
EncodableValue(error.message()),
error.details()});
}
// Generated class from Pigeon that represents Flutter messages that can be
// called from C++.
MessageFlutterApi::MessageFlutterApi(flutter::BinaryMessenger* binary_messenger)
: binary_messenger_(binary_messenger) {}
const flutter::StandardMessageCodec& MessageFlutterApi::GetCodec() {
return flutter::StandardMessageCodec::GetInstance(
&flutter::StandardCodecSerializer::GetInstance());
}
void MessageFlutterApi::FlutterMethod(
const std::string* a_string_arg,
std::function<void(const std::string&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error) {
const std::string channel_name =
"dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi."
"flutterMethod";
BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec());
EncodableValue encoded_api_arguments = EncodableValue(EncodableList{
a_string_arg ? EncodableValue(*a_string_arg) : EncodableValue(),
});
channel.Send(
encoded_api_arguments, [channel_name, on_success = std::move(on_success),
on_error = std::move(on_error)](
const uint8_t* reply, size_t reply_size) {
std::unique_ptr<EncodableValue> response =
GetCodec().DecodeMessage(reply, reply_size);
const auto& encodable_return_value = *response;
const auto* list_return_value =
std::get_if<EncodableList>(&encodable_return_value);
if (list_return_value) {
if (list_return_value->size() > 1) {
on_error(
FlutterError(std::get<std::string>(list_return_value->at(0)),
std::get<std::string>(list_return_value->at(1)),
list_return_value->at(2)));
} else {
const auto& return_value =
std::get<std::string>(list_return_value->at(0));
on_success(return_value);
}
} else {
on_error(CreateConnectionError(channel_name));
}
});
}
} // namespace pigeon_example
| packages/packages/pigeon/example/app/windows/runner/messages.g.cpp/0 | {
"file_path": "packages/packages/pigeon/example/app/windows/runner/messages.g.cpp",
"repo_id": "packages",
"token_count": 4989
} | 1,073 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// A [map] function that calls the function with an enumeration as well as the
/// value.
Iterable<U> indexMap<T, U>(
Iterable<T> iterable, U Function(int index, T value) func) sync* {
int index = 0;
for (final T value in iterable) {
yield func(index, value);
++index;
}
}
/// Performs like [forEach] but invokes [func] with an enumeration.
void enumerate<T>(Iterable<T> iterable, void Function(int, T) func) {
int count = 0;
for (final T value in iterable) {
func(count, value);
++count;
}
}
/// A [map] function that takes in 2 iterables. The [Iterable]s must be of
/// equal length.
Iterable<V> map2<T, U, V>(
Iterable<T> ts, Iterable<U> us, V Function(T t, U u) func) sync* {
final Iterator<T> itt = ts.iterator;
final Iterator<U> itu = us.iterator;
while (itu.moveNext() && itt.moveNext()) {
yield func(itt.current, itu.current);
}
if (itu.moveNext() || itt.moveNext()) {
throw ArgumentError("Iterables aren't of equal length.");
}
}
/// A [map] function that takes in 3 iterables. The [Iterable]s must be of
/// equal length.
Iterable<V> map3<T, U, V, W>(Iterable<T> ts, Iterable<U> us, Iterable<W> ws,
V Function(T t, U u, W w) func) sync* {
final Iterator<T> itt = ts.iterator;
final Iterator<U> itu = us.iterator;
final Iterator<W> itw = ws.iterator;
while (itu.moveNext() && itt.moveNext() && itw.moveNext()) {
yield func(itt.current, itu.current, itw.current);
}
if (itu.moveNext() || itt.moveNext() || itw.moveNext()) {
throw ArgumentError("Iterables aren't of equal length.");
}
}
/// Adds [value] to the end of [ts].
Iterable<T> followedByOne<T>(Iterable<T> ts, T value) sync* {
for (final T item in ts) {
yield item;
}
yield value;
}
Iterable<int> _count() sync* {
int x = 0;
while (true) {
yield x++;
}
}
/// All integers starting at zero.
final Iterable<int> wholeNumbers = _count();
/// Repeats an [item] [n] times.
Iterable<T> repeat<T>(T item, int n) sync* {
for (int i = 0; i < n; ++i) {
yield item;
}
}
| packages/packages/pigeon/lib/functional.dart/0 | {
"file_path": "packages/packages/pigeon/lib/functional.dart",
"repo_id": "packages",
"token_count": 835
} | 1,074 |
// 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 file is an example pigeon file that is used in compilation, unit, mock
// handler, and e2e tests.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
javaOptions: JavaOptions(
className: 'MessagePigeon',
package: 'dev.flutter.aaclarke.pigeon',
),
objcOptions: ObjcOptions(
prefix: 'AC',
),
))
/// This comment is to test enum documentation comments.
///
/// This comment also tests multiple line comments.
///
///////////////////////////
/// This comment also tests comments that start with '/'
///////////////////////////
enum MessageRequestState {
pending,
success,
failure,
}
/// This comment is to test class documentation comments.
///
/// This comment also tests multiple line comments.
class MessageSearchRequest {
/// This comment is to test field documentation comments.
String? query;
/// This comment is to test field documentation comments.
int? anInt;
/// This comment is to test field documentation comments.
bool? aBool;
}
/// This comment is to test class documentation comments.
class MessageSearchReply {
/// This comment is to test field documentation comments.
///
/// This comment also tests multiple line comments.
String? result;
/// This comment is to test field documentation comments.
String? error;
/// This comment is to test field documentation comments.
MessageRequestState? state;
}
@HostApi(dartHostTestHandler: 'TestHostApi')
/// This comment is to test api documentation comments.
///
/// This comment also tests multiple line comments.
abstract class MessageApi {
/// This comment is to test documentation comments.
///
/// This comment also tests multiple line comments.
void initialize();
/// This comment is to test method documentation comments.
MessageSearchReply search(MessageSearchRequest request);
}
/// This comment is to test class documentation comments.
class MessageNested {
/// This comment is to test field documentation comments.
MessageSearchRequest? request;
}
@HostApi(dartHostTestHandler: 'TestNestedApi')
/// This comment is to test api documentation comments.
abstract class MessageNestedApi {
/// This comment is to test method documentation comments.
///
/// This comment also tests multiple line comments.
MessageSearchReply search(MessageNested nested);
}
@FlutterApi()
/// This comment is to test api documentation comments.
abstract class MessageFlutterSearchApi {
/// This comment is to test method documentation comments.
MessageSearchReply search(MessageSearchRequest request);
}
| packages/packages/pigeon/pigeons/message.dart/0 | {
"file_path": "packages/packages/pigeon/pigeons/message.dart",
"repo_id": "packages",
"token_count": 701
} | 1,075 |
// 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 com.example.alternate_language_test_plugin;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.alternate_language_test_plugin.CoreTests.AllClassesWrapper;
import com.example.alternate_language_test_plugin.CoreTests.AllNullableTypes;
import com.example.alternate_language_test_plugin.CoreTests.AllTypes;
import com.example.alternate_language_test_plugin.CoreTests.AnEnum;
import com.example.alternate_language_test_plugin.CoreTests.FlutterIntegrationCoreApi;
import com.example.alternate_language_test_plugin.CoreTests.HostIntegrationCoreApi;
import com.example.alternate_language_test_plugin.CoreTests.NullableResult;
import com.example.alternate_language_test_plugin.CoreTests.Result;
import com.example.alternate_language_test_plugin.CoreTests.VoidResult;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import java.util.List;
import java.util.Map;
/** This plugin handles the native side of the integration tests in example/integration_test/. */
public class AlternateLanguageTestPlugin implements FlutterPlugin, HostIntegrationCoreApi {
@Nullable FlutterIntegrationCoreApi flutterApi = null;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
HostIntegrationCoreApi.setUp(binding.getBinaryMessenger(), this);
flutterApi = new FlutterIntegrationCoreApi(binding.getBinaryMessenger());
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {}
// HostIntegrationCoreApi
@Override
public void noop() {}
@Override
public @NonNull AllTypes echoAllTypes(@NonNull AllTypes everything) {
return everything;
}
@Override
public @Nullable AllNullableTypes echoAllNullableTypes(@Nullable AllNullableTypes everything) {
return everything;
}
@Override
public @Nullable Object throwError() {
throw new RuntimeException("An error");
}
@Override
public void throwErrorFromVoid() {
throw new RuntimeException("An error");
}
@Override
public @Nullable Object throwFlutterError() {
throw new CoreTests.FlutterError("code", "message", "details");
}
@Override
public @NonNull Long echoInt(@NonNull Long anInt) {
return anInt;
}
@Override
public @NonNull Double echoDouble(@NonNull Double aDouble) {
return aDouble;
}
@Override
public @NonNull Boolean echoBool(@NonNull Boolean aBool) {
return aBool;
}
@Override
public @NonNull String echoString(@NonNull String aString) {
return aString;
}
@Override
public @NonNull byte[] echoUint8List(@NonNull byte[] aUint8List) {
return aUint8List;
}
@Override
public @NonNull Object echoObject(@NonNull Object anObject) {
return anObject;
}
@Override
public @NonNull List<Object> echoList(@NonNull List<Object> aList) {
return aList;
}
@Override
public @NonNull Map<String, Object> echoMap(@NonNull Map<String, Object> aMap) {
return aMap;
}
@Override
public @NonNull AllClassesWrapper echoClassWrapper(@NonNull AllClassesWrapper wrapper) {
return wrapper;
}
@Override
public @NonNull AnEnum echoEnum(@NonNull AnEnum anEnum) {
return anEnum;
}
@Override
public @NonNull String echoNamedDefaultString(@NonNull String aString) {
return aString;
}
@Override
public @NonNull Double echoOptionalDefaultDouble(@NonNull Double aDouble) {
return aDouble;
}
@Override
public @NonNull Long echoRequiredInt(@NonNull Long anInt) {
return anInt;
}
@Override
public @Nullable String extractNestedNullableString(@NonNull AllClassesWrapper wrapper) {
return wrapper.getAllNullableTypes().getANullableString();
}
@Override
public @NonNull AllClassesWrapper createNestedNullableString(@Nullable String nullableString) {
AllNullableTypes innerObject =
new AllNullableTypes.Builder().setANullableString(nullableString).build();
return new AllClassesWrapper.Builder().setAllNullableTypes(innerObject).build();
}
@Override
public @NonNull AllNullableTypes sendMultipleNullableTypes(
@Nullable Boolean aNullableBool,
@Nullable Long aNullableInt,
@Nullable String aNullableString) {
AllNullableTypes someThings =
new AllNullableTypes.Builder()
.setANullableBool(aNullableBool)
.setANullableInt(aNullableInt)
.setANullableString(aNullableString)
.build();
return someThings;
}
@Override
public @Nullable Long echoNullableInt(@Nullable Long aNullableInt) {
return aNullableInt;
}
@Override
public @Nullable Double echoNullableDouble(@Nullable Double aNullableDouble) {
return aNullableDouble;
}
@Override
public @Nullable Boolean echoNullableBool(@Nullable Boolean aNullableBool) {
return aNullableBool;
}
@Override
public @Nullable String echoNullableString(@Nullable String aNullableString) {
return aNullableString;
}
@Override
public @Nullable byte[] echoNullableUint8List(@Nullable byte[] aNullableUint8List) {
return aNullableUint8List;
}
@Override
public @Nullable Object echoNullableObject(@Nullable Object aNullableObject) {
return aNullableObject;
}
@Override
public @Nullable List<Object> echoNullableList(@Nullable List<Object> aNullableList) {
return aNullableList;
}
@Override
public @Nullable Map<String, Object> echoNullableMap(@Nullable Map<String, Object> aNullableMap) {
return aNullableMap;
}
@Override
public @Nullable AnEnum echoNullableEnum(@Nullable AnEnum anEnum) {
return anEnum;
}
@Override
public @Nullable Long echoOptionalNullableInt(@Nullable Long aNullableInt) {
return aNullableInt;
}
@Override
public @Nullable String echoNamedNullableString(@Nullable String aNullableString) {
return aNullableString;
}
@Override
public void noopAsync(@NonNull VoidResult result) {
result.success();
}
@Override
public void throwAsyncError(@NonNull NullableResult<Object> result) {
result.error(new RuntimeException("An error"));
}
@Override
public void throwAsyncErrorFromVoid(@NonNull VoidResult result) {
result.error(new RuntimeException("An error"));
}
@Override
public void throwAsyncFlutterError(@NonNull NullableResult<Object> result) {
result.error(new CoreTests.FlutterError("code", "message", "details"));
}
@Override
public void echoAsyncAllTypes(@NonNull AllTypes everything, @NonNull Result<AllTypes> result) {
result.success(everything);
}
@Override
public void echoAsyncNullableAllNullableTypes(
@Nullable AllNullableTypes everything, @NonNull NullableResult<AllNullableTypes> result) {
result.success(everything);
}
@Override
public void echoAsyncInt(@NonNull Long anInt, @NonNull Result<Long> result) {
result.success(anInt);
}
@Override
public void echoAsyncDouble(@NonNull Double aDouble, @NonNull Result<Double> result) {
result.success(aDouble);
}
@Override
public void echoAsyncBool(@NonNull Boolean aBool, @NonNull Result<Boolean> result) {
result.success(aBool);
}
@Override
public void echoAsyncString(@NonNull String aString, @NonNull Result<String> result) {
result.success(aString);
}
@Override
public void echoAsyncUint8List(@NonNull byte[] aUint8List, @NonNull Result<byte[]> result) {
result.success(aUint8List);
}
@Override
public void echoAsyncObject(@NonNull Object anObject, @NonNull Result<Object> result) {
result.success(anObject);
}
@Override
public void echoAsyncList(@NonNull List<Object> aList, @NonNull Result<List<Object>> result) {
result.success(aList);
}
@Override
public void echoAsyncMap(
@NonNull Map<String, Object> aMap, @NonNull Result<Map<String, Object>> result) {
result.success(aMap);
}
@Override
public void echoAsyncEnum(@NonNull AnEnum anEnum, @NonNull Result<AnEnum> result) {
result.success(anEnum);
}
@Override
public void echoAsyncNullableInt(@Nullable Long anInt, @NonNull NullableResult<Long> result) {
result.success(anInt);
}
@Override
public void echoAsyncNullableDouble(
@Nullable Double aDouble, @NonNull NullableResult<Double> result) {
result.success(aDouble);
}
@Override
public void echoAsyncNullableBool(
@Nullable Boolean aBool, @NonNull NullableResult<Boolean> result) {
result.success(aBool);
}
@Override
public void echoAsyncNullableString(
@Nullable String aString, @NonNull NullableResult<String> result) {
result.success(aString);
}
@Override
public void echoAsyncNullableUint8List(
@Nullable byte[] aUint8List, @NonNull NullableResult<byte[]> result) {
result.success(aUint8List);
}
@Override
public void echoAsyncNullableObject(
@Nullable Object anObject, @NonNull NullableResult<Object> result) {
result.success(anObject);
}
@Override
public void echoAsyncNullableList(
@Nullable List<Object> aList, @NonNull NullableResult<List<Object>> result) {
result.success(aList);
}
@Override
public void echoAsyncNullableMap(
@Nullable Map<String, Object> aMap, @NonNull NullableResult<Map<String, Object>> result) {
result.success(aMap);
}
@Override
public void echoAsyncNullableEnum(
@Nullable AnEnum anEnum, @NonNull NullableResult<AnEnum> result) {
result.success(anEnum);
}
@Override
public void callFlutterNoop(@NonNull VoidResult result) {
flutterApi.noop(result);
}
@Override
public void callFlutterThrowError(@NonNull NullableResult<Object> result) {
flutterApi.throwError(result);
}
@Override
public void callFlutterThrowErrorFromVoid(@NonNull VoidResult result) {
flutterApi.throwErrorFromVoid(result);
}
@Override
public void callFlutterEchoAllTypes(
@NonNull AllTypes everything, @NonNull Result<AllTypes> result) {
flutterApi.echoAllTypes(everything, result);
}
@Override
public void callFlutterEchoAllNullableTypes(
@Nullable AllNullableTypes everything, @NonNull NullableResult<AllNullableTypes> result) {
flutterApi.echoAllNullableTypes(everything, result);
}
@Override
public void callFlutterSendMultipleNullableTypes(
@Nullable Boolean aNullableBool,
@Nullable Long aNullableInt,
@Nullable String aNullableString,
@NonNull Result<AllNullableTypes> result) {
flutterApi.sendMultipleNullableTypes(aNullableBool, aNullableInt, aNullableString, result);
}
@Override
public void callFlutterEchoBool(@NonNull Boolean aBool, @NonNull Result<Boolean> result) {
flutterApi.echoBool(aBool, result);
}
@Override
public void callFlutterEchoInt(@NonNull Long anInt, @NonNull Result<Long> result) {
flutterApi.echoInt(anInt, result);
}
@Override
public void callFlutterEchoDouble(@NonNull Double aDouble, @NonNull Result<Double> result) {
flutterApi.echoDouble(aDouble, result);
}
@Override
public void callFlutterEchoString(@NonNull String aString, @NonNull Result<String> result) {
flutterApi.echoString(aString, result);
}
@Override
public void callFlutterEchoUint8List(@NonNull byte[] aList, @NonNull Result<byte[]> result) {
flutterApi.echoUint8List(aList, result);
}
@Override
public void callFlutterEchoList(
@NonNull List<Object> aList, @NonNull Result<List<Object>> result) {
flutterApi.echoList(aList, result);
}
@Override
public void callFlutterEchoMap(
@NonNull Map<String, Object> aMap, @NonNull Result<Map<String, Object>> result) {
flutterApi.echoMap(aMap, result);
}
@Override
public void callFlutterEchoEnum(@NonNull AnEnum anEnum, @NonNull Result<AnEnum> result) {
flutterApi.echoEnum(anEnum, result);
}
@Override
public void callFlutterEchoNullableBool(
@Nullable Boolean aBool, @NonNull NullableResult<Boolean> result) {
flutterApi.echoNullableBool(aBool, result);
}
@Override
public void callFlutterEchoNullableInt(
@Nullable Long anInt, @NonNull NullableResult<Long> result) {
flutterApi.echoNullableInt(anInt, result);
}
@Override
public void callFlutterEchoNullableDouble(
@Nullable Double aDouble, @NonNull NullableResult<Double> result) {
flutterApi.echoNullableDouble(aDouble, result);
}
@Override
public void callFlutterEchoNullableString(
@Nullable String aString, @NonNull NullableResult<String> result) {
flutterApi.echoNullableString(aString, result);
}
@Override
public void callFlutterEchoNullableUint8List(
@Nullable byte[] aList, @NonNull NullableResult<byte[]> result) {
flutterApi.echoNullableUint8List(aList, result);
}
@Override
public void callFlutterEchoNullableList(
@Nullable List<Object> aList, @NonNull NullableResult<List<Object>> result) {
flutterApi.echoNullableList(aList, result);
}
@Override
public void callFlutterEchoNullableMap(
@Nullable Map<String, Object> aMap, @NonNull NullableResult<Map<String, Object>> result) {
flutterApi.echoNullableMap(aMap, result);
}
@Override
public void callFlutterEchoNullableEnum(
@Nullable AnEnum anEnum, @NonNull NullableResult<AnEnum> result) {
flutterApi.echoNullableEnum(anEnum, result);
}
}
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/AlternateLanguageTestPlugin.java/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/AlternateLanguageTestPlugin.java",
"repo_id": "packages",
"token_count": 4574
} | 1,076 |
// 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 alternate_language_test_plugin;
#import "EchoMessenger.h"
///////////////////////////////////////////////////////////////////////////////////////////
@interface ListTest : XCTestCase
@end
///////////////////////////////////////////////////////////////////////////////////////////
@implementation ListTest
- (void)testListInList {
FLTTestMessage *top = [[FLTTestMessage alloc] init];
FLTTestMessage *inside = [[FLTTestMessage alloc] init];
inside.testList = @[ @1, @2, @3 ];
top.testList = @[ inside ];
EchoBinaryMessenger *binaryMessenger =
[[EchoBinaryMessenger alloc] initWithCodec:FLTFlutterSmallApiGetCodec()];
FLTFlutterSmallApi *api = [[FLTFlutterSmallApi alloc] initWithBinaryMessenger:binaryMessenger];
XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
[api echoWrappedList:top
completion:^(FLTTestMessage *_Nonnull result, FlutterError *_Nullable err) {
XCTAssertEqual(1u, result.testList.count);
XCTAssertTrue([result.testList[0] isKindOfClass:[FLTTestMessage class]]);
XCTAssertEqualObjects(inside.testList, [result.testList[0] testList]);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:1.0];
}
@end
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/ListTest.m/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/ListTest.m",
"repo_id": "packages",
"token_count": 504
} | 1,077 |
// 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, 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, no_leading_underscores_for_local_identifiers
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';
PlatformException _createConnectionError(String channelName) {
return PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel: "$channelName".',
);
}
List<Object?> wrapResponse(
{Object? result, PlatformException? error, bool empty = false}) {
if (empty) {
return <Object?>[];
}
if (error == null) {
return <Object?>[result];
}
return <Object?>[error.code, error.message, error.details];
}
/// This comment is to test enum documentation comments.
enum EnumState {
/// This comment is to test enum member (Pending) documentation comments.
Pending,
/// This comment is to test enum member (Success) documentation comments.
Success,
/// This comment is to test enum member (Error) documentation comments.
Error,
/// This comment is to test enum member (SnakeCase) documentation comments.
SnakeCase,
}
/// This comment is to test class documentation comments.
class DataWithEnum {
DataWithEnum({
this.state,
});
/// This comment is to test field documentation comments.
EnumState? state;
Object encode() {
return <Object?>[
state?.index,
];
}
static DataWithEnum decode(Object result) {
result as List<Object?>;
return DataWithEnum(
state: result[0] != null ? EnumState.values[result[0]! as int] : null,
);
}
}
class _EnumApi2HostCodec extends StandardMessageCodec {
const _EnumApi2HostCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is DataWithEnum) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return DataWithEnum.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// This comment is to test api documentation comments.
class EnumApi2Host {
/// Constructor for [EnumApi2Host]. 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.
EnumApi2Host({BinaryMessenger? binaryMessenger})
: __pigeon_binaryMessenger = binaryMessenger;
final BinaryMessenger? __pigeon_binaryMessenger;
static const MessageCodec<Object?> pigeonChannelCodec = _EnumApi2HostCodec();
/// This comment is to test method documentation comments.
Future<DataWithEnum> echo(DataWithEnum data) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Host.echo';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[data]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as DataWithEnum?)!;
}
}
}
class _EnumApi2FlutterCodec extends StandardMessageCodec {
const _EnumApi2FlutterCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is DataWithEnum) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return DataWithEnum.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// This comment is to test api documentation comments.
abstract class EnumApi2Flutter {
static const MessageCodec<Object?> pigeonChannelCodec =
_EnumApi2FlutterCodec();
/// This comment is to test method documentation comments.
DataWithEnum echo(DataWithEnum data);
static void setup(EnumApi2Flutter? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<
Object?>(
'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo',
pigeonChannelCodec,
binaryMessenger: binaryMessenger);
if (api == null) {
__pigeon_channel.setMessageHandler(null);
} else {
__pigeon_channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final DataWithEnum? arg_data = (args[0] as DataWithEnum?);
assert(arg_data != null,
'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null, expected non-null DataWithEnum.');
try {
final DataWithEnum output = api.echo(arg_data!);
return wrapResponse(result: output);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart",
"repo_id": "packages",
"token_count": 2443
} | 1,078 |
// 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:shared_test_plugin_code/src/generated/null_fields.gen.dart';
void main() {
test('test constructor with values', () {
final NullFieldsSearchRequest request =
NullFieldsSearchRequest(query: 'query', identifier: 1);
final NullFieldsSearchReply reply = NullFieldsSearchReply(
result: 'result',
error: 'error',
indices: <int>[1, 2, 3],
request: request,
type: NullFieldsSearchReplyType.success,
);
expect(reply.result, 'result');
expect(reply.error, 'error');
expect(reply.indices, <int>[1, 2, 3]);
expect(reply.request!.query, 'query');
expect(reply.type, NullFieldsSearchReplyType.success);
});
test('test request constructor with nulls', () {
final NullFieldsSearchRequest request =
NullFieldsSearchRequest(identifier: 1);
expect(request.query, isNull);
});
test('test reply constructor with nulls', () {
final NullFieldsSearchReply reply = NullFieldsSearchReply();
expect(reply.result, isNull);
expect(reply.error, isNull);
expect(reply.indices, isNull);
expect(reply.request, isNull);
expect(reply.type, isNull);
});
test('test request decode with values', () {
final NullFieldsSearchRequest request =
NullFieldsSearchRequest.decode(<dynamic>[
'query',
1,
]);
expect(request.query, 'query');
});
test('test request decode with null', () {
final NullFieldsSearchRequest request =
NullFieldsSearchRequest.decode(<dynamic>[
null,
1,
]);
expect(request.query, isNull);
});
test('test reply decode with values', () {
final NullFieldsSearchReply reply = NullFieldsSearchReply.decode(<dynamic>[
'result',
'error',
<int>[1, 2, 3],
<dynamic>[
'query',
1,
],
NullFieldsSearchReplyType.success.index,
]);
expect(reply.result, 'result');
expect(reply.error, 'error');
expect(reply.indices, <int>[1, 2, 3]);
expect(reply.request!.query, 'query');
expect(reply.type, NullFieldsSearchReplyType.success);
});
test('test reply decode with nulls', () {
final NullFieldsSearchReply reply = NullFieldsSearchReply.decode(<dynamic>[
null,
null,
null,
null,
null,
]);
expect(reply.result, isNull);
expect(reply.error, isNull);
expect(reply.indices, isNull);
expect(reply.request, isNull);
expect(reply.type, isNull);
});
test('test request encode with values', () {
final NullFieldsSearchRequest request =
NullFieldsSearchRequest(query: 'query', identifier: 1);
expect(request.encode(), <Object?>[
'query',
1,
]);
});
test('test request encode with null', () {
final NullFieldsSearchRequest request =
NullFieldsSearchRequest(identifier: 1);
expect(request.encode(), <Object?>[
null,
1,
]);
});
test('test reply encode with values', () {
final NullFieldsSearchReply reply = NullFieldsSearchReply(
result: 'result',
error: 'error',
indices: <int>[1, 2, 3],
request: NullFieldsSearchRequest(query: 'query', identifier: 1),
type: NullFieldsSearchReplyType.success,
);
expect(reply.encode(), <Object?>[
'result',
'error',
<int>[1, 2, 3],
<Object?>[
'query',
1,
],
NullFieldsSearchReplyType.success.index,
]);
});
test('test reply encode with nulls', () {
final NullFieldsSearchReply reply = NullFieldsSearchReply();
expect(reply.encode(), <Object?>[
null,
null,
null,
null,
null,
]);
});
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart",
"repo_id": "packages",
"token_count": 1498
} | 1,079 |
// 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 com.example.test_plugin
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
/** This plugin handles the native side of the integration tests in example/integration_test/. */
class TestPlugin : FlutterPlugin, HostIntegrationCoreApi {
var flutterApi: FlutterIntegrationCoreApi? = null
override fun onAttachedToEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
HostIntegrationCoreApi.setUp(binding.getBinaryMessenger(), this)
flutterApi = FlutterIntegrationCoreApi(binding.getBinaryMessenger())
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {}
// HostIntegrationCoreApi
override fun noop() {}
override fun echoAllTypes(everything: AllTypes): AllTypes {
return everything
}
override fun echoAllNullableTypes(everything: AllNullableTypes?): AllNullableTypes? {
return everything
}
override fun throwError(): Any? {
throw Exception("An error")
}
override fun throwErrorFromVoid() {
throw Exception("An error")
}
override fun throwFlutterError(): Any? {
throw FlutterError("code", "message", "details")
}
override fun echoInt(anInt: Long): Long {
return anInt
}
override fun echoDouble(aDouble: Double): Double {
return aDouble
}
override fun echoBool(aBool: Boolean): Boolean {
return aBool
}
override fun echoString(aString: String): String {
return aString
}
override fun echoUint8List(aUint8List: ByteArray): ByteArray {
return aUint8List
}
override fun echoObject(anObject: Any): Any {
return anObject
}
override fun echoList(aList: List<Any?>): List<Any?> {
return aList
}
override fun echoMap(aMap: Map<String?, Any?>): Map<String?, Any?> {
return aMap
}
override fun echoClassWrapper(wrapper: AllClassesWrapper): AllClassesWrapper {
return wrapper
}
override fun echoEnum(anEnum: AnEnum): AnEnum {
return anEnum
}
override fun echoNamedDefaultString(aString: String): String {
return aString
}
override fun echoOptionalDefaultDouble(aDouble: Double): Double {
return aDouble
}
override fun echoRequiredInt(anInt: Long): Long {
return anInt
}
override fun extractNestedNullableString(wrapper: AllClassesWrapper): String? {
return wrapper.allNullableTypes.aNullableString
}
override fun createNestedNullableString(nullableString: String?): AllClassesWrapper {
return AllClassesWrapper(AllNullableTypes(aNullableString = nullableString))
}
override fun sendMultipleNullableTypes(
aNullableBool: Boolean?,
aNullableInt: Long?,
aNullableString: String?
): AllNullableTypes {
return AllNullableTypes(
aNullableBool = aNullableBool,
aNullableInt = aNullableInt,
aNullableString = aNullableString)
}
override fun echoNullableInt(aNullableInt: Long?): Long? {
return aNullableInt
}
override fun echoNullableDouble(aNullableDouble: Double?): Double? {
return aNullableDouble
}
override fun echoNullableBool(aNullableBool: Boolean?): Boolean? {
return aNullableBool
}
override fun echoNullableString(aNullableString: String?): String? {
return aNullableString
}
override fun echoNullableUint8List(aNullableUint8List: ByteArray?): ByteArray? {
return aNullableUint8List
}
override fun echoNullableObject(aNullableObject: Any?): Any? {
return aNullableObject
}
override fun echoNullableList(aNullableList: List<Any?>?): List<Any?>? {
return aNullableList
}
override fun echoNullableMap(aNullableMap: Map<String?, Any?>?): Map<String?, Any?>? {
return aNullableMap
}
override fun echoNullableEnum(anEnum: AnEnum?): AnEnum? {
return anEnum
}
override fun echoOptionalNullableInt(aNullableInt: Long?): Long? {
return aNullableInt
}
override fun echoNamedNullableString(aNullableString: String?): String? {
return aNullableString
}
override fun noopAsync(callback: (Result<Unit>) -> Unit) {
callback(Result.success(Unit))
}
override fun throwAsyncError(callback: (Result<Any?>) -> Unit) {
callback(Result.failure(Exception("except")))
}
override fun throwAsyncErrorFromVoid(callback: (Result<Unit>) -> Unit) {
callback(Result.failure(Exception("except")))
}
override fun throwAsyncFlutterError(callback: (Result<Any?>) -> Unit) {
callback(Result.failure(FlutterError("code", "message", "details")))
}
override fun echoAsyncAllTypes(everything: AllTypes, callback: (Result<AllTypes>) -> Unit) {
callback(Result.success(everything))
}
override fun echoAsyncNullableAllNullableTypes(
everything: AllNullableTypes?,
callback: (Result<AllNullableTypes?>) -> Unit
) {
callback(Result.success(everything))
}
override fun echoAsyncInt(anInt: Long, callback: (Result<Long>) -> Unit) {
callback(Result.success(anInt))
}
override fun echoAsyncDouble(aDouble: Double, callback: (Result<Double>) -> Unit) {
callback(Result.success(aDouble))
}
override fun echoAsyncBool(aBool: Boolean, callback: (Result<Boolean>) -> Unit) {
callback(Result.success(aBool))
}
override fun echoAsyncString(aString: String, callback: (Result<String>) -> Unit) {
callback(Result.success(aString))
}
override fun echoAsyncUint8List(aUint8List: ByteArray, callback: (Result<ByteArray>) -> Unit) {
callback(Result.success(aUint8List))
}
override fun echoAsyncObject(anObject: Any, callback: (Result<Any>) -> Unit) {
callback(Result.success(anObject))
}
override fun echoAsyncList(aList: List<Any?>, callback: (Result<List<Any?>>) -> Unit) {
callback(Result.success(aList))
}
override fun echoAsyncMap(
aMap: Map<String?, Any?>,
callback: (Result<Map<String?, Any?>>) -> Unit
) {
callback(Result.success(aMap))
}
override fun echoAsyncEnum(anEnum: AnEnum, callback: (Result<AnEnum>) -> Unit) {
callback(Result.success(anEnum))
}
override fun echoAsyncNullableInt(anInt: Long?, callback: (Result<Long?>) -> Unit) {
callback(Result.success(anInt))
}
override fun echoAsyncNullableDouble(aDouble: Double?, callback: (Result<Double?>) -> Unit) {
callback(Result.success(aDouble))
}
override fun echoAsyncNullableBool(aBool: Boolean?, callback: (Result<Boolean?>) -> Unit) {
callback(Result.success(aBool))
}
override fun echoAsyncNullableString(aString: String?, callback: (Result<String?>) -> Unit) {
callback(Result.success(aString))
}
override fun echoAsyncNullableUint8List(
aUint8List: ByteArray?,
callback: (Result<ByteArray?>) -> Unit
) {
callback(Result.success(aUint8List))
}
override fun echoAsyncNullableObject(anObject: Any?, callback: (Result<Any?>) -> Unit) {
callback(Result.success(anObject))
}
override fun echoAsyncNullableList(aList: List<Any?>?, callback: (Result<List<Any?>?>) -> Unit) {
callback(Result.success(aList))
}
override fun echoAsyncNullableMap(
aMap: Map<String?, Any?>?,
callback: (Result<Map<String?, Any?>?>) -> Unit
) {
callback(Result.success(aMap))
}
override fun echoAsyncNullableEnum(anEnum: AnEnum?, callback: (Result<AnEnum?>) -> Unit) {
callback(Result.success(anEnum))
}
override fun callFlutterNoop(callback: (Result<Unit>) -> Unit) {
flutterApi!!.noop() { callback(Result.success(Unit)) }
}
override fun callFlutterThrowError(callback: (Result<Any?>) -> Unit) {
flutterApi!!.throwError() { result -> callback(result) }
}
override fun callFlutterThrowErrorFromVoid(callback: (Result<Unit>) -> Unit) {
flutterApi!!.throwErrorFromVoid() { result -> callback(result) }
}
override fun callFlutterEchoAllTypes(everything: AllTypes, callback: (Result<AllTypes>) -> Unit) {
flutterApi!!.echoAllTypes(everything) { echo -> callback(echo) }
}
override fun callFlutterSendMultipleNullableTypes(
aNullableBool: Boolean?,
aNullableInt: Long?,
aNullableString: String?,
callback: (Result<AllNullableTypes>) -> Unit
) {
flutterApi!!.sendMultipleNullableTypes(aNullableBool, aNullableInt, aNullableString) { echo ->
callback(echo)
}
}
override fun callFlutterEchoBool(aBool: Boolean, callback: (Result<Boolean>) -> Unit) {
flutterApi!!.echoBool(aBool) { echo -> callback(echo) }
}
override fun callFlutterEchoInt(anInt: Long, callback: (Result<Long>) -> Unit) {
flutterApi!!.echoInt(anInt) { echo -> callback(echo) }
}
override fun callFlutterEchoDouble(aDouble: Double, callback: (Result<Double>) -> Unit) {
flutterApi!!.echoDouble(aDouble) { echo -> callback(echo) }
}
override fun callFlutterEchoString(aString: String, callback: (Result<String>) -> Unit) {
flutterApi!!.echoString(aString) { echo -> callback(echo) }
}
override fun callFlutterEchoUint8List(aList: ByteArray, callback: (Result<ByteArray>) -> Unit) {
flutterApi!!.echoUint8List(aList) { echo -> callback(echo) }
}
override fun callFlutterEchoList(aList: List<Any?>, callback: (Result<List<Any?>>) -> Unit) {
flutterApi!!.echoList(aList) { echo -> callback(echo) }
}
override fun callFlutterEchoMap(
aMap: Map<String?, Any?>,
callback: (Result<Map<String?, Any?>>) -> Unit
) {
flutterApi!!.echoMap(aMap) { echo -> callback(echo) }
}
override fun callFlutterEchoEnum(anEnum: AnEnum, callback: (Result<AnEnum>) -> Unit) {
flutterApi!!.echoEnum(anEnum) { echo -> callback(echo) }
}
override fun callFlutterEchoAllNullableTypes(
everything: AllNullableTypes?,
callback: (Result<AllNullableTypes?>) -> Unit
) {
flutterApi!!.echoAllNullableTypes(everything) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableBool(aBool: Boolean?, callback: (Result<Boolean?>) -> Unit) {
flutterApi!!.echoNullableBool(aBool) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableInt(anInt: Long?, callback: (Result<Long?>) -> Unit) {
flutterApi!!.echoNullableInt(anInt) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableDouble(
aDouble: Double?,
callback: (Result<Double?>) -> Unit
) {
flutterApi!!.echoNullableDouble(aDouble) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableString(
aString: String?,
callback: (Result<String?>) -> Unit
) {
flutterApi!!.echoNullableString(aString) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableUint8List(
aList: ByteArray?,
callback: (Result<ByteArray?>) -> Unit
) {
flutterApi!!.echoNullableUint8List(aList) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableList(
aList: List<Any?>?,
callback: (Result<List<Any?>?>) -> Unit
) {
flutterApi!!.echoNullableList(aList) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableMap(
aMap: Map<String?, Any?>?,
callback: (Result<Map<String?, Any?>?>) -> Unit
) {
flutterApi!!.echoNullableMap(aMap) { echo -> callback(echo) }
}
override fun callFlutterEchoNullableEnum(anEnum: AnEnum?, callback: (Result<AnEnum?>) -> Unit) {
flutterApi!!.echoNullableEnum(anEnum) { echo -> callback(echo) }
}
}
| packages/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/TestPlugin.kt/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/TestPlugin.kt",
"repo_id": "packages",
"token_count": 3988
} | 1,080 |
// 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
@testable import test_plugin
class MockNullableArgHostApi: NullableArgHostApi {
var didCall: Bool = false
var x: Int64?
func doit(x: Int64?) -> Int64 {
didCall = true
self.x = x
return x ?? 0
}
}
class NullableReturnsTests: XCTestCase {
var codec = FlutterStandardMessageCodec.sharedInstance()
func testNullableParameterWithFlutterApi() {
let binaryMessenger = EchoBinaryMessenger(codec: codec)
binaryMessenger.defaultReturn = 99
let api = NullableArgFlutterApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
api.doit(x: nil) { result in
switch result {
case .success(let res):
XCTAssertEqual(99, res)
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
func testNullableParameterWithHostApi() {
let api = MockNullableArgHostApi()
let binaryMessenger = MockBinaryMessenger<Int64?>(codec: codec)
let channel = "dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit"
NullableArgHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: api)
XCTAssertNotNil(binaryMessenger.handlers[channel])
let inputEncoded = binaryMessenger.codec.encode([nil] as [Any?])
let expectation = XCTestExpectation(description: "callback")
binaryMessenger.handlers[channel]?(inputEncoded) { _ in
expectation.fulfill()
}
XCTAssertTrue(api.didCall)
XCTAssertNil(api.x)
wait(for: [expectation], timeout: 1.0)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NullableReturnsTests.swift/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NullableReturnsTests.swift",
"repo_id": "packages",
"token_count": 656
} | 1,081 |
// 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.
#ifndef FLUTTER_PLUGIN_TEST_PLUGIN_H_
#define FLUTTER_PLUGIN_TEST_PLUGIN_H_
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <memory>
#include <optional>
#include <string>
#include "pigeon/core_tests.gen.h"
namespace test_plugin {
// This plugin handles the native side of the integration tests in
// example/integration_test/
class TestPlugin : public flutter::Plugin,
public core_tests_pigeontest::HostIntegrationCoreApi {
public:
static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar);
TestPlugin(flutter::BinaryMessenger* binary_messenger);
virtual ~TestPlugin();
// Disallow copy and assign.
TestPlugin(const TestPlugin&) = delete;
TestPlugin& operator=(const TestPlugin&) = delete;
// HostIntegrationCoreApi.
std::optional<core_tests_pigeontest::FlutterError> Noop() override;
core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AllTypes> EchoAllTypes(
const core_tests_pigeontest::AllTypes& everything) override;
core_tests_pigeontest::ErrorOr<
std::optional<core_tests_pigeontest::AllNullableTypes>>
EchoAllNullableTypes(
const core_tests_pigeontest::AllNullableTypes* everything) override;
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableValue>>
ThrowError() override;
std::optional<core_tests_pigeontest::FlutterError> ThrowErrorFromVoid()
override;
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableValue>>
ThrowFlutterError() override;
core_tests_pigeontest::ErrorOr<int64_t> EchoInt(int64_t an_int) override;
core_tests_pigeontest::ErrorOr<double> EchoDouble(double a_double) override;
core_tests_pigeontest::ErrorOr<bool> EchoBool(bool a_bool) override;
core_tests_pigeontest::ErrorOr<std::string> EchoString(
const std::string& a_string) override;
core_tests_pigeontest::ErrorOr<std::vector<uint8_t>> EchoUint8List(
const std::vector<uint8_t>& a_uint8_list) override;
core_tests_pigeontest::ErrorOr<flutter::EncodableValue> EchoObject(
const flutter::EncodableValue& an_object) override;
core_tests_pigeontest::ErrorOr<flutter::EncodableList> EchoList(
const flutter::EncodableList& a_list) override;
core_tests_pigeontest::ErrorOr<flutter::EncodableMap> EchoMap(
const flutter::EncodableMap& a_map) override;
core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AllClassesWrapper>
EchoClassWrapper(
const core_tests_pigeontest::AllClassesWrapper& wrapper) override;
core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AnEnum> EchoEnum(
const core_tests_pigeontest::AnEnum& an_enum) override;
core_tests_pigeontest::ErrorOr<std::string> EchoNamedDefaultString(
const std::string& a_string) override;
core_tests_pigeontest::ErrorOr<double> EchoOptionalDefaultDouble(
double a_double) override;
core_tests_pigeontest::ErrorOr<int64_t> EchoRequiredInt(
int64_t an_int) override;
core_tests_pigeontest::ErrorOr<std::optional<std::string>>
ExtractNestedNullableString(
const core_tests_pigeontest::AllClassesWrapper& wrapper) override;
core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AllClassesWrapper>
CreateNestedNullableString(const std::string* nullable_string) override;
core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AllNullableTypes>
SendMultipleNullableTypes(const bool* a_nullable_bool,
const int64_t* a_nullable_int,
const std::string* a_nullable_string) override;
core_tests_pigeontest::ErrorOr<std::optional<int64_t>> EchoNullableInt(
const int64_t* a_nullable_int) override;
core_tests_pigeontest::ErrorOr<std::optional<double>> EchoNullableDouble(
const double* a_nullable_double) override;
core_tests_pigeontest::ErrorOr<std::optional<bool>> EchoNullableBool(
const bool* a_nullable_bool) override;
core_tests_pigeontest::ErrorOr<std::optional<std::string>> EchoNullableString(
const std::string* a_nullable_string) override;
core_tests_pigeontest::ErrorOr<std::optional<std::vector<uint8_t>>>
EchoNullableUint8List(
const std::vector<uint8_t>* a_nullable_uint8_list) override;
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableValue>>
EchoNullableObject(const flutter::EncodableValue* a_nullable_object) override;
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableList>>
EchoNullableList(const flutter::EncodableList* a_nullable_list) override;
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableMap>>
EchoNullableMap(const flutter::EncodableMap* a_nullable_map) override;
core_tests_pigeontest::ErrorOr<std::optional<core_tests_pigeontest::AnEnum>>
EchoNullableEnum(const core_tests_pigeontest::AnEnum* an_enum) override;
core_tests_pigeontest::ErrorOr<std::optional<int64_t>>
EchoOptionalNullableInt(const int64_t* a_nullable_int) override;
core_tests_pigeontest::ErrorOr<std::optional<std::string>>
EchoNamedNullableString(const std::string* a_nullable_string) override;
void NoopAsync(std::function<
void(std::optional<core_tests_pigeontest::FlutterError> reply)>
result) override;
void ThrowAsyncError(
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableValue>>
reply)>
result) override;
void ThrowAsyncErrorFromVoid(
std::function<
void(std::optional<core_tests_pigeontest::FlutterError> reply)>
result) override;
void ThrowAsyncFlutterError(
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableValue>>
reply)>
result) override;
void EchoAsyncAllTypes(
const core_tests_pigeontest::AllTypes& everything,
std::function<
void(core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AllTypes>
reply)>
result) override;
void EchoAsyncNullableAllNullableTypes(
const core_tests_pigeontest::AllNullableTypes* everything,
std::function<void(core_tests_pigeontest::ErrorOr<
std::optional<core_tests_pigeontest::AllNullableTypes>>
reply)>
result) override;
void EchoAsyncInt(
int64_t an_int,
std::function<void(core_tests_pigeontest::ErrorOr<int64_t> reply)> result)
override;
void EchoAsyncDouble(
double a_double,
std::function<void(core_tests_pigeontest::ErrorOr<double> reply)> result)
override;
void EchoAsyncBool(
bool a_bool,
std::function<void(core_tests_pigeontest::ErrorOr<bool> reply)> result)
override;
void EchoAsyncString(
const std::string& a_string,
std::function<void(core_tests_pigeontest::ErrorOr<std::string> reply)>
result) override;
void EchoAsyncUint8List(
const std::vector<uint8_t>& a_uint8_list,
std::function<
void(core_tests_pigeontest::ErrorOr<std::vector<uint8_t>> reply)>
result) override;
void EchoAsyncObject(
const flutter::EncodableValue& an_object,
std::function<
void(core_tests_pigeontest::ErrorOr<flutter::EncodableValue> reply)>
result) override;
void EchoAsyncList(
const flutter::EncodableList& a_list,
std::function<
void(core_tests_pigeontest::ErrorOr<flutter::EncodableList> reply)>
result) override;
void EchoAsyncMap(
const flutter::EncodableMap& a_map,
std::function<
void(core_tests_pigeontest::ErrorOr<flutter::EncodableMap> reply)>
result) override;
void EchoAsyncEnum(
const core_tests_pigeontest::AnEnum& an_enum,
std::function<void(
core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AnEnum> reply)>
result) override;
void EchoAsyncNullableInt(
const int64_t* an_int,
std::function<
void(core_tests_pigeontest::ErrorOr<std::optional<int64_t>> reply)>
result) override;
void EchoAsyncNullableDouble(
const double* a_double,
std::function<
void(core_tests_pigeontest::ErrorOr<std::optional<double>> reply)>
result) override;
void EchoAsyncNullableBool(
const bool* a_bool,
std::function<
void(core_tests_pigeontest::ErrorOr<std::optional<bool>> reply)>
result) override;
void EchoAsyncNullableString(
const std::string* a_string,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<std::string>> reply)>
result) override;
void EchoAsyncNullableUint8List(
const std::vector<uint8_t>* a_uint8_list,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<std::vector<uint8_t>>>
reply)>
result) override;
void EchoAsyncNullableObject(
const flutter::EncodableValue* an_object,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableValue>>
reply)>
result) override;
void EchoAsyncNullableList(
const flutter::EncodableList* a_list,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableList>>
reply)>
result) override;
void EchoAsyncNullableMap(
const flutter::EncodableMap* a_map,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableMap>>
reply)>
result) override;
void EchoAsyncNullableEnum(
const core_tests_pigeontest::AnEnum* an_enum,
std::function<void(core_tests_pigeontest::ErrorOr<
std::optional<core_tests_pigeontest::AnEnum>>
reply)>
result) override;
void CallFlutterNoop(
std::function<
void(std::optional<core_tests_pigeontest::FlutterError> reply)>
result) override;
void CallFlutterThrowError(
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableValue>>
reply)>
result) override;
void CallFlutterThrowErrorFromVoid(
std::function<
void(std::optional<core_tests_pigeontest::FlutterError> reply)>
result) override;
void CallFlutterEchoAllTypes(
const core_tests_pigeontest::AllTypes& everything,
std::function<
void(core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AllTypes>
reply)>
result) override;
void CallFlutterEchoAllNullableTypes(
const core_tests_pigeontest::AllNullableTypes* everything,
std::function<void(core_tests_pigeontest::ErrorOr<
std::optional<core_tests_pigeontest::AllNullableTypes>>
reply)>
result) override;
void CallFlutterSendMultipleNullableTypes(
const bool* a_nullable_bool, const int64_t* a_nullable_int,
const std::string* a_nullable_string,
std::function<void(core_tests_pigeontest::ErrorOr<
core_tests_pigeontest::AllNullableTypes>
reply)>
result) override;
void CallFlutterEchoBool(
bool a_bool,
std::function<void(core_tests_pigeontest::ErrorOr<bool> reply)> result)
override;
void CallFlutterEchoInt(
int64_t an_int,
std::function<void(core_tests_pigeontest::ErrorOr<int64_t> reply)> result)
override;
void CallFlutterEchoDouble(
double a_double,
std::function<void(core_tests_pigeontest::ErrorOr<double> reply)> result)
override;
void CallFlutterEchoString(
const std::string& a_string,
std::function<void(core_tests_pigeontest::ErrorOr<std::string> reply)>
result) override;
void CallFlutterEchoUint8List(
const std::vector<uint8_t>& a_list,
std::function<
void(core_tests_pigeontest::ErrorOr<std::vector<uint8_t>> reply)>
result) override;
void CallFlutterEchoList(
const flutter::EncodableList& a_list,
std::function<
void(core_tests_pigeontest::ErrorOr<flutter::EncodableList> reply)>
result) override;
void CallFlutterEchoMap(
const flutter::EncodableMap& a_map,
std::function<
void(core_tests_pigeontest::ErrorOr<flutter::EncodableMap> reply)>
result) override;
void CallFlutterEchoEnum(
const core_tests_pigeontest::AnEnum& an_enum,
std::function<void(
core_tests_pigeontest::ErrorOr<core_tests_pigeontest::AnEnum> reply)>
result) override;
void CallFlutterEchoNullableBool(
const bool* a_bool,
std::function<
void(core_tests_pigeontest::ErrorOr<std::optional<bool>> reply)>
result) override;
void CallFlutterEchoNullableInt(
const int64_t* an_int,
std::function<
void(core_tests_pigeontest::ErrorOr<std::optional<int64_t>> reply)>
result) override;
void CallFlutterEchoNullableDouble(
const double* a_double,
std::function<
void(core_tests_pigeontest::ErrorOr<std::optional<double>> reply)>
result) override;
void CallFlutterEchoNullableString(
const std::string* a_string,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<std::string>> reply)>
result) override;
void CallFlutterEchoNullableUint8List(
const std::vector<uint8_t>* a_list,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<std::vector<uint8_t>>>
reply)>
result) override;
void CallFlutterEchoNullableList(
const flutter::EncodableList* a_list,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableList>>
reply)>
result) override;
void CallFlutterEchoNullableMap(
const flutter::EncodableMap* a_map,
std::function<void(
core_tests_pigeontest::ErrorOr<std::optional<flutter::EncodableMap>>
reply)>
result) override;
void CallFlutterEchoNullableEnum(
const core_tests_pigeontest::AnEnum* an_enum,
std::function<void(core_tests_pigeontest::ErrorOr<
std::optional<core_tests_pigeontest::AnEnum>>
reply)>
result) override;
private:
std::unique_ptr<core_tests_pigeontest::FlutterIntegrationCoreApi>
flutter_api_;
};
} // namespace test_plugin
#endif // FLUTTER_PLUGIN_TEST_PLUGIN_H_
| packages/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.h/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.h",
"repo_id": "packages",
"token_count": 6242
} | 1,082 |
// 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
// Generates the pigeon output files needed for platform_test tests.
//
// Eventually this may get more options to control which files are generated,
// but for now it always generates everything needed for the platform unit
// tests.
import 'dart:io' show Platform, exit;
import 'package:args/args.dart';
import 'package:path/path.dart' as p;
import 'shared/generation.dart';
const String _helpFlag = 'help';
const String _formatFlag = 'format';
const String _noFormatFlag = 'no-format';
const String _files = 'files';
const String _test = 'test';
const String _example = 'example';
const List<String> _fileGroups = <String>[_test, _example];
Future<void> main(List<String> args) async {
final ArgParser parser = ArgParser()
..addFlag(
_formatFlag,
abbr: 'f',
help:
'Autoformat after generation. This flag is no longer needed, as this behavior is the default',
defaultsTo: true,
hide: true,
)
..addFlag(
_noFormatFlag,
abbr: 'n',
help: 'Do not autoformat after generation.',
)
..addFlag(_helpFlag,
negatable: false, abbr: 'h', help: 'Print this reference.')
..addMultiOption(_files,
help:
'Select specific groups of files to generate; $_test or $_example. Defaults to both.',
allowed: _fileGroups);
final ArgResults argResults = parser.parse(args);
if (argResults.wasParsed(_helpFlag)) {
print('''
usage: dart run tool/generate.dart [options]
${parser.usage}''');
exit(0);
}
final String baseDir = p.dirname(p.dirname(Platform.script.toFilePath()));
final List<String> toGenerate = argResults.wasParsed(_files)
? argResults[_files] as List<String>
: _fileGroups;
if (toGenerate.contains(_test)) {
print('Generating platform_test/ output...');
final int generateExitCode = await generateTestPigeons(baseDir: baseDir);
if (generateExitCode == 0) {
print('Generation complete!');
} else {
print('Generation failed; see above for errors.');
exit(generateExitCode);
}
}
if (toGenerate.contains(_example)) {
print('Generating example/ output...');
final int generateExitCode = await generateExamplePigeons();
if (generateExitCode == 0) {
print('Generation complete!');
} else {
print('Generation failed; see above for errors.');
exit(generateExitCode);
}
}
if (!argResults.wasParsed(_noFormatFlag)) {
print('Formatting generated output...');
final int formatExitCode =
await formatAllFiles(repositoryRoot: p.dirname(p.dirname(baseDir)));
if (formatExitCode != 0) {
print('Formatting failed; see above for errors.');
exit(formatExitCode);
}
}
}
| packages/packages/pigeon/tool/generate.dart/0 | {
"file_path": "packages/packages/pigeon/tool/generate.dart",
"repo_id": "packages",
"token_count": 1034
} | 1,083 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "efbf63d9c66b9f6ec30e9ad4611189aa80003d31"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
base_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
- platform: android
create_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
base_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
- platform: ios
create_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
base_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
- platform: linux
create_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
base_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
- platform: macos
create_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
base_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
- platform: windows
create_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
base_revision: efbf63d9c66b9f6ec30e9ad4611189aa80003d31
# 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'
| packages/packages/platform/example/.metadata/0 | {
"file_path": "packages/packages/platform/example/.metadata",
"repo_id": "packages",
"token_count": 687
} | 1,084 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
/// Provides API parity with the `Platform` class in `dart:io`, but using
/// instance properties rather than static properties. This difference enables
/// the use of these APIs in tests, where you can provide mock implementations.
abstract class Platform {
/// Creates a new [Platform].
const Platform();
/// A string constant to compare with [operatingSystem] to see if the platform
/// is Linux.
///
/// Useful in case statements when switching on [operatingSystem].
///
/// To just check if the platform is Linux, use [isLinux].
static const String linux = 'linux';
/// A string constant to compare with [operatingSystem] to see if the platform
/// is Windows.
///
/// Useful in case statements when switching on [operatingSystem].
///
/// To just check if the platform is Windows, use [isWindows].
static const String windows = 'windows';
/// A string constant to compare with [operatingSystem] to see if the platform
/// is macOS.
///
/// Useful in case statements when switching on [operatingSystem].
///
/// To just check if the platform is macOS, use [isMacOS].
static const String macOS = 'macos';
/// A string constant to compare with [operatingSystem] to see if the platform
/// is Android.
///
/// Useful in case statements when switching on [operatingSystem].
///
/// To just check if the platform is Android, use [isAndroid].
static const String android = 'android';
/// A string constant to compare with [operatingSystem] to see if the platform
/// is iOS.
///
/// Useful in case statements when switching on [operatingSystem].
///
/// To just check if the platform is iOS, use [isIOS].
static const String iOS = 'ios';
/// A string constant to compare with [operatingSystem] to see if the platform
/// is Fuchsia.
///
/// Useful in case statements when switching on [operatingSystem].
///
/// To just check if the platform is Fuchsia, use [isFuchsia].
static const String fuchsia = 'fuchsia';
/// A list of the possible values that [operatingSystem] can return.
static const List<String> operatingSystemValues = <String>[
linux,
macOS,
windows,
android,
iOS,
fuchsia,
];
/// The number of processors of the machine.
int get numberOfProcessors;
/// The path separator used by the operating system to separate
/// components in file paths.
String get pathSeparator;
/// A string (`linux`, `macos`, `windows`, `android`, `ios`, or `fuchsia`)
/// representing the operating system.
///
/// The possible return values are available from [operatingSystemValues], and
/// there are constants for each of the platforms to use in switch statements
/// or conditionals (See [linux], [macOS], [windows], [android], [iOS], and
/// [fuchsia]).
String get operatingSystem;
/// A string representing the version of the operating system or platform.
String get operatingSystemVersion;
/// Get the local hostname for the system.
String get localHostname;
/// True if the operating system is Linux.
bool get isLinux => operatingSystem == linux;
/// True if the operating system is OS X.
bool get isMacOS => operatingSystem == macOS;
/// True if the operating system is Windows.
bool get isWindows => operatingSystem == windows;
/// True if the operating system is Android.
bool get isAndroid => operatingSystem == android;
/// True if the operating system is iOS.
bool get isIOS => operatingSystem == iOS;
/// True if the operating system is Fuchsia
bool get isFuchsia => operatingSystem == fuchsia;
/// The environment for this process.
///
/// The returned environment is an unmodifiable map whose content is
/// retrieved from the operating system on its first use.
///
/// Environment variables on Windows are case-insensitive. The map
/// returned on Windows is therefore case-insensitive and will convert
/// all keys to upper case. On other platforms the returned map is
/// a standard case-sensitive map.
Map<String, String> get environment;
/// The path of the executable used to run the script in this isolate.
///
/// The path returned is the literal path used to run the script. This
/// path might be relative or just be a name from which the executable
/// was found by searching the `PATH`.
///
/// To get the absolute path to the resolved executable use
/// [resolvedExecutable].
String get executable;
/// The path of the executable used to run the script in this
/// isolate after it has been resolved by the OS.
///
/// This is the absolute path, with all symlinks resolved, to the
/// executable used to run the script.
String get resolvedExecutable;
/// The absolute URI of the script being run in this
/// isolate.
///
/// If the script argument on the command line is relative,
/// it is resolved to an absolute URI before fetching the script, and
/// this absolute URI is returned.
///
/// URI resolution only does string manipulation on the script path, and this
/// may be different from the file system's path resolution behavior. For
/// example, a symbolic link immediately followed by '..' will not be
/// looked up.
///
/// If the executable environment does not support [script] an empty
/// [Uri] is returned.
Uri get script;
/// The flags passed to the executable used to run the script in this
/// isolate. These are the command-line flags between the executable name
/// and the script name. Each fetch of `executableArguments` returns a new
/// list containing the flags passed to the executable.
List<String> get executableArguments;
/// The value of the `--packages` flag passed to the executable
/// used to run the script in this isolate. This is the configuration which
/// specifies how Dart packages are looked up.
///
/// If there is no `--packages` flag, `null` is returned.
String? get packageConfig;
/// The version of the current Dart runtime.
///
/// The returned `String` is formatted as the [semver](http://semver.org)
/// version string of the current dart runtime, possibly followed by
/// whitespace and other version and build details.
String get version;
/// When stdin is connected to a terminal, whether ANSI codes are supported.
bool get stdinSupportsAnsi;
/// When stdout is connected to a terminal, whether ANSI codes are supported.
bool get stdoutSupportsAnsi;
/// Get the name of the current locale.
String get localeName;
/// Returns a JSON-encoded representation of this platform.
String toJson() {
return const JsonEncoder.withIndent(' ').convert(<String, dynamic>{
'numberOfProcessors': numberOfProcessors,
'pathSeparator': pathSeparator,
'operatingSystem': operatingSystem,
'operatingSystemVersion': operatingSystemVersion,
'localHostname': localHostname,
'environment': environment,
'executable': executable,
'resolvedExecutable': resolvedExecutable,
'script': script.toString(),
'executableArguments': executableArguments,
'packageConfig': packageConfig,
'version': version,
'stdinSupportsAnsi': stdinSupportsAnsi,
'stdoutSupportsAnsi': stdoutSupportsAnsi,
'localeName': localeName,
});
}
}
| packages/packages/platform/lib/src/interface/platform.dart/0 | {
"file_path": "packages/packages/platform/lib/src/interface/platform.dart",
"repo_id": "packages",
"token_count": 2007
} | 1,085 |
// 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:js_interop';
import 'dart:ui_web' as ui_web;
import 'package:flutter/material.dart';
import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart';
import 'package:pointer_interceptor_web/pointer_interceptor_web.dart';
import 'package:web/web.dart' as web;
const String _htmlElementViewType = '_htmlElementViewType';
const double _containerWidth = 640;
const double _containerHeight = 480;
/// The html.Element that will be rendered underneath the flutter UI.
final web.Element _htmlElement =
(web.document.createElement('div') as web.HTMLDivElement)
..style.width = '100%'
..style.height = '100%'
..style.backgroundColor = '#fabada'
..style.cursor = 'auto'
..id = 'background-html-view';
// See other examples commented out below...
// final web.Element _htmlElement =
// (web.document.createElement('video') as web.HTMLVideoElement)
// ..style.width = '100%'
// ..style.height = '100%'
// ..style.cursor = 'auto'
// ..style.backgroundColor = 'black'
// ..id = 'background-html-view'
// ..src =
// 'https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4'
// ..poster =
// 'https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217'
// ..controls = true;
// final web.Element _htmlElement =
// (web.document.createElement('video') as web.HTMLIFrameElement)
// ..width = '100%'
// ..height = '100%'
// ..id = 'background-html-view'
// ..src = 'https://www.youtube.com/embed/IyFZznAk69U'
// ..style.border = 'none';
void main() {
runApp(const MyApp());
}
/// Main app
class MyApp extends StatelessWidget {
/// Creates main app.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Stopping Clicks with PointerInterceptor',
home: MyHomePage(),
);
}
}
/// First page
class MyHomePage extends StatefulWidget {
/// Creates first page.
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _lastClick = 'none';
void _clickedOn(String key) {
setState(() {
_lastClick = key;
});
}
@override
void initState() {
super.initState();
ui_web.platformViewRegistry.registerViewFactory(
_htmlElementViewType,
(int viewId) => _htmlElement,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('PointerInterceptor demo'),
actions: <Widget>[
PointerInterceptorPlatform.instance.buildWidget(
// debug: true,
child: IconButton(
icon: const Icon(Icons.add_alert),
tooltip: 'AppBar Icon',
onPressed: () {
_clickedOn('appbar-icon');
},
),
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Last click on: $_lastClick',
key: const Key('last-clicked'),
),
Container(
color: Colors.black,
width: _containerWidth,
height: _containerHeight,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
HtmlElement(
key: const Key('background-widget'),
onClick: () {
_clickedOn('html-element');
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ElevatedButton(
key: const Key('transparent-button'),
child: const Text('Never calls onPressed'),
onPressed: () {
_clickedOn('transparent-button');
},
),
PointerInterceptorWeb().buildWidget(
intercepting: false,
child: ElevatedButton(
key: const Key('wrapped-transparent-button'),
child:
const Text('Never calls onPressed transparent'),
onPressed: () {
_clickedOn('wrapped-transparent-button');
},
)),
PointerInterceptorPlatform.instance.buildWidget(
child: ElevatedButton(
key: const Key('clickable-button'),
child: const Text('Works As Expected'),
onPressed: () {
_clickedOn('clickable-button');
},
),
),
],
),
],
),
),
],
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
PointerInterceptorPlatform.instance.buildWidget(
// debug: true,
child: FloatingActionButton(
child: const Icon(Icons.navigation),
onPressed: () {
_clickedOn('fab-1');
},
),
),
],
),
drawer: Drawer(
child: PointerInterceptorPlatform.instance.buildWidget(
// debug: true, // Enable this to "see" the interceptor covering the column.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListTile(
title: const Text('Item 1'),
onTap: () {
_clickedOn('drawer-item-1');
},
),
ListTile(
title: const Text('Item 2'),
onTap: () {
_clickedOn('drawer-item-2');
},
),
],
),
),
),
);
}
}
/// Initialize the videoPlayer, then render the corresponding view...
class HtmlElement extends StatelessWidget {
/// Constructor
const HtmlElement({super.key, required this.onClick});
/// A function to run when the element is clicked
final VoidCallback onClick;
@override
Widget build(BuildContext context) {
_htmlElement.addEventListener(
'click',
(JSAny? _) {
onClick();
}.toJS,
);
return const HtmlElementView(
viewType: _htmlElementViewType,
);
}
}
| packages/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart",
"repo_id": "packages",
"token_count": 3544
} | 1,086 |
# Process
A generic process invocation abstraction for Dart.
Like `dart:io`, `package:process` supplies a rich, Dart-idiomatic API for
spawning OS processes.
Unlike `dart:io`, `package:process` requires processes to be started with
[ProcessManager], which allows for easy mocking and testing of code that
spawns processes in a hermetic way.
[ProcessManager]: https://pub.dev/documentation/process/latest/process/ProcessManager-class.html
| packages/packages/process/README.md/0 | {
"file_path": "packages/packages/process/README.md",
"repo_id": "packages",
"token_count": 115
} | 1,087 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/quick_actions/quick_actions/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/quick_actions/quick_actions/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,088 |
# quick\_actions\_android
The Android implementation of [`quick_actions`][1].
## Usage
This package is [endorsed][2], which means you can simply use `quick_actions`
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.
## Contributing
If you would like to contribute to the plugin, check out our [contribution guide][3].
[1]: https://pub.dev/packages/quick_actions
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
[3]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md
| packages/packages/quick_actions/quick_actions_android/README.md/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/README.md",
"repo_id": "packages",
"token_count": 227
} | 1,089 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.quickactionsexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="quick_actions_example" android:icon="@mipmap/ic_launcher">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true"/>
<activity android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
</manifest>
| packages/packages/quick_actions/quick_actions_android/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 403
} | 1,090 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 1.0.6
* Updates minimum required plugin_platform_interface version to 2.1.7.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 1.0.5
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
* Updates minimum Flutter version to 3.3.
* Aligns Dart and Flutter SDK constraints.
## 1.0.4
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 1.0.3
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 1.0.2
* Removes dependency on `meta`.
## 1.0.1
* Updates code for analyzer changes.
* Update to use the `verify` method introduced in plugin_platform_interface 2.1.0.
## 1.0.0
* Initial release of quick_actions_platform_interface
| packages/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md",
"repo_id": "packages",
"token_count": 288
} | 1,091 |
# Contributing
If you run into any problems, please file a [new
bug](https://github.com/flutter/flutter/issues/new?labels=p:%20rfw,package,P2).
Rather than waiting for a fix, we encourage you to consider submitting
a PR yourself. See our [contributing
guide](https://github.com/flutter/packages/blob/master/CONTRIBUTING.md)
for details.
Adding more widgets to `lib/flutter/core_widgets.dart` and
`lib/flutter/material_widgets.dart` is welcome.
When contributing code, ensure that `flutter test --coverage; lcov
--list coverage/lcov.info` continues to show 100% test coverage, and
update `test_coverage/bin/test_coverage.dart` with the appropriate
expectations to prevent future coverage regressions. (That program is
run by `run_tests.sh`.)
## Tests
To run the tests, use `flutter test`.
To run the web tests, use `flutter test --platform=chrome`. If there
is code that only runs on the web target, mark each such line by
ending it with the string `// dead code on VM target`. This will
exclude that line from the coverage calculation.
Golden tests are only run against the Flutter master channel and only
run on Linux, since minor rendering differences are expected on
different platforms and on different versions of Flutter.
## Golden test failures
When golden tests fail, several files will be created in a `test/failures`
directory.
The suffix of each file briefly describes its contents:
* `_masterImage`: The current golden against which comparisons are being made.
* `_testImage`: The image generated by this run of the test.
* `_isolatedDiff`: An image where only the pixels that differ between the
master and test images are rendered.
* `_maskedDiff`: An image where the pixels that differ between the master and
test images are rendered in black (isolatedDiff + maskedDiff = testImage).
Check the `_testImage` and the `Diff`s and see if the changes are valid. From
time to time, a new dithering or anti-aliasing algorithm will land in Flutter
that will invalidate a bunch of goldens, but not really break the rendering.
In this case, you may update the golden files.
### Updating golden files
Once you've validated that the new goldens are correct, you may update them by
calling `run_tests.sh --update-goldens`.
That command updates the reference golden images in the `test/goldens` directory.
Read more about Golden matching [in `package:flutter_test` API docs][package-test].
[package-test]: https://api.flutter.dev/flutter/flutter_test/matchesGoldenFile.html
| packages/packages/rfw/CONTRIBUTING.md/0 | {
"file_path": "packages/packages/rfw/CONTRIBUTING.md",
"repo_id": "packages",
"token_count": 682
} | 1,092 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/rfw/example/local/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "packages/packages/rfw/example/local/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 1,093 |
{
"name": "local",
"short_name": "local",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "Example of new custom local widgets for RFW",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icons/Icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icons/Icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
| packages/packages/rfw/example/local/web/manifest.json/0 | {
"file_path": "packages/packages/rfw/example/local/web/manifest.json",
"repo_id": "packages",
"token_count": 515
} | 1,094 |
// 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.
/// # Remote Flutter Widgets - formats only import
///
/// This is a subset of the [rfw] library that only exposes features that
/// do not depend on Flutter.
///
/// Specifically, the following APIs are exposed by this library:
///
/// * [parseLibraryFile] and [parseDataFile], for parsing Remote Flutter
/// Widgets text library and data files respectively. (These are not exposed
/// by the [rfw] library since they are not intended for use in client-side
/// code.)
///
/// * [encodeLibraryBlob] and [encodeDataBlob], for encoding the output of the
/// previous methods into binary form.
///
/// * [decodeLibraryBlob] and [decodeDataBlob], which decode those binary
/// forms.
///
/// * The [DynamicMap], [DynamicList], and [BlobNode] types (and subclasses),
/// which are used to represent the data model and remote widget libraries in
/// memory.
///
/// For client-side code, import `package:rfw/rfw.dart` instead.
library formats;
export 'src/dart/binary.dart';
export 'src/dart/model.dart';
export 'src/dart/text.dart';
| packages/packages/rfw/lib/formats.dart/0 | {
"file_path": "packages/packages/rfw/lib/formats.dart",
"repo_id": "packages",
"token_count": 360
} | 1,095 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:rfw/formats.dart' show parseLibraryFile;
import 'package:rfw/rfw.dart';
import 'utils.dart';
void main() {
const LibraryName coreName = LibraryName(<String>['core']);
const LibraryName materialName = LibraryName(<String>['material']);
const LibraryName testName = LibraryName(<String>['test']);
Runtime setupRuntime() {
return Runtime()
..update(coreName, createCoreWidgets())
..update(materialName, createMaterialWidgets());
}
testWidgets('Material widgets', (WidgetTester tester) async {
final Runtime runtime = setupRuntime();
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(testName, 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
),
);
expect(
tester.takeException().toString(),
contains('Could not find remote widget named'),
);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
import material;
widget root = Scaffold(
appBar: AppBar(
title: Text(text: 'Title'),
flexibleSpace: Placeholder(),
bottom: SizedBox(height: 56.0, child: Placeholder()),
),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(),
ListTile(
visualDensity: 'adaptivePlatformDensity',
title: Text(text: 'title'),
subtitle: Text(text: 'title'),
),
ListTile(
visualDensity: 'comfortable',
title: Text(text: 'title'),
subtitle: Text(text: 'title'),
),
ListTile(
visualDensity: 'compact',
title: Text(text: 'title'),
subtitle: Text(text: 'title'),
),
ListTile(
visualDensity: 'standard',
title: Text(text: 'title'),
subtitle: Text(text: 'title'),
),
ListTile(
visualDensity: { horizontal: -4.0, vertical: 4.0 },
title: Text(text: 'title'),
subtitle: Text(text: 'title'),
),
AboutListTile(),
],
),
),
body: ListView(
children: [
Card(
margin: [20.0],
child: ListBody(
children: [
ButtonBar(
children: [
ElevatedButton(
onPressed: event 'button' { },
child: Text(text: 'Elevated'),
),
OutlinedButton(
onPressed: event 'button' { },
child: Text(text: 'Outlined'),
),
TextButton(
onPressed: event 'button' { },
child: Text(text: 'Text'),
),
VerticalDivider(),
InkWell(
child: Text(text: 'Ink'),
),
],
),
],
),
),
Divider(),
Padding(
padding: [20.0],
child: Center(
child: CircularProgressIndicator(
value: 0.6,
),
),
),
Divider(),
Padding(
padding: [20.0],
child: Center(
child: LinearProgressIndicator(
value: 0.6,
),
),
),
Divider(),
Padding(
padding: [20.0],
child: Row(
mainAxisAlignment: 'spaceEvenly',
children: [
DropdownButton(
value: 'foo',
elevation: 14,
dropdownColor: 0xFF9E9E9E,
underline: Container(
height: 2,
color: 0xFF7C4DFF,
),
style: {
color:0xFF7C4DFF,
},
items: [
{
value: 'foo',
child: Text(text: 'foo'),
},
{
value: 'bar',
child: Text(text: 'bar'),
onTap: event 'menu_item' { args: 'bar' },
},
],
borderRadius:[{x: 8.0, y: 8.0}, {x: 8.0, y: 8.0}, {x: 8.0, y: 8.0}, {x: 8.0, y: 8.0}],
onChanged: event 'dropdown' {},
),
DropdownButton(
value: 1.0,
items: [
{
value: 1.0,
child: Text(text: 'first'),
},
{
value: 2.0,
child: Text(text: 'second'),
onTap: event 'menu_item' { args: 'second' },
},
],
onChanged: event 'dropdown' {},
),
],
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: event 'fab' {},
child: Placeholder(),
),
);
'''));
await tester.pump();
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile('goldens/material_test.scaffold.png'),
skip: !runGoldens,
);
await tester.tap(find.byType(DropdownButton<Object>).first);
await tester.pumpAndSettle();
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('goldens/material_test.dropdown.png'),
skip: !runGoldens,
);
// Tap on the second item.
await tester.tap(find.text('bar'));
await tester.pumpAndSettle();
expect(eventLog, contains('menu_item {args: bar}'));
expect(eventLog, contains('dropdown {value: bar}'));
await tester.tap(find.byType(DropdownButton<Object>).last);
await tester.pumpAndSettle();
await tester.tap(find.text('second'));
await tester.pumpAndSettle();
expect(eventLog, contains('menu_item {args: second}'));
expect(eventLog,
contains(kIsWeb ? 'dropdown {value: 2}' : 'dropdown {value: 2.0}'));
await tester.tapAt(const Offset(20.0, 20.0));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile('goldens/material_test.drawer.png'),
skip: !runGoldens,
);
});
testWidgets('Implement ButtonBar properties', (WidgetTester tester) async {
final Runtime runtime = setupRuntime();
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(testName, 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
),
);
expect(
tester.takeException().toString(),
contains('Could not find remote widget named'),
);
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
runtime.update(testName, parseLibraryFile('''
import core;
import material;
widget root = Scaffold(
body: Center(
child: ButtonBar(
buttonPadding: [8.0],
layoutBehavior: 'constrained',
alignment: 'end',
overflowDirection: 'up',
overflowButtonSpacing: 8.0,
mainAxisSize: 'min',
children: [
ElevatedButton(
onPressed: event 'button' { },
child: Text(text: 'Elevated'),
),
OutlinedButton(
onPressed: event 'button' { },
child: Text(text: 'Outlined'),
),
TextButton(
onPressed: event 'button' { },
child: Text(text: 'Text'),
),
],
),
),
);
'''));
await tester.pump();
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile('goldens/material_test.button_bar_properties.png'),
skip: !runGoldens,
);
// Update the surface size for ButtonBar to overflow.
await tester.binding.setSurfaceSize(const Size(200.0, 600.0));
await tester.pump();
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile(
'goldens/material_test.button_bar_properties.overflow.png'),
skip: !runGoldens,
);
});
testWidgets('OverflowBar configured to resemble ButtonBar',
(WidgetTester tester) async {
final Runtime runtime = setupRuntime();
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(testName, 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
),
);
expect(
tester.takeException().toString(),
contains('Could not find remote widget named'),
);
runtime.update(testName, parseLibraryFile('''
import core;
import material;
widget root = Scaffold(
body: Card(
margin: [20.0],
child: Padding(
padding: [8.0],
child: OverflowBar(
spacing: 8.0,
children: [
ElevatedButton(
onPressed: event 'button' { },
child: Text(text: 'Elevated'),
),
OutlinedButton(
onPressed: event 'button' { },
child: Text(text: 'Outlined'),
),
TextButton(
onPressed: event 'button' { },
child: Text(text: 'Text'),
),
],
),
),
),
);
'''));
await tester.pump();
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile(
'goldens/material_test.overflow_bar_resembles_button_bar.png'),
skip: !runGoldens,
);
});
testWidgets('Implement OverflowBar properties', (WidgetTester tester) async {
final Runtime runtime = setupRuntime();
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(testName, 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
),
);
expect(
tester.takeException().toString(),
contains('Could not find remote widget named'),
);
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
runtime.update(testName, parseLibraryFile('''
import core;
import material;
widget root = Scaffold(
body: Center(
child: OverflowBar(
spacing: 16.0,
alignment: 'end',
overflowSpacing: 4.0,
overflowAlignment: 'center',
overflowDirection: 'up',
children: [
ElevatedButton(
onPressed: event 'button' { },
child: Text(text: 'Elevated'),
),
OutlinedButton(
onPressed: event 'button' { },
child: Text(text: 'Outlined'),
),
TextButton(
onPressed: event 'button' { },
child: Text(text: 'Text'),
),
],
),
),
);
'''));
await tester.pump();
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile('goldens/material_test.overflow_bar_properties.png'),
skip: !runGoldens,
);
// Update the surface size for OverflowBar to overflow.
await tester.binding.setSurfaceSize(const Size(200.0, 600.0));
await tester.pump();
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile(
'goldens/material_test.overflow_bar_properties.overflow.png'),
skip: !runGoldens,
);
});
testWidgets('Implement InkResponse properties', (WidgetTester tester) async {
final Runtime runtime = setupRuntime();
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(testName, 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
),
);
expect(
tester.takeException().toString(),
contains('Could not find remote widget named'),
);
runtime.update(testName, parseLibraryFile('''
import core;
import material;
widget root = Scaffold(
body: Center(
child: InkResponse(
onTap: event 'onTap' {},
onHover: event 'onHover' {},
borderRadius: [{x: 8.0, y: 8.0}, {x: 8.0, y: 8.0}, {x: 8.0, y: 8.0}, {x: 8.0, y: 8.0}],
hoverColor: 0xFF00FF00,
splashColor: 0xAA0000FF,
highlightColor: 0xAAFF0000,
containedInkWell: true,
highlightShape: 'circle',
child: Text(text: 'InkResponse'),
),
),
);
'''));
await tester.pump();
expect(find.byType(InkResponse), findsOneWidget);
// Hover
final Offset center = tester.getCenter(find.byType(InkResponse));
final TestGesture gesture =
await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
addTearDown(gesture.removePointer);
await gesture.moveTo(center);
await tester.pumpAndSettle();
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile('goldens/material_test.ink_response_hover.png'),
skip: !runGoldens,
);
expect(eventLog, contains('onHover {}'));
// Tap
await gesture.down(center);
await tester.pump(); // start gesture
await tester.pump(const Duration(
milliseconds: 200)); // wait for splash to be well under way
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile('goldens/material_test.ink_response_tap.png'),
skip: !runGoldens,
);
await gesture.up();
await tester.pump();
expect(eventLog, contains('onTap {}'));
});
testWidgets('Implement Material properties', (WidgetTester tester) async {
final Runtime runtime = setupRuntime();
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(testName, 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
),
);
expect(
tester.takeException().toString(),
contains('Could not find remote widget named'),
);
runtime.update(testName, parseLibraryFile('''
import core;
import material;
widget root = Material(
type: 'circle',
elevation: 6.0,
color: 0xFF0000FF,
shadowColor: 0xFF00FF00,
surfaceTintColor: 0xff0000ff,
animationDuration: 300,
borderOnForeground: false,
child: SizedBox(
width: 20.0,
height: 20.0,
),
);
'''));
await tester.pump();
expect(tester.widget<Material>(find.byType(Material)).animationDuration,
const Duration(milliseconds: 300));
expect(tester.widget<Material>(find.byType(Material)).borderOnForeground,
false);
await expectLater(
find.byType(RemoteWidget),
matchesGoldenFile('goldens/material_test.material_properties.png'),
skip: !runGoldens,
);
runtime.update(testName, parseLibraryFile('''
import core;
import material;
widget root = Material(
clipBehavior: 'antiAlias',
shape: { type: 'circle', side: { width: 10.0, color: 0xFF0066FF } },
child: SizedBox(
width: 20.0,
height: 20.0,
),
);
'''));
await tester.pump();
expect(tester.widget<Material>(find.byType(Material)).clipBehavior,
Clip.antiAlias);
});
}
| packages/packages/rfw/test/material_widgets_test.dart/0 | {
"file_path": "packages/packages/rfw/test/material_widgets_test.dart",
"repo_id": "packages",
"token_count": 9116
} | 1,096 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,097 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_android/shared_preferences_android.dart';
import 'package:shared_preferences_android/src/messages.g.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:shared_preferences_platform_interface/types.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _FakeSharedPreferencesApi api;
late SharedPreferencesAndroid plugin;
const Map<String, Object> flutterTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.Bool': true,
'flutter.Int': 42,
'flutter.Double': 3.14159,
'flutter.StringList': <String>['foo', 'bar'],
};
const Map<String, Object> prefixTestValues = <String, Object>{
'prefix.String': 'hello world',
'prefix.Bool': true,
'prefix.Int': 42,
'prefix.Double': 3.14159,
'prefix.StringList': <String>['foo', 'bar'],
};
const Map<String, Object> nonPrefixTestValues = <String, Object>{
'String': 'hello world',
'Bool': true,
'Int': 42,
'Double': 3.14159,
'StringList': <String>['foo', 'bar'],
};
final Map<String, Object> allTestValues = <String, Object>{};
allTestValues.addAll(flutterTestValues);
allTestValues.addAll(prefixTestValues);
allTestValues.addAll(nonPrefixTestValues);
setUp(() {
api = _FakeSharedPreferencesApi();
plugin = SharedPreferencesAndroid(api: api);
});
test('registerWith', () {
SharedPreferencesAndroid.registerWith();
expect(SharedPreferencesStorePlatform.instance,
isA<SharedPreferencesAndroid>());
});
test('remove', () async {
api.items['flutter.hi'] = 'world';
expect(await plugin.remove('flutter.hi'), isTrue);
expect(api.items.containsKey('flutter.hi'), isFalse);
});
test('clear', () async {
api.items['flutter.hi'] = 'world';
expect(await plugin.clear(), isTrue);
expect(api.items.containsKey('flutter.hi'), isFalse);
});
test('clearWithPrefix', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
Map<String?, Object?> all = await plugin.getAllWithPrefix('prefix.');
expect(all.length, 5);
await plugin.clearWithPrefix('prefix.');
all = await plugin.getAll();
expect(all.length, 5);
all = await plugin.getAllWithPrefix('prefix.');
expect(all.length, 0);
});
test('clearWithParameters', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
Map<String?, Object?> all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(all.length, 5);
await plugin.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
all = await plugin.getAll();
expect(all.length, 5);
all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(all.length, 0);
});
test('clearWithParameters with allow list', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
Map<String?, Object?> all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(all.length, 5);
await plugin.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(
prefix: 'prefix.',
allowList: <String>{'prefix.StringList'},
),
),
);
all = await plugin.getAll();
expect(all.length, 5);
all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(all.length, 4);
});
test('getAll', () async {
for (final String key in flutterTestValues.keys) {
api.items[key] = flutterTestValues[key]!;
}
final Map<String?, Object?> all = await plugin.getAll();
expect(all.length, 5);
expect(all, flutterTestValues);
});
test('getAllWithNoPrefix', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
final Map<String?, Object?> all = await plugin.getAllWithPrefix('');
expect(all.length, 15);
expect(all, allTestValues);
});
test('clearWithNoPrefix', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
Map<String?, Object?> all = await plugin.getAllWithPrefix('');
expect(all.length, 15);
await plugin.clearWithPrefix('');
all = await plugin.getAllWithPrefix('');
expect(all.length, 0);
});
test('getAllWithParameters', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
final Map<String?, Object?> all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(all.length, 5);
expect(all, prefixTestValues);
});
test('getAllWithParameters with allow list', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
final Map<String?, Object?> all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(
prefix: 'prefix.',
allowList: <String>{'prefix.Bool'},
),
),
);
expect(all.length, 1);
expect(all['prefix.Bool'], true);
});
test('setValue', () async {
expect(await plugin.setValue('Bool', 'flutter.Bool', true), isTrue);
expect(api.items['flutter.Bool'], true);
expect(await plugin.setValue('Double', 'flutter.Double', 1.5), isTrue);
expect(api.items['flutter.Double'], 1.5);
expect(await plugin.setValue('Int', 'flutter.Int', 12), isTrue);
expect(api.items['flutter.Int'], 12);
expect(await plugin.setValue('String', 'flutter.String', 'hi'), isTrue);
expect(api.items['flutter.String'], 'hi');
expect(
await plugin
.setValue('StringList', 'flutter.StringList', <String>['hi']),
isTrue);
expect(api.items['flutter.StringList'], <String>['hi']);
});
test('setValue with unsupported type', () {
expect(() async {
await plugin.setValue('Map', 'flutter.key', <String, String>{});
}, throwsA(isA<PlatformException>()));
});
test('getAllWithNoPrefix', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
final Map<String?, Object?> all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: ''),
),
);
expect(all.length, 15);
expect(all, allTestValues);
});
test('clearWithNoPrefix', () async {
for (final String key in allTestValues.keys) {
api.items[key] = allTestValues[key]!;
}
Map<String?, Object?> all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: ''),
),
);
expect(all.length, 15);
await plugin.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(prefix: ''),
),
);
all = await plugin.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: ''),
),
);
expect(all.length, 0);
});
}
class _FakeSharedPreferencesApi implements SharedPreferencesApi {
final Map<String, Object> items = <String, Object>{};
@override
Future<Map<String?, Object?>> getAll(
String prefix,
List<String?>? allowList,
) async {
Set<String?>? allowSet;
if (allowList != null) {
allowSet = Set<String>.from(allowList);
}
return <String?, Object?>{
for (final String key in items.keys)
if (key.startsWith(prefix) &&
(allowSet == null || allowSet.contains(key)))
key: items[key]
};
}
@override
Future<bool> remove(String key) async {
items.remove(key);
return true;
}
@override
Future<bool> setBool(String key, bool value) async {
items[key] = value;
return true;
}
@override
Future<bool> setDouble(String key, double value) async {
items[key] = value;
return true;
}
@override
Future<bool> clear(String prefix, List<String?>? allowList) async {
items.keys.toList().forEach((String key) {
if (key.startsWith(prefix) &&
(allowList == null || allowList.contains(key))) {
items.remove(key);
}
});
return true;
}
@override
Future<bool> setInt(String key, Object value) async {
items[key] = value;
return true;
}
@override
Future<bool> setString(String key, String value) async {
items[key] = value;
return true;
}
@override
Future<bool> setStringList(String key, List<String?> value) async {
items[key] = value;
return true;
}
}
| packages/packages/shared_preferences/shared_preferences_android/test/shared_preferences_android_test.dart/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_android/test/shared_preferences_android_test.dart",
"repo_id": "packages",
"token_count": 3573
} | 1,098 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 2.3.2
* Updates minimum required plugin_platform_interface version to 2.1.7.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 2.3.1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.3.0
* Adds `clearWithParameters` and `getAllWithParameters` methods.
* Deprecates `clearWithPrefix` and `getAllWithPrefix` methods.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 2.2.0
* Adds `getAllWithPrefix` and `clearWithPrefix` method.
* Aligns Dart and Flutter SDK constraints.
## 2.1.1
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.1.0
* Adopts `plugin_platform_interface`. As a result, `isMock` is deprecated in
favor of the now-standard `MockPlatformInterfaceMixin`.
## 2.0.0
* Migrate to null safety.
## 1.0.5
* Update Flutter SDK constraint.
## 1.0.4
* Update lower bound of dart dependency to 2.1.0.
## 1.0.3
* Make the pedantic dev_dependency explicit.
## 1.0.2
* Adds a `shared_preferences_macos` package.
## 1.0.1
* Remove the deprecated `author:` field from pubspec.yaml
## 1.0.0
* Initial release. Contains the interface and an implementation based on
method channels.
| packages/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md",
"repo_id": "packages",
"token_count": 460
} | 1,099 |
name: shared_preferences_web_integration_tests
publish_to: none
environment:
sdk: ">=3.2.0 <4.0.0"
flutter: ">=3.16.0"
dependencies:
flutter:
sdk: flutter
shared_preferences_platform_interface: ^2.3.0
shared_preferences_web:
path: ../
web: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
| packages/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 163
} | 1,100 |
# example_standard_message_codec
A sample app for demonstrating the StandardMessageCodec
| packages/packages/standard_message_codec/example/README.md/0 | {
"file_path": "packages/packages/standard_message_codec/example/README.md",
"repo_id": "packages",
"token_count": 22
} | 1,101 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/two_dimensional_scrollables/example/android/gradle.properties/0 | {
"file_path": "packages/packages/two_dimensional_scrollables/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 31
} | 1,102 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,103 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export 'package:url_launcher_platform_interface/link.dart'
show FollowLink, LinkTarget, LinkWidgetBuilder;
export 'src/link.dart' show Link;
| packages/packages/url_launcher/url_launcher/lib/link.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher/lib/link.dart",
"repo_id": "packages",
"token_count": 90
} | 1,104 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 6.3.0
* Adds support for `BrowserConfiguration`.
* Implements `showTitle` functionality for Android Custom Tabs.
* Updates compileSdk version to 34.
## 6.2.3
* Bumps androidx.annotation:annotation from 1.7.0 to 1.7.1.
## 6.2.2
* Updates minimum required plugin_platform_interface version to 2.1.7.
## 6.2.1
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Fixes lint warnings.
## 6.2.0
* Adds support for `inAppBrowserView` as a separate launch mode option from
`inAppWebView` mode. `inAppBrowserView` is the preferred in-app mode for most uses,
but does not support `closeInAppWebView`.
* Implements `supportsMode` and `supportsCloseForMode`.
## 6.1.1
* Updates annotations lib to 1.7.0.
## 6.1.0
* Adds support for Android Custom Tabs.
## 6.0.39
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 6.0.38
* Updates android implementation to support api 34 broadcast receiver requirements.
## 6.0.37
* Sets android.defaults.buildfeatures.buildconfig to true for compatibility with AGP 8.0+.
## 6.0.36
* Bumps androidx.annotation:annotation from 1.2.0 to 1.6.0.
* Adds a dependency on kotlin-bom to align versions of Kotlin transitive dependencies.
## 6.0.35
* Converts method channels to Pigeon.
## 6.0.34
* Reverts ContextCompat usage that caused flutter/flutter#127014
## 6.0.33
* Explicitly sets if reciever for close should be exported.
## 6.0.32
* Updates gradle, AGP and fixes some lint errors.
## 6.0.31
* Fixes compatibility with AGP versions older than 4.2.
## 6.0.30
* Adds `targetCompatibilty` matching `sourceCompatibility` for older toolchains.
## 6.0.29
* Adds a namespace for compatibility with AGP 8.0.
## 6.0.28
* Sets an explicit Java compatibility version.
## 6.0.27
* Fixes Java warnings.
* Updates minimum Flutter version to 3.3.
## 6.0.26
* Bump RoboElectric dependency to 4.4.1 to support AndroidX.
## 6.0.25
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
## 6.0.24
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 6.0.23
* Updates code for stricter lint checks.
## 6.0.22
* Updates code for new analysis options.
## 6.0.21
* Updates androidx.annotation to 1.2.0.
## 6.0.20
* Updates android gradle plugin to 4.2.0.
## 6.0.19
* Revert gradle back to 3.4.2.
## 6.0.18
* Updates gradle to 7.2.2.
* Updates minimum Flutter version to 2.10.
## 6.0.17
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 6.0.16
* Adds fallback querying for `canLaunch` with web URLs, to avoid false negatives
when there is a custom scheme handler.
## 6.0.15
* Switches to an in-package method channel implementation.
## 6.0.14
* Updates code for new analysis options.
* Removes dependency on `meta`.
## 6.0.13
* Splits from `shared_preferences` as a federated implementation.
| packages/packages/url_launcher/url_launcher_android/CHANGELOG.md/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_android/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1053
} | 1,105 |
// 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 (v10.1.6), 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';
/// Configuration options for an in-app WebView.
class WebViewOptions {
WebViewOptions({
required this.enableJavaScript,
required this.enableDomStorage,
required this.headers,
});
bool enableJavaScript;
bool enableDomStorage;
Map<String?, String?> headers;
Object encode() {
return <Object?>[
enableJavaScript,
enableDomStorage,
headers,
];
}
static WebViewOptions decode(Object result) {
result as List<Object?>;
return WebViewOptions(
enableJavaScript: result[0]! as bool,
enableDomStorage: result[1]! as bool,
headers: (result[2] as Map<Object?, Object?>?)!.cast<String?, String?>(),
);
}
}
class BrowserOptions {
BrowserOptions({
required this.showTitle,
});
bool showTitle;
Object encode() {
return <Object?>[
showTitle,
];
}
static BrowserOptions decode(Object result) {
result as List<Object?>;
return BrowserOptions(
showTitle: result[0]! as bool,
);
}
}
class _UrlLauncherApiCodec extends StandardMessageCodec {
const _UrlLauncherApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is BrowserOptions) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is WebViewOptions) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return BrowserOptions.decode(readValue(buffer)!);
case 129:
return WebViewOptions.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class UrlLauncherApi {
/// Constructor for [UrlLauncherApi]. 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.
UrlLauncherApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _UrlLauncherApiCodec();
/// Returns true if the URL can definitely be launched.
Future<bool> canLaunchUrl(String arg_url) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.canLaunchUrl',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_url]) 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?)!;
}
}
/// Opens the URL externally, returning true if successful.
Future<bool> launchUrl(
String arg_url, Map<String?, String?> arg_headers) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.launchUrl',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[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 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?)!;
}
}
/// Opens the URL in an in-app WebView, returning true if it opens
/// successfully.
Future<bool> openUrlInApp(
String arg_url,
bool arg_allowCustomTab,
WebViewOptions arg_webViewOptions,
BrowserOptions arg_browserOptions) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.openUrlInApp',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(<Object?>[
arg_url,
arg_allowCustomTab,
arg_webViewOptions,
arg_browserOptions
]) 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> supportsCustomTabs() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.supportsCustomTabs',
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?)!;
}
}
/// Closes the view opened by [openUrlInSafariViewController].
Future<void> closeWebView() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.closeWebView',
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 {
return;
}
}
}
| packages/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart",
"repo_id": "packages",
"token_count": 3065
} | 1,106 |
// 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:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'src/messages.g.dart';
/// An implementation of [UrlLauncherPlatform] for macOS.
class UrlLauncherMacOS extends UrlLauncherPlatform {
/// Creates a new plugin implementation instance.
UrlLauncherMacOS({
@visibleForTesting UrlLauncherApi? api,
}) : _hostApi = api ?? UrlLauncherApi();
final UrlLauncherApi _hostApi;
/// Registers this class as the default instance of [UrlLauncherPlatform].
static void registerWith() {
UrlLauncherPlatform.instance = UrlLauncherMacOS();
}
@override
final LinkDelegate? linkDelegate = null;
@override
Future<bool> canLaunch(String url) async {
final UrlLauncherBoolResult result = await _hostApi.canLaunchUrl(url);
switch (result.error) {
case UrlLauncherError.invalidUrl:
throw _getInvalidUrlException(url);
case null:
}
return result.value;
}
@override
Future<bool> launch(
String url, {
required bool useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
String? webOnlyWindowName,
}) async {
final UrlLauncherBoolResult result = await _hostApi.launchUrl(url);
switch (result.error) {
case UrlLauncherError.invalidUrl:
throw _getInvalidUrlException(url);
case null:
}
return result.value;
}
@override
Future<bool> supportsMode(PreferredLaunchMode mode) async {
return mode == PreferredLaunchMode.platformDefault ||
mode == PreferredLaunchMode.externalApplication;
}
@override
Future<bool> supportsCloseForMode(PreferredLaunchMode mode) async {
// No supported mode is closeable.
return false;
}
Exception _getInvalidUrlException(String url) {
// TODO(stuartmorgan): Make this an actual ArgumentError. This should be
// coordinated across all platforms as a breaking change to have them all
// return the same thing; currently it throws a PlatformException to
// preserve existing behavior.
return PlatformException(
code: 'argument_error',
message: 'Unable to parse URL',
details: 'Provided URL: $url');
}
}
| packages/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart",
"repo_id": "packages",
"token_count": 855
} | 1,107 |
// 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.
#ifndef RUNNER_RUN_LOOP_H_
#define RUNNER_RUN_LOOP_H_
#include <flutter/flutter_engine.h>
#include <chrono>
#include <set>
// A runloop that will service events for Flutter instances as well
// as native messages.
class RunLoop {
public:
RunLoop();
~RunLoop();
// Prevent copying
RunLoop(RunLoop const&) = delete;
RunLoop& operator=(RunLoop const&) = delete;
// Runs the run loop until the application quits.
void Run();
// Registers the given Flutter instance for event servicing.
void RegisterFlutterInstance(flutter::FlutterEngine* flutter_instance);
// Unregisters the given Flutter instance from event servicing.
void UnregisterFlutterInstance(flutter::FlutterEngine* flutter_instance);
private:
using TimePoint = std::chrono::steady_clock::time_point;
// Processes all currently pending messages for registered Flutter instances.
TimePoint ProcessFlutterMessages();
std::set<flutter::FlutterEngine*> flutter_instances_;
};
#endif // RUNNER_RUN_LOOP_H_
| packages/packages/url_launcher/url_launcher_windows/example/windows/runner/run_loop.h/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_windows/example/windows/runner/run_loop.h",
"repo_id": "packages",
"token_count": 351
} | 1,108 |
// 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 (v13.0.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#ifndef PIGEON_MESSAGES_G_H_
#define PIGEON_MESSAGES_G_H_
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
namespace url_launcher_windows {
// Generated class from Pigeon.
class FlutterError {
public:
explicit FlutterError(const std::string& code) : code_(code) {}
explicit FlutterError(const std::string& code, const std::string& message)
: code_(code), message_(message) {}
explicit FlutterError(const std::string& code, const std::string& message,
const flutter::EncodableValue& details)
: code_(code), message_(message), details_(details) {}
const std::string& code() const { return code_; }
const std::string& message() const { return message_; }
const flutter::EncodableValue& details() const { return details_; }
private:
std::string code_;
std::string message_;
flutter::EncodableValue details_;
};
template <class T>
class ErrorOr {
public:
ErrorOr(const T& rhs) : v_(rhs) {}
ErrorOr(const T&& rhs) : v_(std::move(rhs)) {}
ErrorOr(const FlutterError& rhs) : v_(rhs) {}
ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {}
bool has_error() const { return std::holds_alternative<FlutterError>(v_); }
const T& value() const { return std::get<T>(v_); };
const FlutterError& error() const { return std::get<FlutterError>(v_); };
private:
friend class UrlLauncherApi;
ErrorOr() = default;
T TakeValue() && { return std::get<T>(std::move(v_)); }
std::variant<T, FlutterError> v_;
};
// Generated interface from Pigeon that represents a handler of messages from
// Flutter.
class UrlLauncherApi {
public:
UrlLauncherApi(const UrlLauncherApi&) = delete;
UrlLauncherApi& operator=(const UrlLauncherApi&) = delete;
virtual ~UrlLauncherApi() {}
virtual ErrorOr<bool> CanLaunchUrl(const std::string& url) = 0;
virtual ErrorOr<bool> LaunchUrl(const std::string& url) = 0;
// The codec used by UrlLauncherApi.
static const flutter::StandardMessageCodec& GetCodec();
// Sets up an instance of `UrlLauncherApi` to handle messages through the
// `binary_messenger`.
static void SetUp(flutter::BinaryMessenger* binary_messenger,
UrlLauncherApi* api);
static flutter::EncodableValue WrapError(std::string_view error_message);
static flutter::EncodableValue WrapError(const FlutterError& error);
protected:
UrlLauncherApi() = default;
};
} // namespace url_launcher_windows
#endif // PIGEON_MESSAGES_G_H_
| packages/packages/url_launcher/url_launcher_windows/windows/messages.g.h/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_windows/windows/messages.g.h",
"repo_id": "packages",
"token_count": 1007
} | 1,109 |
name: video_player
description: Flutter plugin for displaying inline video with other Flutter
widgets on Android, iOS, and web.
repository: https://github.com/flutter/packages/tree/main/packages/video_player/video_player
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
version: 2.8.3
environment:
sdk: ">=3.1.0 <4.0.0"
flutter: ">=3.13.0"
flutter:
plugin:
platforms:
android:
default_package: video_player_android
ios:
default_package: video_player_avfoundation
macos:
default_package: video_player_avfoundation
web:
default_package: video_player_web
dependencies:
flutter:
sdk: flutter
html: ^0.15.0
video_player_android: ^2.3.5
video_player_avfoundation: ^2.5.0
video_player_platform_interface: ">=6.1.0 <7.0.0"
video_player_web: ^2.0.0
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- video
- video-player
| packages/packages/video_player/video_player/pubspec.yaml/0 | {
"file_path": "packages/packages/video_player/video_player/pubspec.yaml",
"repo_id": "packages",
"token_count": 410
} | 1,110 |
// 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.videoplayer;
import io.flutter.plugin.common.EventChannel;
import java.util.ArrayList;
/**
* And implementation of {@link EventChannel.EventSink} which can wrap an underlying sink.
*
* <p>It delivers messages immediately when downstream is available, but it queues messages before
* the delegate event sink is set with setDelegate.
*
* <p>This class is not thread-safe. All calls must be done on the same thread or synchronized
* externally.
*/
final class QueuingEventSink implements EventChannel.EventSink {
private EventChannel.EventSink delegate;
private final ArrayList<Object> eventQueue = new ArrayList<>();
private boolean done = false;
public void setDelegate(EventChannel.EventSink delegate) {
this.delegate = delegate;
maybeFlush();
}
@Override
public void endOfStream() {
enqueue(new EndOfStreamEvent());
maybeFlush();
done = true;
}
@Override
public void error(String code, String message, Object details) {
enqueue(new ErrorEvent(code, message, details));
maybeFlush();
}
@Override
public void success(Object event) {
enqueue(event);
maybeFlush();
}
private void enqueue(Object event) {
if (done) {
return;
}
eventQueue.add(event);
}
private void maybeFlush() {
if (delegate == null) {
return;
}
for (Object event : eventQueue) {
if (event instanceof EndOfStreamEvent) {
delegate.endOfStream();
} else if (event instanceof ErrorEvent) {
ErrorEvent errorEvent = (ErrorEvent) event;
delegate.error(errorEvent.code, errorEvent.message, errorEvent.details);
} else {
delegate.success(event);
}
}
eventQueue.clear();
}
static class EndOfStreamEvent {}
private static class ErrorEvent {
String code;
String message;
Object details;
ErrorEvent(String code, String message, Object details) {
this.code = code;
this.message = message;
this.details = details;
}
}
}
| packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/QueuingEventSink.java/0 | {
"file_path": "packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/QueuingEventSink.java",
"repo_id": "packages",
"token_count": 726
} | 1,111 |
name: video_player_example
description: Demonstrates how to use the video_player plugin.
publish_to: none
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
flutter:
sdk: flutter
video_player_android:
# When depending on this package from a real application you should use:
# video_player_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: ../
video_player_platform_interface: ">=6.1.0 <7.0.0"
dev_dependencies:
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
| packages/packages/video_player/video_player_android/example/pubspec.yaml/0 | {
"file_path": "packages/packages/video_player/video_player_android/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 323
} | 1,112 |
// 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 <AVFoundation/AVFoundation.h>
/// Returns a standardized transform
/// according to the orientation of the track.
///
/// Note: https://stackoverflow.com/questions/64161544
/// `AVAssetTrack.preferredTransform` can have wrong `tx` and `ty`.
CGAffineTransform FVPGetStandardizedTransformForTrack(AVAssetTrack* track);
| packages/packages/video_player/video_player_avfoundation/darwin/Classes/AVAssetTrackUtils.h/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/AVAssetTrackUtils.h",
"repo_id": "packages",
"token_count": 136
} | 1,113 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 6.2.2
* Updates minimum required plugin_platform_interface version to 2.1.7.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 6.2.1
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 6.2.0
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
* Adds web options to customize control's list and displaying context menu.
## 6.1.0
* Aligns Dart and Flutter SDK constraints.
* Adds the `VideoEventType.isPlayingStateUpdate` event to track changes in play / pause state with
the underlying video player.
## 6.0.2
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 6.0.1
* Fixes comment describing file URI construction.
## 6.0.0
* **BREAKING CHANGE**: Removes `MethodChannelVideoPlayer`. The default
implementation is now only a placeholder with no functionality;
implementations of `video_player` must include their own `VideoPlayerPlatform`
Dart implementation.
* Updates minimum Flutter version to 2.10.
* Fixes violations of new analysis option use_named_constants.
## 5.1.4
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 5.1.3
* Updates references to the obsolete master branch.
* Removes unnecessary imports.
## 5.1.2
* Adopts `Object.hash`.
* Removes obsolete dependency on `pedantic`.
## 5.1.1
* Adds `rotationCorrection` (for Android playing videos recorded in landscapeRight [#60327](https://github.com/flutter/flutter/issues/60327)).
## 5.1.0
* Adds `allowBackgroundPlayback` to `VideoPlayerOptions`.
## 5.0.2
* Adds the Pigeon definitions used to create the method channel implementation.
* Internal code cleanup for stricter analysis options.
## 5.0.1
* Update to use the `verify` method introduced in platform_plugin_interface 2.1.0.
## 5.0.0
* **BREAKING CHANGES**:
* Updates to extending `PlatformInterface`. Removes `isMock`, in favor of the
now-standard `MockPlatformInterfaceMixin`.
* Removes test.dart from the public interface. Tests in other packages should
mock `VideoPlatformInterface` rather than the method channel.
## 4.2.0
* Add `contentUri` to `DataSourceType`.
## 4.1.0
* Add `httpHeaders` to `DataSource`
## 4.0.0
* **Breaking Changes**:
* Migrate to null-safety
* Update to latest Pigeon. This includes a breaking change to how the test logic is exposed.
* Add note about the `mixWithOthers` option being ignored on the web.
* Make DataSource's `uri` parameter nullable.
* `messages.dart` sets Dart `2.12`.
## 3.0.0
* Version 3 only was published as nullsafety "previews".
## 2.2.1
* Update Flutter SDK constraint.
## 2.2.0
* Added option to set the video playback speed on the video controller.
## 2.1.1
* Fix mixWithOthers test channel.
## 2.1.0
* Add VideoPlayerOptions with audio mix mode
## 2.0.2
* Migrated tests to use pigeon correctly.
## 2.0.1
* Updated minimum Dart version.
* Added class to help testing Pigeon communication.
## 2.0.0
* Migrated to [pigeon](https://pub.dev/packages/pigeon).
## 1.0.5
* Make the pedantic dev_dependency explicit.
## 1.0.4
* Remove the deprecated `author:` field from pubspec.yaml
* Require Flutter SDK 1.10.0 or greater.
## 1.0.3
* Document public API.
## 1.0.2
* Fix unawaited futures in the tests.
## 1.0.1
* Return correct platform event type when buffering
## 1.0.0
* Initial release.
| packages/packages/video_player/video_player_platform_interface/CHANGELOG.md/0 | {
"file_path": "packages/packages/video_player/video_player_platform_interface/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1149
} | 1,114 |
// 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:js_interop';
import 'package:web/web.dart' as web;
import 'pkg_web_tweaks.dart';
// Returns the URL to load an asset from this example app as a network source.
//
// TODO(stuartmorgan): Convert this to a local `HttpServer` that vends the
// assets directly, https://github.com/flutter/flutter/issues/95420
String getUrlForAssetAsNetworkSource(String assetKey) {
return 'https://github.com/flutter/packages/blob/'
// This hash can be rolled forward to pick up newly-added assets.
'2e1673307ff7454aff40b47024eaed49a9e77e81'
'/packages/video_player/video_player/example/'
'$assetKey'
'?raw=true';
}
/// Forces a VideoElement to report "Infinity" duration.
///
/// Uses JS Object.defineProperty to set the value of a readonly property.
void setInfinityDuration(web.HTMLVideoElement element) {
DomObject.defineProperty(
element,
'duration',
Descriptor.data(
writable: true,
value: double.infinity.toJS,
),
);
}
/// Makes the `currentTime` setter throw an exception if used.
void makeSetCurrentTimeThrow(web.HTMLVideoElement element) {
DomObject.defineProperty(
element,
'currentTime',
Descriptor.accessor(
set: (JSAny? value) {
throw Exception('Unexpected call to currentTime with value: $value');
},
get: () => 100.toJS,
));
}
| packages/packages/video_player/video_player_web/example/integration_test/utils.dart/0 | {
"file_path": "packages/packages/video_player/video_player_web/example/integration_test/utils.dart",
"repo_id": "packages",
"token_count": 546
} | 1,115 |
// 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:web_benchmarks/src/browser.dart';
import 'browser_test_json_samples.dart';
void main() {
group('BlinkTraceEvent works with Chrome 89+', () {
// Used to test 'false' results
final BlinkTraceEvent unrelatedPhX =
BlinkTraceEvent.fromJson(unrelatedPhXJson);
final BlinkTraceEvent anotherUnrelated =
BlinkTraceEvent.fromJson(anotherUnrelatedJson);
test('isBeginFrame', () {
final BlinkTraceEvent event =
BlinkTraceEvent.fromJson(beginMainFrameJson_89plus);
expect(event.isBeginFrame, isTrue);
expect(unrelatedPhX.isBeginFrame, isFalse);
expect(anotherUnrelated.isBeginFrame, isFalse);
});
test('isUpdateAllLifecyclePhases', () {
final BlinkTraceEvent event =
BlinkTraceEvent.fromJson(updateLifecycleJson_89plus);
expect(event.isUpdateAllLifecyclePhases, isTrue);
expect(unrelatedPhX.isUpdateAllLifecyclePhases, isFalse);
expect(anotherUnrelated.isUpdateAllLifecyclePhases, isFalse);
});
test('isBeginMeasuredFrame', () {
final BlinkTraceEvent event =
BlinkTraceEvent.fromJson(beginMeasuredFrameJson_89plus);
expect(event.isBeginMeasuredFrame, isTrue);
expect(unrelatedPhX.isBeginMeasuredFrame, isFalse);
expect(anotherUnrelated.isBeginMeasuredFrame, isFalse);
});
test('isEndMeasuredFrame', () {
final BlinkTraceEvent event =
BlinkTraceEvent.fromJson(endMeasuredFrameJson_89plus);
expect(event.isEndMeasuredFrame, isTrue);
expect(unrelatedPhX.isEndMeasuredFrame, isFalse);
expect(anotherUnrelated.isEndMeasuredFrame, isFalse);
});
});
}
| packages/packages/web_benchmarks/test/src/browser_test.dart/0 | {
"file_path": "packages/packages/web_benchmarks/test/src/browser_test.dart",
"repo_id": "packages",
"token_count": 702
} | 1,116 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.webviewflutterexample">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:usesCleartextTraffic="true">
<activity
android:name=".WebViewTestActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
</activity>
</application>
</manifest>
| packages/packages/webview_flutter/webview_flutter/example/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/example/android/app/src/debug/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 322
} | 1,117 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'navigation_delegate.dart';
import 'webview_widget.dart';
/// Controls a WebView provided by the host platform.
///
/// Pass this to a [WebViewWidget] to display the WebView.
///
/// A [WebViewController] can only be used by a single [WebViewWidget] at a
/// time.
///
/// ## Platform-Specific Features
/// This class contains an underlying implementation provided by the current
/// platform. Once a platform implementation is imported, the examples below
/// can be followed to use features provided by a platform's implementation.
///
/// {@macro webview_flutter.WebViewController.fromPlatformCreationParams}
///
/// Below is an example of accessing the platform-specific implementation for
/// iOS and Android:
///
/// ```dart
/// final WebViewController webViewController = WebViewController();
///
/// if (WebViewPlatform.instance is WebKitWebViewPlatform) {
/// final WebKitWebViewController webKitController =
/// webViewController.platform as WebKitWebViewController;
/// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
/// final AndroidWebViewController androidController =
/// webViewController.platform as AndroidWebViewController;
/// }
/// ```
class WebViewController {
/// Constructs a [WebViewController].
///
/// {@template webview_fluttter.WebViewController.constructor}
/// `onPermissionRequest`: A callback that notifies the host application that
/// web content is requesting permission to access the specified resources.
/// To grant access for a device resource, most platforms will need to update
/// their app configurations for the relevant system resource.
///
/// For Android, you will need to update your `AndroidManifest.xml`. See
/// https://developer.android.com/training/permissions/declaring
///
/// For iOS, you will need to update your `Info.plist`. See
/// https://developer.apple.com/documentation/uikit/protecting_the_user_s_privacy/requesting_access_to_protected_resources?language=objc.
/// {@endtemplate}
///
/// See [WebViewController.fromPlatformCreationParams] for setting parameters
/// for a specific platform.
WebViewController({
void Function(WebViewPermissionRequest request)? onPermissionRequest,
}) : this.fromPlatformCreationParams(
const PlatformWebViewControllerCreationParams(),
onPermissionRequest: onPermissionRequest,
);
/// Constructs a [WebViewController] from creation params for a specific
/// platform.
///
/// {@macro webview_fluttter.WebViewController.constructor}
///
/// {@template webview_flutter.WebViewController.fromPlatformCreationParams}
/// Below is an example of setting platform-specific creation parameters for
/// iOS and Android:
///
/// ```dart
/// PlatformWebViewControllerCreationParams params =
/// const PlatformWebViewControllerCreationParams();
///
/// if (WebViewPlatform.instance is WebKitWebViewPlatform) {
/// params = WebKitWebViewControllerCreationParams
/// .fromPlatformWebViewControllerCreationParams(
/// params,
/// );
/// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
/// params = AndroidWebViewControllerCreationParams
/// .fromPlatformWebViewControllerCreationParams(
/// params,
/// );
/// }
///
/// final WebViewController webViewController =
/// WebViewController.fromPlatformCreationParams(
/// params,
/// );
/// ```
/// {@endtemplate}
WebViewController.fromPlatformCreationParams(
PlatformWebViewControllerCreationParams params, {
void Function(WebViewPermissionRequest request)? onPermissionRequest,
}) : this.fromPlatform(
PlatformWebViewController(params),
onPermissionRequest: onPermissionRequest,
);
/// Constructs a [WebViewController] from a specific platform implementation.
///
/// {@macro webview_fluttter.WebViewController.constructor}
WebViewController.fromPlatform(
this.platform, {
void Function(WebViewPermissionRequest request)? onPermissionRequest,
}) {
if (onPermissionRequest != null) {
platform.setOnPlatformPermissionRequest(
(PlatformWebViewPermissionRequest request) {
onPermissionRequest(WebViewPermissionRequest._(
request,
types: request.types,
));
},
);
}
}
/// Implementation of [PlatformWebViewController] for the current platform.
final PlatformWebViewController platform;
/// Loads the file located on the specified [absoluteFilePath].
///
/// The [absoluteFilePath] parameter should contain the absolute path to the
/// file as it is stored on the device. For example:
/// `/Users/username/Documents/www/index.html`.
///
/// Throws a `PlatformException` if the [absoluteFilePath] does not exist.
Future<void> loadFile(String absoluteFilePath) {
return platform.loadFile(absoluteFilePath);
}
/// Loads the Flutter asset specified in the pubspec.yaml file.
///
/// Throws a `PlatformException` if [key] is not part of the specified assets
/// in the pubspec.yaml file.
Future<void> loadFlutterAsset(String key) {
assert(key.isNotEmpty);
return platform.loadFlutterAsset(key);
}
/// Loads the supplied HTML string.
///
/// The [baseUrl] parameter is used when resolving relative URLs within the
/// HTML string.
Future<void> loadHtmlString(String html, {String? baseUrl}) {
assert(html.isNotEmpty);
return platform.loadHtmlString(html, baseUrl: baseUrl);
}
/// Makes a specific HTTP request and loads the response in the webview.
///
/// [method] must be one of the supported HTTP methods in [LoadRequestMethod].
///
/// If [headers] is not empty, its key-value pairs will be added as the
/// headers for the request.
///
/// If [body] is not null, it will be added as the body for the request.
///
/// Throws an ArgumentError if [uri] has an empty scheme.
Future<void> loadRequest(
Uri uri, {
LoadRequestMethod method = LoadRequestMethod.get,
Map<String, String> headers = const <String, String>{},
Uint8List? body,
}) {
if (uri.scheme.isEmpty) {
throw ArgumentError('Missing scheme in uri: $uri');
}
return platform.loadRequest(LoadRequestParams(
uri: uri,
method: method,
headers: headers,
body: body,
));
}
/// Returns the current URL that the WebView is displaying.
///
/// If no URL was ever loaded, returns `null`.
Future<String?> currentUrl() {
return platform.currentUrl();
}
/// Checks whether there's a back history item.
Future<bool> canGoBack() {
return platform.canGoBack();
}
/// Checks whether there's a forward history item.
Future<bool> canGoForward() {
return platform.canGoForward();
}
/// Goes back in the history of this WebView.
///
/// If there is no back history item this is a no-op.
Future<void> goBack() {
return platform.goBack();
}
/// Goes forward in the history of this WebView.
///
/// If there is no forward history item this is a no-op.
Future<void> goForward() {
return platform.goForward();
}
/// Reloads the current URL.
Future<void> reload() {
return platform.reload();
}
/// Sets the [NavigationDelegate] containing the callback methods that are
/// called during navigation events.
Future<void> setNavigationDelegate(NavigationDelegate delegate) {
return platform.setPlatformNavigationDelegate(delegate.platform);
}
/// Clears all caches used by the WebView.
///
/// The following caches are cleared:
/// 1. Browser HTTP Cache.
/// 2. [Cache API](https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/cache-api)
/// caches. Service workers tend to use this cache.
/// 3. Application cache.
Future<void> clearCache() {
return platform.clearCache();
}
/// Clears the local storage used by the WebView.
Future<void> clearLocalStorage() {
return platform.clearLocalStorage();
}
/// Runs the given JavaScript in the context of the current page.
///
/// The Future completes with an error if a JavaScript error occurred.
Future<void> runJavaScript(String javaScript) {
return platform.runJavaScript(javaScript);
}
/// Runs the given JavaScript in the context of the current page, and returns
/// the result.
///
/// The Future completes with an error if a JavaScript error occurred, or if
/// the type the given expression evaluates to is unsupported. Unsupported
/// values include certain non-primitive types on iOS, as well as `undefined`
/// or `null` on iOS 14+.
Future<Object> runJavaScriptReturningResult(String javaScript) {
return platform.runJavaScriptReturningResult(javaScript);
}
/// Adds a new JavaScript channel to the set of enabled channels.
///
/// The JavaScript code can then call `postMessage` on that object to send a
/// message that will be passed to [onMessageReceived].
///
/// For example, after adding the following JavaScript channel:
///
/// ```dart
/// final WebViewController controller = WebViewController();
/// controller.addJavaScriptChannel(
/// 'Print',
/// onMessageReceived: (JavaScriptMessage message) {
/// print(message.message);
/// },
/// );
/// ```
///
/// JavaScript code can call:
///
/// ```javascript
/// Print.postMessage('Hello');
/// ```
///
/// to asynchronously invoke the message handler which will print the message
/// to standard output.
///
/// Adding a new JavaScript channel only takes effect after the next page is
/// loaded.
///
/// A channel [name] cannot be the same for multiple channels.
Future<void> addJavaScriptChannel(
String name, {
required void Function(JavaScriptMessage) onMessageReceived,
}) {
assert(name.isNotEmpty);
return platform.addJavaScriptChannel(JavaScriptChannelParams(
name: name,
onMessageReceived: onMessageReceived,
));
}
/// Removes the JavaScript channel with the matching name from the set of
/// enabled channels.
///
/// This disables the channel with the matching name if it was previously
/// enabled through the [addJavaScriptChannel].
Future<void> removeJavaScriptChannel(String javaScriptChannelName) {
return platform.removeJavaScriptChannel(javaScriptChannelName);
}
/// The title of the currently loaded page.
Future<String?> getTitle() {
return platform.getTitle();
}
/// Sets the scrolled position of this view.
///
/// The parameters `x` and `y` specify the position to scroll to in WebView
/// pixels.
Future<void> scrollTo(int x, int y) {
return platform.scrollTo(x, y);
}
/// Moves the scrolled position of this view.
///
/// The parameters `x` and `y` specify the amount of WebView pixels to scroll
/// by.
Future<void> scrollBy(int x, int y) {
return platform.scrollBy(x, y);
}
/// Returns the current scroll position of this view.
///
/// Scroll position is measured from the top left.
Future<Offset> getScrollPosition() {
return platform.getScrollPosition();
}
/// Whether to support zooming using the on-screen zoom controls and gestures.
Future<void> enableZoom(bool enabled) {
return platform.enableZoom(enabled);
}
/// Sets the current background color of this view.
Future<void> setBackgroundColor(Color color) {
return platform.setBackgroundColor(color);
}
/// Sets the JavaScript execution mode to be used by the WebView.
Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) {
return platform.setJavaScriptMode(javaScriptMode);
}
/// Sets the value used for the HTTP `User-Agent:` request header.
Future<void> setUserAgent(String? userAgent) {
return platform.setUserAgent(userAgent);
}
/// Sets a callback that notifies the host application on any log messages
/// written to the JavaScript console.
///
/// Platforms may not preserve all the log level information so clients should
/// not rely on a 1:1 mapping between the JavaScript calls.
///
/// On iOS setting this callback will inject a custom [WKUserScript] which
/// overrides the default implementation of `console.debug`, `console.error`,
/// `console.info`, `console.log` and `console.warning` methods. The iOS
/// WebKit framework unfortunately doesn't provide a built-in method to
/// forward console messages.
Future<void> setOnConsoleMessage(
void Function(JavaScriptConsoleMessage message) onConsoleMessage) {
return platform.setOnConsoleMessage(onConsoleMessage);
}
/// Sets a callback that notifies the host application that the web page
/// wants to display a JavaScript alert() dialog.
Future<void> setOnJavaScriptAlertDialog(
Future<void> Function(JavaScriptAlertDialogRequest request)
onJavaScriptAlertDialog) async {
return platform.setOnJavaScriptAlertDialog(onJavaScriptAlertDialog);
}
/// Sets a callback that notifies the host application that the web page
/// wants to display a JavaScript confirm() dialog.
Future<void> setOnJavaScriptConfirmDialog(
Future<bool> Function(JavaScriptConfirmDialogRequest request)
onJavaScriptConfirmDialog) async {
return platform.setOnJavaScriptConfirmDialog(onJavaScriptConfirmDialog);
}
/// Sets a callback that notifies the host application that the web page
/// wants to display a JavaScript prompt() dialog.
Future<void> setOnJavaScriptTextInputDialog(
Future<String> Function(JavaScriptTextInputDialogRequest request)
onJavaScriptTextInputDialog) async {
return platform.setOnJavaScriptTextInputDialog(onJavaScriptTextInputDialog);
}
/// Gets the value used for the HTTP `User-Agent:` request header.
Future<String?> getUserAgent() {
return platform.getUserAgent();
}
/// Sets a listener for scroll position changes.
Future<void> setOnScrollPositionChange(
void Function(ScrollPositionChange change)? onScrollPositionChange,
) {
return platform.setOnScrollPositionChange(onScrollPositionChange);
}
}
/// Permissions request when web content requests access to protected resources.
///
/// A response MUST be provided by calling [grant], [deny], or a method from
/// [platform].
///
/// ## Platform-Specific Features
/// This class contains an underlying implementation provided by the current
/// platform. Once a platform implementation is imported, the example below
/// can be followed to use features provided by a platform's implementation.
///
/// Below is an example of accessing the platform-specific implementation for
/// iOS and Android:
///
/// ```dart
/// final WebViewPermissionRequest request = ...;
///
/// if (WebViewPlatform.instance is WebKitWebViewPlatform) {
/// final WebKitWebViewPermissionRequest webKitRequest =
/// request.platform as WebKitWebViewPermissionRequest;
/// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
/// final AndroidWebViewPermissionRequest androidRequest =
/// request.platform as AndroidWebViewPermissionRequest;
/// }
/// ```
@immutable
class WebViewPermissionRequest {
const WebViewPermissionRequest._(this.platform, {required this.types});
/// All resources access has been requested for.
final Set<WebViewPermissionResourceType> types;
/// Implementation of [PlatformWebViewPermissionRequest] for the current
/// platform.
final PlatformWebViewPermissionRequest platform;
/// Grant permission for the requested resource(s).
Future<void> grant() {
return platform.grant();
}
/// Deny permission for the requested resource(s).
Future<void> deny() {
return platform.deny();
}
}
| packages/packages/webview_flutter/webview_flutter/lib/src/webview_controller.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/lib/src/webview_controller.dart",
"repo_id": "packages",
"token_count": 4637
} | 1,118 |
// Mocks generated by Mockito 5.4.4 from annotations
// in webview_flutter/test/webview_widget_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i7;
import 'dart:ui' as _i3;
import 'package:flutter/foundation.dart' as _i5;
import 'package:flutter/widgets.dart' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_platform_interface/src/platform_navigation_delegate.dart'
as _i8;
import 'package:webview_flutter_platform_interface/src/platform_webview_controller.dart'
as _i6;
import 'package:webview_flutter_platform_interface/src/platform_webview_widget.dart'
as _i9;
import 'package:webview_flutter_platform_interface/src/types/types.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakePlatformWebViewControllerCreationParams_0 extends _i1.SmartFake
implements _i2.PlatformWebViewControllerCreationParams {
_FakePlatformWebViewControllerCreationParams_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeObject_1 extends _i1.SmartFake implements Object {
_FakeObject_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeOffset_2 extends _i1.SmartFake implements _i3.Offset {
_FakeOffset_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePlatformWebViewWidgetCreationParams_3 extends _i1.SmartFake
implements _i2.PlatformWebViewWidgetCreationParams {
_FakePlatformWebViewWidgetCreationParams_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWidget_4 extends _i1.SmartFake implements _i4.Widget {
_FakeWidget_4(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
@override
String toString({_i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) =>
super.toString();
}
/// A class which mocks [PlatformWebViewController].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformWebViewController extends _i1.Mock
implements _i6.PlatformWebViewController {
MockPlatformWebViewController() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformWebViewControllerCreationParams_0(
this,
Invocation.getter(#params),
),
) as _i2.PlatformWebViewControllerCreationParams);
@override
_i7.Future<void> loadFile(String? absoluteFilePath) => (super.noSuchMethod(
Invocation.method(
#loadFile,
[absoluteFilePath],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod(
Invocation.method(
#loadFlutterAsset,
[key],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> loadHtmlString(
String? html, {
String? baseUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadHtmlString,
[html],
{#baseUrl: baseUrl},
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> loadRequest(_i2.LoadRequestParams? params) =>
(super.noSuchMethod(
Invocation.method(
#loadRequest,
[params],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<String?> currentUrl() => (super.noSuchMethod(
Invocation.method(
#currentUrl,
[],
),
returnValue: _i7.Future<String?>.value(),
) as _i7.Future<String?>);
@override
_i7.Future<bool> canGoBack() => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[],
),
returnValue: _i7.Future<bool>.value(false),
) as _i7.Future<bool>);
@override
_i7.Future<bool> canGoForward() => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[],
),
returnValue: _i7.Future<bool>.value(false),
) as _i7.Future<bool>);
@override
_i7.Future<void> goBack() => (super.noSuchMethod(
Invocation.method(
#goBack,
[],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> goForward() => (super.noSuchMethod(
Invocation.method(
#goForward,
[],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> clearCache() => (super.noSuchMethod(
Invocation.method(
#clearCache,
[],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> clearLocalStorage() => (super.noSuchMethod(
Invocation.method(
#clearLocalStorage,
[],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setPlatformNavigationDelegate(
_i8.PlatformNavigationDelegate? handler) =>
(super.noSuchMethod(
Invocation.method(
#setPlatformNavigationDelegate,
[handler],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> runJavaScript(String? javaScript) => (super.noSuchMethod(
Invocation.method(
#runJavaScript,
[javaScript],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<Object> runJavaScriptReturningResult(String? javaScript) =>
(super.noSuchMethod(
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
returnValue: _i7.Future<Object>.value(_FakeObject_1(
this,
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
)),
) as _i7.Future<Object>);
@override
_i7.Future<void> addJavaScriptChannel(
_i6.JavaScriptChannelParams? javaScriptChannelParams) =>
(super.noSuchMethod(
Invocation.method(
#addJavaScriptChannel,
[javaScriptChannelParams],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> removeJavaScriptChannel(String? javaScriptChannelName) =>
(super.noSuchMethod(
Invocation.method(
#removeJavaScriptChannel,
[javaScriptChannelName],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<String?> getTitle() => (super.noSuchMethod(
Invocation.method(
#getTitle,
[],
),
returnValue: _i7.Future<String?>.value(),
) as _i7.Future<String?>);
@override
_i7.Future<void> scrollTo(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollTo,
[
x,
y,
],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> scrollBy(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollBy,
[
x,
y,
],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<_i3.Offset> getScrollPosition() => (super.noSuchMethod(
Invocation.method(
#getScrollPosition,
[],
),
returnValue: _i7.Future<_i3.Offset>.value(_FakeOffset_2(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
) as _i7.Future<_i3.Offset>);
@override
_i7.Future<void> enableZoom(bool? enabled) => (super.noSuchMethod(
Invocation.method(
#enableZoom,
[enabled],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setBackgroundColor(_i3.Color? color) => (super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[color],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setJavaScriptMode(_i2.JavaScriptMode? javaScriptMode) =>
(super.noSuchMethod(
Invocation.method(
#setJavaScriptMode,
[javaScriptMode],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setUserAgent(String? userAgent) => (super.noSuchMethod(
Invocation.method(
#setUserAgent,
[userAgent],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setOnPlatformPermissionRequest(
void Function(_i2.PlatformWebViewPermissionRequest)?
onPermissionRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnPlatformPermissionRequest,
[onPermissionRequest],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<String?> getUserAgent() => (super.noSuchMethod(
Invocation.method(
#getUserAgent,
[],
),
returnValue: _i7.Future<String?>.value(),
) as _i7.Future<String?>);
@override
_i7.Future<void> setOnConsoleMessage(
void Function(_i2.JavaScriptConsoleMessage)? onConsoleMessage) =>
(super.noSuchMethod(
Invocation.method(
#setOnConsoleMessage,
[onConsoleMessage],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setOnScrollPositionChange(
void Function(_i2.ScrollPositionChange)? onScrollPositionChange) =>
(super.noSuchMethod(
Invocation.method(
#setOnScrollPositionChange,
[onScrollPositionChange],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setOnJavaScriptAlertDialog(
_i7.Future<void> Function(_i2.JavaScriptAlertDialogRequest)?
onJavaScriptAlertDialog) =>
(super.noSuchMethod(
Invocation.method(
#setOnJavaScriptAlertDialog,
[onJavaScriptAlertDialog],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setOnJavaScriptConfirmDialog(
_i7.Future<bool> Function(_i2.JavaScriptConfirmDialogRequest)?
onJavaScriptConfirmDialog) =>
(super.noSuchMethod(
Invocation.method(
#setOnJavaScriptConfirmDialog,
[onJavaScriptConfirmDialog],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
@override
_i7.Future<void> setOnJavaScriptTextInputDialog(
_i7.Future<String> Function(_i2.JavaScriptTextInputDialogRequest)?
onJavaScriptTextInputDialog) =>
(super.noSuchMethod(
Invocation.method(
#setOnJavaScriptTextInputDialog,
[onJavaScriptTextInputDialog],
),
returnValue: _i7.Future<void>.value(),
returnValueForMissingStub: _i7.Future<void>.value(),
) as _i7.Future<void>);
}
/// A class which mocks [PlatformWebViewWidget].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformWebViewWidget extends _i1.Mock
implements _i9.PlatformWebViewWidget {
MockPlatformWebViewWidget() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformWebViewWidgetCreationParams get params => (super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformWebViewWidgetCreationParams_3(
this,
Invocation.getter(#params),
),
) as _i2.PlatformWebViewWidgetCreationParams);
@override
_i4.Widget build(_i4.BuildContext? context) => (super.noSuchMethod(
Invocation.method(
#build,
[context],
),
returnValue: _FakeWidget_4(
this,
Invocation.method(
#build,
[context],
),
),
) as _i4.Widget);
}
| packages/packages/webview_flutter/webview_flutter/test/webview_widget_test.mocks.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/test/webview_widget_test.mocks.dart",
"repo_id": "packages",
"token_count": 6799
} | 1,119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.