text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
export 'assets.gen.dart';
| pinball/packages/pinball_ui/lib/gen/gen.dart/0 | {
"file_path": "pinball/packages/pinball_ui/lib/gen/gen.dart",
"repo_id": "pinball",
"token_count": 10
} | 1,112 |
name: pinball_ui
description: UI Toolkit for the Pinball Flutter Application
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
url_launcher: ^6.1.0
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
test: ^1.19.2
very_good_analysis: ^2.4.0
flutter:
uses-material-design: true
generate: true
assets:
- assets/images/dialog/
- assets/images/button/
fonts:
- family: PixeloidSans
fonts:
- asset: fonts/PixeloidSans-nR3g1.ttf
- asset: fonts/PixeloidSansBold-RpeJo.ttf
weight: 700
- family: PixeloidMono
fonts:
- asset: fonts/PixeloidMono-1G8ae.ttf
flutter_gen:
line_length: 80
assets:
package_parameter_enabled: true
| pinball/packages/pinball_ui/pubspec.yaml/0 | {
"file_path": "pinball/packages/pinball_ui/pubspec.yaml",
"repo_id": "pinball",
"token_count": 358
} | 1,113 |
import 'package:flutter/foundation.dart';
/// {@template platform_helper}
/// Returns whether the current platform is running on a mobile device.
/// {@endtemplate}
class PlatformHelper {
/// {@macro platform_helper}
bool get isMobile {
return defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.android;
}
}
| pinball/packages/platform_helper/lib/src/platform_helper.dart/0 | {
"file_path": "pinball/packages/platform_helper/lib/src/platform_helper.dart",
"repo_id": "pinball",
"token_count": 105
} | 1,114 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/assets_manager/assets_manager.dart';
void main() {
group('AssetsManagerState', () {
test('can be instantiated', () {
expect(
AssetsManagerState(assetsCount: 0, loaded: 0),
isNotNull,
);
});
test('has the correct initial state', () {
expect(
AssetsManagerState.initial(),
equals(
AssetsManagerState(
assetsCount: 0,
loaded: 0,
),
),
);
});
group('progress', () {
test('returns 0 when no future is loaded', () {
expect(
AssetsManagerState(
assetsCount: 2,
loaded: 0,
).progress,
equals(0),
);
});
test('returns the correct value when some of the futures are loaded', () {
expect(
AssetsManagerState(
assetsCount: 2,
loaded: 1,
).progress,
equals(0.5),
);
});
test('returns the 1 when all futures are loaded', () {
expect(
AssetsManagerState(
assetsCount: 2,
loaded: 2,
).progress,
equals(1),
);
});
});
group('copyWith', () {
test('returns a copy with the updated assetsCount', () {
expect(
AssetsManagerState(
assetsCount: 0,
loaded: 0,
).copyWith(assetsCount: 1),
equals(
AssetsManagerState(
assetsCount: 1,
loaded: 0,
),
),
);
});
test('returns a copy with the updated loaded', () {
expect(
AssetsManagerState(
assetsCount: 0,
loaded: 0,
).copyWith(loaded: 1),
equals(
AssetsManagerState(
assetsCount: 0,
loaded: 1,
),
),
);
});
});
test('supports value comparison', () {
expect(
AssetsManagerState(
assetsCount: 0,
loaded: 0,
),
equals(
AssetsManagerState(
assetsCount: 0,
loaded: 0,
),
),
);
expect(
AssetsManagerState(
assetsCount: 1,
loaded: 0,
),
isNot(
equals(
AssetsManagerState(
assetsCount: 1,
loaded: 1,
),
),
),
);
});
});
}
| pinball/test/assets_manager/cubit/assets_manager_state_test.dart/0 | {
"file_path": "pinball/test/assets_manager/cubit/assets_manager_state_test.dart",
"repo_id": "pinball",
"token_count": 1394
} | 1,115 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.android.spaceship.saucer.keyName,
Assets.images.android.spaceship.animatronic.keyName,
Assets.images.android.spaceship.lightBeam.keyName,
Assets.images.android.ramp.boardOpening.keyName,
Assets.images.android.ramp.railingForeground.keyName,
Assets.images.android.ramp.railingBackground.keyName,
Assets.images.android.ramp.main.keyName,
Assets.images.android.ramp.arrow.inactive.keyName,
Assets.images.android.ramp.arrow.active1.keyName,
Assets.images.android.ramp.arrow.active2.keyName,
Assets.images.android.ramp.arrow.active3.keyName,
Assets.images.android.ramp.arrow.active4.keyName,
Assets.images.android.ramp.arrow.active5.keyName,
Assets.images.android.rail.main.keyName,
Assets.images.android.rail.exit.keyName,
Assets.images.android.bumper.a.lit.keyName,
Assets.images.android.bumper.a.dimmed.keyName,
Assets.images.android.bumper.b.lit.keyName,
Assets.images.android.bumper.b.dimmed.keyName,
Assets.images.android.bumper.cow.lit.keyName,
Assets.images.android.bumper.cow.dimmed.keyName,
]);
}
Future<void> pump(AndroidAcres child) async {
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: GameBloc(),
children: [child],
),
);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('AndroidAcres', () {
final flameTester = FlameTester(_TestGame.new);
flameTester.test('loads correctly', (game) async {
final component = AndroidAcres();
await game.pump(component);
expect(game.descendants(), contains(component));
});
group('loads', () {
flameTester.test(
'an AndroidSpaceship',
(game) async {
await game.pump(AndroidAcres());
expect(
game.descendants().whereType<AndroidSpaceship>().length,
equals(1),
);
},
);
flameTester.test(
'an AndroidAnimatronic',
(game) async {
await game.pump(AndroidAcres());
expect(
game.descendants().whereType<AndroidAnimatronic>().length,
equals(1),
);
},
);
flameTester.test(
'a SpaceshipRamp',
(game) async {
await game.pump(AndroidAcres());
expect(
game.descendants().whereType<SpaceshipRamp>().length,
equals(1),
);
},
);
flameTester.test(
'a SpaceshipRail',
(game) async {
await game.pump(AndroidAcres());
expect(
game.descendants().whereType<SpaceshipRail>().length,
equals(1),
);
},
);
flameTester.test(
'three AndroidBumper',
(game) async {
await game.pump(AndroidAcres());
expect(
game.descendants().whereType<AndroidBumper>().length,
equals(3),
);
},
);
flameTester.test(
'three AndroidBumpers with BumperNoiseBehavior',
(game) async {
await game.pump(AndroidAcres());
final bumpers = game.descendants().whereType<AndroidBumper>();
for (final bumper in bumpers) {
expect(
bumper.firstChild<BumperNoiseBehavior>(),
isA<BumperNoiseBehavior>(),
);
}
},
);
flameTester.test(
'one AndroidBumper with CowBumperNoiseBehavior',
(game) async {
await game.pump(AndroidAcres());
final bumpers = game.descendants().whereType<AndroidBumper>();
expect(
bumpers.singleWhere(
(bumper) => bumper.firstChild<CowBumperNoiseBehavior>() != null,
),
isA<AndroidBumper>(),
);
},
);
});
flameTester.test('adds a FlameBlocProvider', (game) async {
final androidAcres = AndroidAcres();
await game.pump(androidAcres);
expect(
androidAcres.children
.whereType<
FlameBlocProvider<AndroidSpaceshipCubit,
AndroidSpaceshipState>>()
.single,
isNotNull,
);
});
flameTester.test('adds an AndroidSpaceshipBonusBehavior', (game) async {
final androidAcres = AndroidAcres();
await game.pump(androidAcres);
final provider = androidAcres.children
.whereType<
FlameBlocProvider<AndroidSpaceshipCubit, AndroidSpaceshipState>>()
.single;
expect(
provider.children.whereType<AndroidSpaceshipBonusBehavior>().single,
isNotNull,
);
});
});
}
| pinball/test/game/components/android_acres/android_acres_test.dart/0 | {
"file_path": "pinball/test/game/components/android_acres/android_acres_test.dart",
"repo_id": "pinball",
"token_count": 2442
} | 1,116 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/components/backbox/displays/displays.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
await super.onLoad();
images.prefix = '';
await images.loadAll(
[
Assets.images.errorBackground.keyName,
],
);
}
Future<void> pump(LeaderboardFailureDisplay component) {
return ensureAdd(
FlameProvider.value(
_MockAppLocalizations(),
children: [component],
),
);
}
}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get leaderboardErrorMessage => 'Message';
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('LeaderboardFailureDisplay', () {
final flameTester = FlameTester(_TestGame.new);
flameTester.test('renders correctly', (game) async {
await game.pump(LeaderboardFailureDisplay());
expect(
game
.descendants()
.where(
(component) =>
component is TextComponent && component.text == 'Message',
)
.length,
equals(1),
);
});
});
}
| pinball/test/game/components/backbox/displays/leaderboard_failure_display_test.dart/0 | {
"file_path": "pinball/test/game/components/backbox/displays/leaderboard_failure_display_test.dart",
"repo_id": "pinball",
"token_count": 629
} | 1,117 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.multiball.lit.keyName,
Assets.images.multiball.dimmed.keyName,
]);
}
Future<void> pump(Multiballs child, {GameBloc? gameBloc}) async {
// Not needed once https://github.com/flame-engine/flame/issues/1607
// is fixed
await onLoad();
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: gameBloc ?? GameBloc(),
children: [child],
),
);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameBlocTester = FlameTester(_TestGame.new);
group('Multiballs', () {
flameBlocTester.testGameWidget(
'loads correctly',
setUp: (game, tester) async {
final multiballs = Multiballs();
await game.pump(multiballs);
},
verify: (game, tester) async {
expect(game.descendants().whereType<Multiballs>().length, equals(1));
},
);
flameBlocTester.test(
'loads four Multiball',
(game) async {
final multiballs = Multiballs();
await game.pump(multiballs);
expect(
multiballs.descendants().whereType<Multiball>().length,
equals(4),
);
},
);
});
}
| pinball/test/game/components/multiballs/multiballs_test.dart/0 | {
"file_path": "pinball/test/game/components/multiballs/multiballs_test.dart",
"repo_id": "pinball",
"token_count": 692
} | 1,118 |
import 'dart:typed_data';
import 'package:flame/assets.dart';
import 'package:flame/flame.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class _MockImages extends Mock implements Images {}
/// {@template mock_flame_images}
/// Mock for flame images instance.
///
/// Using real images blocks the tests, for this reason we need fake image
/// everywhere we use [Images.fromCache] or [Images.load].
/// {@endtemplate}
Future<void> mockFlameImages() async {
final image = await decodeImageFromList(Uint8List.fromList(_fakeImage));
final images = _MockImages();
when(() => images.fromCache(any())).thenReturn(image);
when(() => images.load(any())).thenAnswer((_) => Future.value(image));
Flame.images = images;
}
const _fakeImage = <int>[
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A,
0x00,
0x00,
0x00,
0x0D,
0x49,
0x48,
0x44,
0x52,
0x00,
0x00,
0x00,
0x01,
0x00,
0x00,
0x00,
0x01,
0x08,
0x06,
0x00,
0x00,
0x00,
0x1F,
0x15,
0xC4,
0x89,
0x00,
0x00,
0x00,
0x0A,
0x49,
0x44,
0x41,
0x54,
0x78,
0x9C,
0x63,
0x00,
0x01,
0x00,
0x00,
0x05,
0x00,
0x01,
0x0D,
0x0A,
0x2D,
0xB4,
0x00,
0x00,
0x00,
0x00,
0x49,
0x45,
0x4E,
0x44,
0xAE,
];
| pinball/test/helpers/mock_flame_images.dart/0 | {
"file_path": "pinball/test/helpers/mock_flame_images.dart",
"repo_id": "pinball",
"token_count": 666
} | 1,119 |
#!/bin/bash
# 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.
# To set FETCH_HEAD for "git merge-base" to work
git fetch origin main
# Pinned version of the plugin tools, to avoid breakage in this repository
# when pushing updates from flutter/packages.
dart pub global activate flutter_plugin_tools 0.13.4+3
| plugins/.ci/scripts/prepare_tool.sh/0 | {
"file_path": "plugins/.ci/scripts/prepare_tool.sh",
"repo_id": "plugins",
"token_count": 119
} | 1,120 |
# Below is a list of Flutter team members who are suggested reviewers
# for contributions to plugins in this repository.
#
# These names are just suggestions. It is fine to have your changes
# reviewed by someone else.
# Plugin-level rules.
packages/camera/** @bparrishMines
packages/file_selector/** @stuartmorgan
packages/google_maps_flutter/** @stuartmorgan
packages/google_sign_in/** @stuartmorgan
packages/image_picker/** @tarrinneal
packages/in_app_purchase/** @bparrishMines
packages/local_auth/** @stuartmorgan
packages/path_provider/** @stuartmorgan
packages/plugin_platform_interface/** @stuartmorgan
packages/quick_actions/** @bparrishMines
packages/shared_preferences/** @tarrinneal
packages/url_launcher/** @stuartmorgan
packages/video_player/** @tarrinneal
packages/webview_flutter/** @bparrishMines
# Sub-package-level rules. These should stay last, since the last matching
# entry takes precedence.
# - Web
packages/**/*_web/** @ditman
# - Android
packages/camera/camera_android/** @camsim99
packages/camera/camera_android_camerax/** @camsim99
packages/espresso/** @reidbaker
packages/flutter_plugin_android_lifecycle/** @reidbaker
packages/google_maps_flutter/google_maps_flutter_android/** @reidbaker
packages/google_sign_in/google_sign_in_android/** @camsim99
packages/image_picker/image_picker_android/** @gmackall
packages/in_app_purchase/in_app_purchase_android/** @gmackall
packages/local_auth/local_auth_android/** @camsim99
packages/path_provider/path_provider_android/** @camsim99
packages/quick_actions/quick_actions_android/** @camsim99
packages/shared_preferences/shared_preferences_android/** @reidbaker
packages/url_launcher/url_launcher_android/** @gmackall
packages/video_player/video_player_android/** @camsim99
# - iOS
packages/camera/camera_avfoundation/** @hellohuanlin
packages/file_selector/file_selector_ios/** @jmagman
packages/google_maps_flutter/google_maps_flutter_ios/** @cyanglaz
packages/google_sign_in/google_sign_in_ios/** @vashworth
packages/image_picker/image_picker_ios/** @vashworth
packages/in_app_purchase/in_app_purchase_storekit/** @cyanglaz
packages/ios_platform_images/ios/** @jmagman
packages/local_auth/local_auth_ios/** @louisehsu
packages/path_provider/path_provider_foundation/** @jmagman
packages/quick_actions/quick_actions_ios/** @hellohuanlin
packages/shared_preferences/shared_preferences_foundation/** @cyanglaz
packages/url_launcher/url_launcher_ios/** @jmagman
packages/video_player/video_player_avfoundation/** @hellohuanlin
packages/webview_flutter/webview_flutter_wkwebview/** @cyanglaz
# - Linux
packages/file_selector/file_selector_linux/** @cbracken
packages/path_provider/path_provider_linux/** @cbracken
packages/shared_preferences/shared_preferences_linux/** @cbracken
packages/url_launcher/url_launcher_linux/** @cbracken
# - macOS
packages/file_selector/file_selector_macos/** @cbracken
packages/url_launcher/url_launcher_macos/** @cbracken
# - Windows
packages/camera/camera_windows/** @cbracken
packages/file_selector/file_selector_windows/** @cbracken
packages/image_picker/image_picker_windows/** @cbracken
packages/local_auth/local_auth_windows/** @cbracken
packages/path_provider/path_provider_windows/** @cbracken
packages/shared_preferences/shared_preferences_windows/** @cbracken
packages/url_launcher/url_launcher_windows/** @cbracken
| plugins/CODEOWNERS/0 | {
"file_path": "plugins/CODEOWNERS",
"repo_id": "plugins",
"token_count": 2018
} | 1,121 |
// 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.camera.features.exposurepoint;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.MeteringRectangle;
import android.util.Size;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.CameraRegionUtils;
import io.flutter.plugins.camera.features.CameraFeature;
import io.flutter.plugins.camera.features.Point;
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
/** Exposure point controls where in the frame exposure metering will come from. */
public class ExposurePointFeature extends CameraFeature<Point> {
private Size cameraBoundaries;
private Point exposurePoint;
private MeteringRectangle exposureRectangle;
private final SensorOrientationFeature sensorOrientationFeature;
/**
* Creates a new instance of the {@link ExposurePointFeature}.
*
* @param cameraProperties Collection of the characteristics for the current camera device.
*/
public ExposurePointFeature(
CameraProperties cameraProperties, SensorOrientationFeature sensorOrientationFeature) {
super(cameraProperties);
this.sensorOrientationFeature = sensorOrientationFeature;
}
/**
* Sets the camera boundaries that are required for the exposure point feature to function.
*
* @param cameraBoundaries - The camera boundaries to set.
*/
public void setCameraBoundaries(@NonNull Size cameraBoundaries) {
this.cameraBoundaries = cameraBoundaries;
this.buildExposureRectangle();
}
@Override
public String getDebugName() {
return "ExposurePointFeature";
}
@Override
public Point getValue() {
return exposurePoint;
}
@Override
public void setValue(Point value) {
this.exposurePoint = (value == null || value.x == null || value.y == null) ? null : value;
this.buildExposureRectangle();
}
// Whether or not this camera can set the exposure point.
@Override
public boolean checkIsSupported() {
Integer supportedRegions = cameraProperties.getControlMaxRegionsAutoExposure();
return supportedRegions != null && supportedRegions > 0;
}
@Override
public void updateBuilder(CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
requestBuilder.set(
CaptureRequest.CONTROL_AE_REGIONS,
exposureRectangle == null ? null : new MeteringRectangle[] {exposureRectangle});
}
private void buildExposureRectangle() {
if (this.cameraBoundaries == null) {
throw new AssertionError(
"The cameraBoundaries should be set (using `ExposurePointFeature.setCameraBoundaries(Size)`) before updating the exposure point.");
}
if (this.exposurePoint == null) {
this.exposureRectangle = null;
} else {
PlatformChannel.DeviceOrientation orientation =
this.sensorOrientationFeature.getLockedCaptureOrientation();
if (orientation == null) {
orientation =
this.sensorOrientationFeature.getDeviceOrientationManager().getLastUIOrientation();
}
this.exposureRectangle =
CameraRegionUtils.convertPointToMeteringRectangle(
this.cameraBoundaries, this.exposurePoint.x, this.exposurePoint.y, orientation);
}
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurepoint/ExposurePointFeature.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurepoint/ExposurePointFeature.java",
"repo_id": "plugins",
"token_count": 1091
} | 1,122 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.types;
// Mirrors exposure_mode.dart
public enum ExposureMode {
auto("auto"),
locked("locked");
private final String strValue;
ExposureMode(String strValue) {
this.strValue = strValue;
}
public static ExposureMode getValueForString(String modeStr) {
for (ExposureMode value : values()) {
if (value.strValue.equals(modeStr)) return value;
}
return null;
}
@Override
public String toString() {
return strValue;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/ExposureMode.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/ExposureMode.java",
"repo_id": "plugins",
"token_count": 209
} | 1,123 |
// 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 'android_camera_camerax_flutter_api_impls.dart';
import 'camera.dart';
import 'camera_info.dart';
import 'camera_selector.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
import 'use_case.dart';
/// Provides an object to manage the camera.
///
/// See https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider.
class ProcessCameraProvider extends JavaObject {
/// Creates a detached [ProcessCameraProvider].
ProcessCameraProvider.detached(
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = ProcessCameraProviderHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final ProcessCameraProviderHostApiImpl _api;
/// Gets an instance of [ProcessCameraProvider].
static Future<ProcessCameraProvider> getInstance(
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) {
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
final ProcessCameraProviderHostApiImpl api =
ProcessCameraProviderHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
return api.getInstancefromInstances();
}
/// Retrieves the cameras available to the device.
Future<List<CameraInfo>> getAvailableCameraInfos() {
return _api.getAvailableCameraInfosFromInstances(this);
}
/// Binds the specified [UseCase]s to the lifecycle of the camera that it
/// returns.
Future<Camera> bindToLifecycle(
CameraSelector cameraSelector, List<UseCase> useCases) {
return _api.bindToLifecycleFromInstances(this, cameraSelector, useCases);
}
/// Unbinds specified [UseCase]s from the lifecycle of the camera that this
/// instance tracks.
void unbind(List<UseCase> useCases) {
_api.unbindFromInstances(this, useCases);
}
/// Unbinds all previously bound [UseCase]s from the lifecycle of the camera
/// that this tracks.
void unbindAll() {
_api.unbindAllFromInstances(this);
}
}
/// Host API implementation of [ProcessCameraProvider].
class ProcessCameraProviderHostApiImpl extends ProcessCameraProviderHostApi {
/// Creates a [ProcessCameraProviderHostApiImpl].
ProcessCameraProviderHostApiImpl(
{this.binaryMessenger, InstanceManager? instanceManager})
: super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Retrieves an instance of a ProcessCameraProvider from the context of
/// the FlutterActivity.
Future<ProcessCameraProvider> getInstancefromInstances() async {
return instanceManager.getInstanceWithWeakReference(await getInstance())!
as ProcessCameraProvider;
}
/// Gets identifier that the [instanceManager] has set for
/// the [ProcessCameraProvider] instance.
int getProcessCameraProviderIdentifier(ProcessCameraProvider instance) {
final int? identifier = instanceManager.getIdentifier(instance);
assert(identifier != null,
'No ProcessCameraProvider has the identifer of that which was requested.');
return identifier!;
}
/// Retrives the list of CameraInfos corresponding to the available cameras.
Future<List<CameraInfo>> getAvailableCameraInfosFromInstances(
ProcessCameraProvider instance) async {
final int identifier = getProcessCameraProviderIdentifier(instance);
final List<int?> cameraInfos = await getAvailableCameraInfos(identifier);
return cameraInfos
.map<CameraInfo>((int? id) =>
instanceManager.getInstanceWithWeakReference(id!)! as CameraInfo)
.toList();
}
/// Binds the specified [UseCase]s to the lifecycle of the camera which
/// the provided [ProcessCameraProvider] instance tracks.
///
/// The instance of the camera whose lifecycle the [UseCase]s are bound to
/// is returned.
Future<Camera> bindToLifecycleFromInstances(
ProcessCameraProvider instance,
CameraSelector cameraSelector,
List<UseCase> useCases,
) async {
final int identifier = getProcessCameraProviderIdentifier(instance);
final List<int> useCaseIds = useCases
.map<int>((UseCase useCase) => instanceManager.getIdentifier(useCase)!)
.toList();
final int cameraIdentifier = await bindToLifecycle(
identifier,
instanceManager.getIdentifier(cameraSelector)!,
useCaseIds,
);
return instanceManager.getInstanceWithWeakReference(cameraIdentifier)!
as Camera;
}
/// Unbinds specified [UseCase]s from the lifecycle of the camera which the
/// provided [ProcessCameraProvider] instance tracks.
void unbindFromInstances(
ProcessCameraProvider instance,
List<UseCase> useCases,
) {
final int identifier = getProcessCameraProviderIdentifier(instance);
final List<int> useCaseIds = useCases
.map<int>((UseCase useCase) => instanceManager.getIdentifier(useCase)!)
.toList();
unbind(identifier, useCaseIds);
}
/// Unbinds all previously bound [UseCase]s from the lifecycle of the camera
/// which the provided [ProcessCameraProvider] instance tracks.
void unbindAllFromInstances(ProcessCameraProvider instance) {
final int identifier = getProcessCameraProviderIdentifier(instance);
unbindAll(identifier);
}
}
/// Flutter API Implementation of [ProcessCameraProvider].
class ProcessCameraProviderFlutterApiImpl
implements ProcessCameraProviderFlutterApi {
/// Constructs a [ProcessCameraProviderFlutterApiImpl].
ProcessCameraProviderFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(int identifier) {
instanceManager.addHostCreatedInstance(
ProcessCameraProvider.detached(
binaryMessenger: binaryMessenger, instanceManager: instanceManager),
identifier,
onCopy: (ProcessCameraProvider original) {
return ProcessCameraProvider.detached(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
},
);
}
}
| plugins/packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart",
"repo_id": "plugins",
"token_count": 2163
} | 1,124 |
// 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 camera_avfoundation;
@import camera_avfoundation.Test;
@import XCTest;
@import AVFoundation;
#import <OCMock/OCMock.h>
@interface CameraFocusTests : XCTestCase
@property(readonly, nonatomic) FLTCam *camera;
@property(readonly, nonatomic) id mockDevice;
@property(readonly, nonatomic) id mockUIDevice;
@end
@implementation CameraFocusTests
- (void)setUp {
_camera = [[FLTCam alloc] init];
_mockDevice = OCMClassMock([AVCaptureDevice class]);
_mockUIDevice = OCMPartialMock([UIDevice currentDevice]);
}
- (void)tearDown {
[_mockDevice stopMocking];
[_mockUIDevice stopMocking];
}
- (void)testAutoFocusWithContinuousModeSupported_ShouldSetContinuousAutoFocus {
// AVCaptureFocusModeContinuousAutoFocus is supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]).andReturn(true);
// AVCaptureFocusModeContinuousAutoFocus is supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]).andReturn(true);
// Don't expect setFocusMode:AVCaptureFocusModeAutoFocus
[[_mockDevice reject] setFocusMode:AVCaptureFocusModeAutoFocus];
// Run test
[_camera applyFocusMode:FLTFocusModeAuto onDevice:_mockDevice];
// Expect setFocusMode:AVCaptureFocusModeContinuousAutoFocus
OCMVerify([_mockDevice setFocusMode:AVCaptureFocusModeContinuousAutoFocus]);
}
- (void)testAutoFocusWithContinuousModeNotSupported_ShouldSetAutoFocus {
// AVCaptureFocusModeContinuousAutoFocus is not supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus])
.andReturn(false);
// AVCaptureFocusModeContinuousAutoFocus is supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]).andReturn(true);
// Don't expect setFocusMode:AVCaptureFocusModeContinuousAutoFocus
[[_mockDevice reject] setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
// Run test
[_camera applyFocusMode:FLTFocusModeAuto onDevice:_mockDevice];
// Expect setFocusMode:AVCaptureFocusModeAutoFocus
OCMVerify([_mockDevice setFocusMode:AVCaptureFocusModeAutoFocus]);
}
- (void)testAutoFocusWithNoModeSupported_ShouldSetNothing {
// AVCaptureFocusModeContinuousAutoFocus is not supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus])
.andReturn(false);
// AVCaptureFocusModeContinuousAutoFocus is not supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]).andReturn(false);
// Don't expect any setFocus
[[_mockDevice reject] setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
[[_mockDevice reject] setFocusMode:AVCaptureFocusModeAutoFocus];
// Run test
[_camera applyFocusMode:FLTFocusModeAuto onDevice:_mockDevice];
}
- (void)testLockedFocusWithModeSupported_ShouldSetModeAutoFocus {
// AVCaptureFocusModeContinuousAutoFocus is supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]).andReturn(true);
// AVCaptureFocusModeContinuousAutoFocus is supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]).andReturn(true);
// Don't expect any setFocus
[[_mockDevice reject] setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
// Run test
[_camera applyFocusMode:FLTFocusModeLocked onDevice:_mockDevice];
// Expect setFocusMode:AVCaptureFocusModeAutoFocus
OCMVerify([_mockDevice setFocusMode:AVCaptureFocusModeAutoFocus]);
}
- (void)testLockedFocusWithModeNotSupported_ShouldSetNothing {
// AVCaptureFocusModeContinuousAutoFocus is supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]).andReturn(true);
// AVCaptureFocusModeContinuousAutoFocus is not supported
OCMStub([_mockDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]).andReturn(false);
// Don't expect any setFocus
[[_mockDevice reject] setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
[[_mockDevice reject] setFocusMode:AVCaptureFocusModeAutoFocus];
// Run test
[_camera applyFocusMode:FLTFocusModeLocked onDevice:_mockDevice];
}
- (void)testSetFocusPointWithResult_SetsFocusPointOfInterest {
// UI is currently in landscape left orientation
OCMStub([(UIDevice *)_mockUIDevice orientation]).andReturn(UIDeviceOrientationLandscapeLeft);
// Focus point of interest is supported
OCMStub([_mockDevice isFocusPointOfInterestSupported]).andReturn(true);
// Set mock device as the current capture device
[_camera setValue:_mockDevice forKey:@"captureDevice"];
// Run test
[_camera setFocusPointWithResult:[[FLTThreadSafeFlutterResult alloc]
initWithResult:^(id _Nullable result){
}]
x:1
y:1];
// Verify the focus point of interest has been set
OCMVerify([_mockDevice setFocusPointOfInterest:CGPointMake(1, 1)]);
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraFocusTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraFocusTests.m",
"repo_id": "plugins",
"token_count": 1627
} | 1,125 |
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 {
compileSdkVersion 31
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.espresso_example"
minSdkVersion 16
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
testImplementation 'junit:junit:4.13.2'
testImplementation "com.google.truth:truth:1.0"
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
// Core library
api 'androidx.test:core:1.2.0'
// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test:rules:1.1.0'
// Assertions
androidTestImplementation 'androidx.test.ext:junit:1.0.0'
androidTestImplementation 'androidx.test.ext:truth:1.0.0'
androidTestImplementation 'com.google.truth:truth:0.42'
// Espresso dependencies
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.0'
androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.1.0'
// The following Espresso dependency can be either "implementation"
// or "androidTestImplementation", depending on whether you want the
// dependency to appear on your APK's compile classpath or the test APK
// classpath.
androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.1.0'
}
| plugins/packages/espresso/example/android/app/build.gradle/0 | {
"file_path": "plugins/packages/espresso/example/android/app/build.gradle",
"repo_id": "plugins",
"token_count": 1131
} | 1,126 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.2.5), 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, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
// This line has been hand-edited due to
// https://github.com/flutter/flutter/issues/97744
// ignore: directives_ordering
import 'package:file_selector_ios/src/messages.g.dart';
class _TestFileSelectorApiCodec extends StandardMessageCodec {
const _TestFileSelectorApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is FileSelectorConfig) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return FileSelectorConfig.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestFileSelectorApi {
static const MessageCodec<Object?> codec = _TestFileSelectorApiCodec();
Future<List<String?>> openFile(FileSelectorConfig config);
static void setup(TestFileSelectorApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.openFile', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.openFile was null.');
final List<Object?> args = (message as List<Object?>?)!;
final FileSelectorConfig? arg_config =
(args[0] as FileSelectorConfig?);
assert(arg_config != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.openFile was null, expected non-null FileSelectorConfig.');
final List<String?> output = await api.openFile(arg_config!);
return <Object?, Object?>{'result': output};
});
}
}
}
}
| plugins/packages/file_selector/file_selector_ios/test/test_api.g.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_ios/test/test_api.g.dart",
"repo_id": "plugins",
"token_count": 1012
} | 1,127 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html';
import 'dart:typed_data';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:file_selector_web/file_selector_web.dart';
import 'package:file_selector_web/src/dom_helper.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
group('FileSelectorWeb', () {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('openFile', () {
testWidgets('works', (WidgetTester _) async {
final XFile mockFile = createXFile('1001', 'identity.png');
final MockDomHelper mockDomHelper = MockDomHelper(
files: <XFile>[mockFile],
expectAccept: '.jpg,.jpeg,image/png,image/*');
final FileSelectorWeb plugin =
FileSelectorWeb(domHelper: mockDomHelper);
const XTypeGroup typeGroup = XTypeGroup(
label: 'images',
extensions: <String>['jpg', 'jpeg'],
mimeTypes: <String>['image/png'],
webWildCards: <String>['image/*'],
);
final XFile file =
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
expect(file.name, mockFile.name);
expect(await file.length(), 4);
expect(await file.readAsString(), '1001');
expect(await file.lastModified(), isNotNull);
});
});
group('openFiles', () {
testWidgets('works', (WidgetTester _) async {
final XFile mockFile1 = createXFile('123456', 'file1.txt');
final XFile mockFile2 = createXFile('', 'file2.txt');
final MockDomHelper mockDomHelper = MockDomHelper(
files: <XFile>[mockFile1, mockFile2],
expectAccept: '.txt',
expectMultiple: true);
final FileSelectorWeb plugin =
FileSelectorWeb(domHelper: mockDomHelper);
const XTypeGroup typeGroup = XTypeGroup(
label: 'files',
extensions: <String>['.txt'],
);
final List<XFile> files =
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
expect(files.length, 2);
expect(files[0].name, mockFile1.name);
expect(await files[0].length(), 6);
expect(await files[0].readAsString(), '123456');
expect(await files[0].lastModified(), isNotNull);
expect(files[1].name, mockFile2.name);
expect(await files[1].length(), 0);
expect(await files[1].readAsString(), '');
expect(await files[1].lastModified(), isNotNull);
});
});
group('getSavePath', () {
testWidgets('returns non-null', (WidgetTester _) async {
final FileSelectorWeb plugin = FileSelectorWeb();
final Future<String?> savePath = plugin.getSavePath();
expect(await savePath, isNotNull);
});
});
});
}
class MockDomHelper implements DomHelper {
MockDomHelper({
List<XFile> files = const <XFile>[],
String expectAccept = '',
bool expectMultiple = false,
}) : _files = files,
_expectedAccept = expectAccept,
_expectedMultiple = expectMultiple;
final List<XFile> _files;
final String _expectedAccept;
final bool _expectedMultiple;
@override
Future<List<XFile>> getFiles({
String accept = '',
bool multiple = false,
FileUploadInputElement? input,
}) {
expect(accept, _expectedAccept,
reason: 'Expected "accept" value does not match.');
expect(multiple, _expectedMultiple,
reason: 'Expected "multiple" value does not match.');
return Future<List<XFile>>.value(_files);
}
}
XFile createXFile(String content, String name) {
final Uint8List data = Uint8List.fromList(content.codeUnits);
return XFile.fromData(data, name: name, lastModified: DateTime.now());
}
| plugins/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart",
"repo_id": "plugins",
"token_count": 1582
} | 1,128 |
// 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',
dartTestOut: 'test/test_api.g.dart',
cppOptions: CppOptions(namespace: 'file_selector_windows'),
cppHeaderOut: 'windows/messages.g.h',
cppSourceOut: 'windows/messages.g.cpp',
copyrightHeader: 'pigeons/copyright.txt',
))
class TypeGroup {
TypeGroup(this.label, {required this.extensions});
String label;
// TODO(stuartmorgan): Make the generic type non-nullable once supported.
// https://github.com/flutter/flutter/issues/97848
// The C++ code treats all of it as non-nullable.
List<String?> extensions;
}
class SelectionOptions {
SelectionOptions({
this.allowMultiple = false,
this.selectFolders = false,
this.allowedTypes = const <TypeGroup?>[],
});
bool allowMultiple;
bool selectFolders;
// TODO(stuartmorgan): Make the generic type non-nullable once supported.
// https://github.com/flutter/flutter/issues/97848
// The C++ code treats the values as non-nullable.
List<TypeGroup?> allowedTypes;
}
@HostApi(dartHostTestHandler: 'TestFileSelectorApi')
abstract class FileSelectorApi {
List<String?> showOpenDialog(
SelectionOptions options,
String? initialDirectory,
String? confirmButtonText,
);
List<String?> showSaveDialog(
SelectionOptions options,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
);
}
| plugins/packages/file_selector/file_selector_windows/pigeons/messages.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_windows/pigeons/messages.dart",
"repo_id": "plugins",
"token_count": 537
} | 1,129 |
rootProject.name = 'flutter_plugin_android_lifecycle'
| plugins/packages/flutter_plugin_android_lifecycle/android/settings.gradle/0 | {
"file_path": "plugins/packages/flutter_plugin_android_lifecycle/android/settings.gradle",
"repo_id": "plugins",
"token_count": 17
} | 1,130 |
name: google_maps_flutter_example
description: Demonstrates how to use the google_maps_flutter plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
cupertino_icons: ^1.0.5
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.1
google_maps_flutter_android:
# When depending on this package from a real application you should use:
# google_maps_flutter_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: ../
google_maps_flutter_platform_interface: ^2.2.1
dev_dependencies:
build_runner: ^2.1.10
espresso: ^0.2.0
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
| plugins/packages/google_maps_flutter/google_maps_flutter_android/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 365
} | 1,131 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:html' as html;
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart';
import 'package:integration_test/integration_test.dart';
/// Test Markers
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// Since onTap/DragEnd events happen asynchronously, we need to store when the event
// is fired. We use a completer so the test can wait for the future to be completed.
late Completer<bool> methodCalledCompleter;
/// This is the future value of the [methodCalledCompleter]. Reinitialized
/// in the [setUp] method, and completed (as `true`) by [onTap] and [onDragEnd]
/// when those methods are called from the MarkerController.
late Future<bool> methodCalled;
void onTap() {
methodCalledCompleter.complete(true);
}
void onDragStart(gmaps.LatLng _) {
methodCalledCompleter.complete(true);
}
void onDrag(gmaps.LatLng _) {
methodCalledCompleter.complete(true);
}
void onDragEnd(gmaps.LatLng _) {
methodCalledCompleter.complete(true);
}
setUp(() {
methodCalledCompleter = Completer<bool>();
methodCalled = methodCalledCompleter.future;
});
group('MarkerController', () {
late gmaps.Marker marker;
setUp(() {
marker = gmaps.Marker();
});
testWidgets('onTap gets called', (WidgetTester tester) async {
MarkerController(marker: marker, onTap: onTap);
// Trigger a click event...
gmaps.Event.trigger(marker, 'click', <Object?>[gmaps.MapMouseEvent()]);
// The event handling is now truly async. Wait for it...
expect(await methodCalled, isTrue);
});
testWidgets('onDragStart gets called', (WidgetTester tester) async {
MarkerController(marker: marker, onDragStart: onDragStart);
// Trigger a drag end event...
gmaps.Event.trigger(marker, 'dragstart',
<Object?>[gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)]);
expect(await methodCalled, isTrue);
});
testWidgets('onDrag gets called', (WidgetTester tester) async {
MarkerController(marker: marker, onDrag: onDrag);
// Trigger a drag end event...
gmaps.Event.trigger(
marker,
'drag',
<Object?>[gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)],
);
expect(await methodCalled, isTrue);
});
testWidgets('onDragEnd gets called', (WidgetTester tester) async {
MarkerController(marker: marker, onDragEnd: onDragEnd);
// Trigger a drag end event...
gmaps.Event.trigger(
marker,
'dragend',
<Object?>[gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)],
);
expect(await methodCalled, isTrue);
});
testWidgets('update', (WidgetTester tester) async {
final MarkerController controller = MarkerController(marker: marker);
final gmaps.MarkerOptions options = gmaps.MarkerOptions()
..draggable = true;
expect(marker.draggable, isNull);
controller.update(options);
expect(marker.draggable, isTrue);
});
testWidgets('infoWindow null, showInfoWindow.',
(WidgetTester tester) async {
final MarkerController controller = MarkerController(marker: marker);
controller.showInfoWindow();
expect(controller.infoWindowShown, isFalse);
});
testWidgets('showInfoWindow', (WidgetTester tester) async {
final gmaps.InfoWindow infoWindow = gmaps.InfoWindow();
final gmaps.GMap map = gmaps.GMap(html.DivElement());
marker.set('map', map);
final MarkerController controller = MarkerController(
marker: marker,
infoWindow: infoWindow,
);
controller.showInfoWindow();
expect(infoWindow.get('map'), map);
expect(controller.infoWindowShown, isTrue);
});
testWidgets('hideInfoWindow', (WidgetTester tester) async {
final gmaps.InfoWindow infoWindow = gmaps.InfoWindow();
final gmaps.GMap map = gmaps.GMap(html.DivElement());
marker.set('map', map);
final MarkerController controller = MarkerController(
marker: marker,
infoWindow: infoWindow,
);
controller.hideInfoWindow();
expect(infoWindow.get('map'), isNull);
expect(controller.infoWindowShown, isFalse);
});
group('remove', () {
late MarkerController controller;
setUp(() {
final gmaps.InfoWindow infoWindow = gmaps.InfoWindow();
final gmaps.GMap map = gmaps.GMap(html.DivElement());
marker.set('map', map);
controller = MarkerController(marker: marker, infoWindow: infoWindow);
});
testWidgets('drops gmaps instance', (WidgetTester tester) async {
controller.remove();
expect(controller.marker, isNull);
});
testWidgets('cannot call update after remove',
(WidgetTester tester) async {
final gmaps.MarkerOptions options = gmaps.MarkerOptions()
..draggable = true;
controller.remove();
expect(() {
controller.update(options);
}, throwsAssertionError);
});
testWidgets('cannot call showInfoWindow after remove',
(WidgetTester tester) async {
controller.remove();
expect(() {
controller.showInfoWindow();
}, throwsAssertionError);
});
testWidgets('cannot call hideInfoWindow after remove',
(WidgetTester tester) async {
controller.remove();
expect(() {
controller.hideInfoWindow();
}, throwsAssertionError);
});
});
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart",
"repo_id": "plugins",
"token_count": 2250
} | 1,132 |
// 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;
/// Type used when passing an override to the _createMap function.
@visibleForTesting
typedef DebugCreateMapFunction = gmaps.GMap Function(
HtmlElement div, gmaps.MapOptions options);
/// Encapsulates a [gmaps.GMap], its events, and where in the DOM it's rendered.
class GoogleMapController {
/// Initializes the GMap, and the sub-controllers related to it. Wires events.
GoogleMapController({
required int mapId,
required StreamController<MapEvent<Object?>> streamController,
required MapWidgetConfiguration widgetConfiguration,
MapObjects mapObjects = const MapObjects(),
MapConfiguration mapConfiguration = const MapConfiguration(),
}) : _mapId = mapId,
_streamController = streamController,
_initialCameraPosition = widgetConfiguration.initialCameraPosition,
_markers = mapObjects.markers,
_polygons = mapObjects.polygons,
_polylines = mapObjects.polylines,
_circles = mapObjects.circles,
_lastMapConfiguration = mapConfiguration {
_circlesController = CirclesController(stream: _streamController);
_polygonsController = PolygonsController(stream: _streamController);
_polylinesController = PolylinesController(stream: _streamController);
_markersController = MarkersController(stream: _streamController);
// Register the view factory that will hold the `_div` that holds the map in the DOM.
// The `_div` needs to be created outside of the ViewFactory (and cached!) so we can
// use it to create the [gmaps.GMap] in the `init()` method of this class.
_div = DivElement()
..id = _getViewType(mapId)
..style.width = '100%'
..style.height = '100%';
ui.platformViewRegistry.registerViewFactory(
_getViewType(mapId),
(int viewId) => _div,
);
}
// The internal ID of the map. Used to broadcast events, DOM IDs and everything where a unique ID is needed.
final int _mapId;
final CameraPosition _initialCameraPosition;
final Set<Marker> _markers;
final Set<Polygon> _polygons;
final Set<Polyline> _polylines;
final Set<Circle> _circles;
// The configuraiton passed by the user, before converting to gmaps.
// Caching this allows us to re-create the map faithfully when needed.
MapConfiguration _lastMapConfiguration = const MapConfiguration();
List<gmaps.MapTypeStyle> _lastStyles = const <gmaps.MapTypeStyle>[];
// Creates the 'viewType' for the _widget
String _getViewType(int mapId) => 'plugins.flutter.io/google_maps_$mapId';
// The Flutter widget that contains the rendered Map.
HtmlElementView? _widget;
late HtmlElement _div;
/// The Flutter widget that will contain the rendered Map. Used for caching.
Widget? get widget {
if (_widget == null && !_streamController.isClosed) {
_widget = HtmlElementView(
viewType: _getViewType(_mapId),
);
}
return _widget;
}
// The currently-enabled traffic layer.
gmaps.TrafficLayer? _trafficLayer;
/// A getter for the current traffic layer. Only for tests.
@visibleForTesting
gmaps.TrafficLayer? get trafficLayer => _trafficLayer;
// The underlying GMap instance. This is the interface with the JS SDK.
gmaps.GMap? _googleMap;
// The StreamController used by this controller and the geometry ones.
final StreamController<MapEvent<Object?>> _streamController;
/// The StreamController for the events of this Map. Only for integration testing.
@visibleForTesting
StreamController<MapEvent<Object?>> get stream => _streamController;
/// The Stream over which this controller broadcasts events.
Stream<MapEvent<Object?>> get events => _streamController.stream;
// Geometry controllers, for different features of the map.
CirclesController? _circlesController;
PolygonsController? _polygonsController;
PolylinesController? _polylinesController;
MarkersController? _markersController;
// Keeps track if _attachGeometryControllers has been called or not.
bool _controllersBoundToMap = false;
// Keeps track if the map is moving or not.
bool _mapIsMoving = false;
/// Overrides certain properties to install mocks defined during testing.
@visibleForTesting
void debugSetOverrides({
DebugCreateMapFunction? createMap,
MarkersController? markers,
CirclesController? circles,
PolygonsController? polygons,
PolylinesController? polylines,
}) {
_overrideCreateMap = createMap;
_markersController = markers ?? _markersController;
_circlesController = circles ?? _circlesController;
_polygonsController = polygons ?? _polygonsController;
_polylinesController = polylines ?? _polylinesController;
}
DebugCreateMapFunction? _overrideCreateMap;
gmaps.GMap _createMap(HtmlElement div, gmaps.MapOptions options) {
if (_overrideCreateMap != null) {
return _overrideCreateMap!(div, options);
}
return gmaps.GMap(div, options);
}
/// A flag that returns true if the controller has been initialized or not.
@visibleForTesting
bool get isInitialized => _googleMap != null;
/// Starts the JS Maps SDK into the target [_div] with `rawOptions`.
///
/// (Also initializes the geometry/traffic layers.)
///
/// The first part of this method starts the rendering of a [gmaps.GMap] inside
/// of the target [_div], with configuration from `rawOptions`. It then stores
/// the created GMap in the [_googleMap] attribute.
///
/// Not *everything* is rendered with the initial `rawOptions` configuration,
/// geometry and traffic layers (and possibly others in the future) have their
/// own configuration and are rendered on top of a GMap instance later. This
/// happens in the second half of this method.
///
/// This method is eagerly called from the [GoogleMapsPlugin.buildView] method
/// so the internal [GoogleMapsController] of a Web Map initializes as soon as
/// possible. Check [_attachMapEvents] to see how this controller notifies the
/// plugin of it being fully ready (through the `onTilesloaded.first` event).
///
/// Failure to call this method would result in the GMap not rendering at all,
/// and most of the public methods on this class no-op'ing.
void init() {
gmaps.MapOptions options = _configurationAndStyleToGmapsOptions(
_lastMapConfiguration, _lastStyles);
// Initial position can only to be set here!
options = _applyInitialPosition(_initialCameraPosition, options);
// Create the map...
final gmaps.GMap map = _createMap(_div, options);
_googleMap = map;
_attachMapEvents(map);
_attachGeometryControllers(map);
// Now attach the geometry, traffic and any other layers...
_renderInitialGeometry(
markers: _markers,
circles: _circles,
polygons: _polygons,
polylines: _polylines,
);
_setTrafficLayer(map, _lastMapConfiguration.trafficEnabled ?? false);
}
// Funnels map gmap events into the plugin's stream controller.
void _attachMapEvents(gmaps.GMap map) {
map.onTilesloaded.first.then((void _) {
// Report the map as ready to go the first time the tiles load
_streamController.add(WebMapReadyEvent(_mapId));
});
map.onClick.listen((gmaps.IconMouseEvent event) {
assert(event.latLng != null);
_streamController.add(
MapTapEvent(_mapId, _gmLatLngToLatLng(event.latLng!)),
);
});
map.onRightclick.listen((gmaps.MapMouseEvent event) {
assert(event.latLng != null);
_streamController.add(
MapLongPressEvent(_mapId, _gmLatLngToLatLng(event.latLng!)),
);
});
map.onBoundsChanged.listen((void _) {
if (!_mapIsMoving) {
_mapIsMoving = true;
_streamController.add(CameraMoveStartedEvent(_mapId));
}
_streamController.add(
CameraMoveEvent(_mapId, _gmViewportToCameraPosition(map)),
);
});
map.onIdle.listen((void _) {
_mapIsMoving = false;
_streamController.add(CameraIdleEvent(_mapId));
});
}
// Binds the Geometry controllers to a map instance
void _attachGeometryControllers(gmaps.GMap map) {
// Now we can add the initial geometry.
// And bind the (ready) map instance to the other geometry controllers.
//
// These controllers are either created in the constructor of this class, or
// overriden (for testing) by the [debugSetOverrides] method. They can't be
// null.
assert(_circlesController != null,
'Cannot attach a map to a null CirclesController instance.');
assert(_polygonsController != null,
'Cannot attach a map to a null PolygonsController instance.');
assert(_polylinesController != null,
'Cannot attach a map to a null PolylinesController instance.');
assert(_markersController != null,
'Cannot attach a map to a null MarkersController instance.');
_circlesController!.bindToMap(_mapId, map);
_polygonsController!.bindToMap(_mapId, map);
_polylinesController!.bindToMap(_mapId, map);
_markersController!.bindToMap(_mapId, map);
_controllersBoundToMap = true;
}
// Renders the initial sets of geometry.
void _renderInitialGeometry({
Set<Marker> markers = const <Marker>{},
Set<Circle> circles = const <Circle>{},
Set<Polygon> polygons = const <Polygon>{},
Set<Polyline> polylines = const <Polyline>{},
}) {
assert(
_controllersBoundToMap,
'Geometry controllers must be bound to a map before any geometry can '
'be added to them. Ensure _attachGeometryControllers is called first.');
// The above assert will only succeed if the controllers have been bound to a map
// in the [_attachGeometryControllers] method, which ensures that all these
// controllers below are *not* null.
_markersController!.addMarkers(markers);
_circlesController!.addCircles(circles);
_polygonsController!.addPolygons(polygons);
_polylinesController!.addPolylines(polylines);
}
// Merges new options coming from the plugin into _lastConfiguration.
//
// Returns the updated _lastConfiguration object.
MapConfiguration _mergeConfigurations(MapConfiguration update) {
_lastMapConfiguration = _lastMapConfiguration.applyDiff(update);
return _lastMapConfiguration;
}
/// Updates the map options from a [MapConfiguration].
///
/// This method converts the map into the proper [gmaps.MapOptions].
void updateMapConfiguration(MapConfiguration update) {
assert(_googleMap != null, 'Cannot update options on a null map.');
final MapConfiguration newConfiguration = _mergeConfigurations(update);
final gmaps.MapOptions newOptions =
_configurationAndStyleToGmapsOptions(newConfiguration, _lastStyles);
_setOptions(newOptions);
_setTrafficLayer(_googleMap!, newConfiguration.trafficEnabled ?? false);
}
/// Updates the map options with a new list of [styles].
void updateStyles(List<gmaps.MapTypeStyle> styles) {
_lastStyles = styles;
_setOptions(
_configurationAndStyleToGmapsOptions(_lastMapConfiguration, styles));
}
// Sets new [gmaps.MapOptions] on the wrapped map.
// ignore: use_setters_to_change_properties
void _setOptions(gmaps.MapOptions options) {
_googleMap?.options = options;
}
// Attaches/detaches a Traffic Layer on the passed `map` if `attach` is true/false.
void _setTrafficLayer(gmaps.GMap map, bool attach) {
if (attach && _trafficLayer == null) {
_trafficLayer = gmaps.TrafficLayer()..set('map', map);
}
if (!attach && _trafficLayer != null) {
_trafficLayer!.set('map', null);
_trafficLayer = null;
}
}
// _googleMap manipulation
// Viewport
/// Returns the [LatLngBounds] of the current viewport.
Future<LatLngBounds> getVisibleRegion() async {
assert(_googleMap != null, 'Cannot get the visible region of a null map.');
final gmaps.LatLngBounds bounds =
await Future<gmaps.LatLngBounds?>.value(_googleMap!.bounds) ??
_nullGmapsLatLngBounds;
return _gmLatLngBoundsTolatLngBounds(bounds);
}
/// Returns the [ScreenCoordinate] for a given viewport [LatLng].
Future<ScreenCoordinate> getScreenCoordinate(LatLng latLng) async {
assert(_googleMap != null,
'Cannot get the screen coordinates with a null map.');
final gmaps.Point point =
toScreenLocation(_googleMap!, _latLngToGmLatLng(latLng));
return ScreenCoordinate(x: point.x!.toInt(), y: point.y!.toInt());
}
/// Returns the [LatLng] for a `screenCoordinate` (in pixels) of the viewport.
Future<LatLng> getLatLng(ScreenCoordinate screenCoordinate) async {
assert(_googleMap != null,
'Cannot get the lat, lng of a screen coordinate with a null map.');
final gmaps.LatLng latLng =
_pixelToLatLng(_googleMap!, screenCoordinate.x, screenCoordinate.y);
return _gmLatLngToLatLng(latLng);
}
/// Applies a `cameraUpdate` to the current viewport.
Future<void> moveCamera(CameraUpdate cameraUpdate) async {
assert(_googleMap != null, 'Cannot update the camera of a null map.');
return _applyCameraUpdate(_googleMap!, cameraUpdate);
}
/// Returns the zoom level of the current viewport.
Future<double> getZoomLevel() async {
assert(_googleMap != null, 'Cannot get zoom level of a null map.');
assert(_googleMap!.zoom != null,
'Zoom level should not be null. Is the map correctly initialized?');
return _googleMap!.zoom!.toDouble();
}
// Geometry manipulation
/// Applies [CircleUpdates] to the currently managed circles.
void updateCircles(CircleUpdates updates) {
assert(
_circlesController != null, 'Cannot update circles after dispose().');
_circlesController?.addCircles(updates.circlesToAdd);
_circlesController?.changeCircles(updates.circlesToChange);
_circlesController?.removeCircles(updates.circleIdsToRemove);
}
/// Applies [PolygonUpdates] to the currently managed polygons.
void updatePolygons(PolygonUpdates updates) {
assert(
_polygonsController != null, 'Cannot update polygons after dispose().');
_polygonsController?.addPolygons(updates.polygonsToAdd);
_polygonsController?.changePolygons(updates.polygonsToChange);
_polygonsController?.removePolygons(updates.polygonIdsToRemove);
}
/// Applies [PolylineUpdates] to the currently managed lines.
void updatePolylines(PolylineUpdates updates) {
assert(_polylinesController != null,
'Cannot update polylines after dispose().');
_polylinesController?.addPolylines(updates.polylinesToAdd);
_polylinesController?.changePolylines(updates.polylinesToChange);
_polylinesController?.removePolylines(updates.polylineIdsToRemove);
}
/// Applies [MarkerUpdates] to the currently managed markers.
void updateMarkers(MarkerUpdates updates) {
assert(
_markersController != null, 'Cannot update markers after dispose().');
_markersController?.addMarkers(updates.markersToAdd);
_markersController?.changeMarkers(updates.markersToChange);
_markersController?.removeMarkers(updates.markerIdsToRemove);
}
/// Shows the [InfoWindow] of the marker identified by its [MarkerId].
void showInfoWindow(MarkerId markerId) {
assert(_markersController != null,
'Cannot show infowindow of marker [${markerId.value}] after dispose().');
_markersController?.showMarkerInfoWindow(markerId);
}
/// Hides the [InfoWindow] of the marker identified by its [MarkerId].
void hideInfoWindow(MarkerId markerId) {
assert(_markersController != null,
'Cannot hide infowindow of marker [${markerId.value}] after dispose().');
_markersController?.hideMarkerInfoWindow(markerId);
}
/// Returns true if the [InfoWindow] of the marker identified by [MarkerId] is shown.
bool isInfoWindowShown(MarkerId markerId) {
return _markersController?.isInfoWindowShown(markerId) ?? false;
}
// Cleanup
/// Disposes of this controller and its resources.
///
/// You won't be able to call many of the methods on this controller after
/// calling `dispose`!
void dispose() {
_widget = null;
_googleMap = null;
_circlesController = null;
_polygonsController = null;
_polylinesController = null;
_markersController = null;
_streamController.close();
}
}
/// A MapEvent event fired when a [mapId] on web is interactive.
class WebMapReadyEvent extends MapEvent<Object?> {
/// Build a WebMapReady Event for the map represented by `mapId`.
WebMapReadyEvent(int mapId) : super(mapId, null);
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart",
"repo_id": "plugins",
"token_count": 5461
} | 1,133 |
rootProject.name = 'google_sign_in_android'
| plugins/packages/google_sign_in/google_sign_in_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 15
} | 1,134 |
// 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.
/*
// DOM shim. This file contains everything we need from the DOM API written as
// @staticInterop, so we don't need dart:html
// https://developer.mozilla.org/en-US/docs/Web/API/
//
// (To be replaced by `package:web`)
*/
import 'package:js/js.dart';
/// Document interface
@JS()
@staticInterop
abstract class DomHtmlDocument {}
/// Some methods of document
extension DomHtmlDocumentExtension on DomHtmlDocument {
/// document.head
external DomHtmlElement get head;
/// document.createElement
external DomHtmlElement createElement(String tagName);
}
/// An instance of an HTMLElement
@JS()
@staticInterop
abstract class DomHtmlElement {}
/// (Some) methods of HtmlElement
extension DomHtmlElementExtension on DomHtmlElement {
/// Node.appendChild
external DomHtmlElement appendChild(DomHtmlElement child);
/// Element.remove
external void remove();
}
/// An instance of an HTMLMetaElement
@JS()
@staticInterop
abstract class DomHtmlMetaElement extends DomHtmlElement {}
/// Some methods exclusive of Script elements
extension DomHtmlMetaElementExtension on DomHtmlMetaElement {
external set name(String name);
external set content(String content);
}
// Getters
/// window.document
@JS()
@staticInterop
external DomHtmlDocument get document;
| plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/src/dom.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/src/dom.dart",
"repo_id": "plugins",
"token_count": 414
} | 1,135 |
group 'io.flutter.plugins.imagepicker'
version '1.0-SNAPSHOT'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.1'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 31
defaultConfig {
minSdkVersion 16
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
dependencies {
implementation 'androidx.core:core:1.8.0'
implementation 'androidx.annotation:annotation:1.3.0'
implementation 'androidx.exifinterface:exifinterface:1.3.3'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:5.1.1'
testImplementation 'androidx.test:core:1.4.0'
testImplementation "org.robolectric:robolectric:4.8.1"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
}
| plugins/packages/image_picker/image_picker_android/android/build.gradle/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/build.gradle",
"repo_id": "plugins",
"token_count": 689
} | 1,136 |
// 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 org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
// RobolectricTestRunner always creates a default mock bitmap when reading from file. So we cannot actually test the scaling.
// But we can still test whether the original or scaled file is created.
@RunWith(RobolectricTestRunner.class)
public class ImageResizerTest {
ImageResizer resizer;
File imageFile;
File externalDirectory;
Bitmap originalImageBitmap;
@Before
public void setUp() throws IOException {
MockitoAnnotations.initMocks(this);
imageFile = new File(getClass().getClassLoader().getResource("pngImage.png").getFile());
originalImageBitmap = BitmapFactory.decodeFile(imageFile.getPath());
TemporaryFolder temporaryFolder = new TemporaryFolder();
temporaryFolder.create();
externalDirectory = temporaryFolder.newFolder("image_picker_testing_path");
resizer = new ImageResizer(externalDirectory, new ExifDataCopier());
}
@Test
public void onResizeImageIfNeeded_WhenQualityIsNull_ShoultNotResize_ReturnTheUnscaledFile() {
String outoutFile = resizer.resizeImageIfNeeded(imageFile.getPath(), null, null, null);
assertThat(outoutFile, equalTo(imageFile.getPath()));
}
@Test
public void onResizeImageIfNeeded_WhenQualityIsNotNull_ShoulResize_ReturnResizedFile() {
String outoutFile = resizer.resizeImageIfNeeded(imageFile.getPath(), null, null, 50);
assertThat(outoutFile, equalTo(externalDirectory.getPath() + "/scaled_pngImage.png"));
}
@Test
public void onResizeImageIfNeeded_WhenWidthIsNotNull_ShoulResize_ReturnResizedFile() {
String outoutFile = resizer.resizeImageIfNeeded(imageFile.getPath(), 50.0, null, null);
assertThat(outoutFile, equalTo(externalDirectory.getPath() + "/scaled_pngImage.png"));
}
@Test
public void onResizeImageIfNeeded_WhenHeightIsNotNull_ShoulResize_ReturnResizedFile() {
String outoutFile = resizer.resizeImageIfNeeded(imageFile.getPath(), null, 50.0, null);
assertThat(outoutFile, equalTo(externalDirectory.getPath() + "/scaled_pngImage.png"));
}
@Test
public void onResizeImageIfNeeded_WhenParentDirectoryDoesNotExists_ShouldNotCrash() {
File nonExistentDirectory = new File(externalDirectory, "/nonExistent");
ImageResizer invalidResizer = new ImageResizer(nonExistentDirectory, new ExifDataCopier());
String outoutFile = invalidResizer.resizeImageIfNeeded(imageFile.getPath(), null, 50.0, null);
assertThat(outoutFile, equalTo(nonExistentDirectory.getPath() + "/scaled_pngImage.png"));
}
}
| plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImageResizerTest.java/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImageResizerTest.java",
"repo_id": "plugins",
"token_count": 983
} | 1,137 |
name: image_picker_for_web
description: Web platform implementation of image_picker
repository: https://github.com/flutter/plugins/tree/main/packages/image_picker/image_picker_for_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22
version: 2.1.10
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: image_picker
platforms:
web:
pluginClass: ImagePickerPlugin
fileName: image_picker_for_web.dart
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
image_picker_platform_interface: ^2.2.0
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/image_picker/image_picker_for_web/pubspec.yaml/0 | {
"file_path": "plugins/packages/image_picker/image_picker_for_web/pubspec.yaml",
"repo_id": "plugins",
"token_count": 301
} | 1,138 |
name: image_picker_windows
description: Windows platform implementation of image_picker
repository: https://github.com/flutter/plugins/tree/main/packages/image_picker/image_picker_windows
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22
version: 0.1.0+4
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: image_picker
platforms:
windows:
dartPluginClass: ImagePickerWindows
dependencies:
file_selector_platform_interface: ^2.2.0
file_selector_windows: ^0.8.2
flutter:
sdk: flutter
image_picker_platform_interface: ^2.4.3
dev_dependencies:
build_runner: ^2.1.5
flutter_test:
sdk: flutter
mockito: ^5.0.16
| plugins/packages/image_picker/image_picker_windows/pubspec.yaml/0 | {
"file_path": "plugins/packages/image_picker/image_picker_windows/pubspec.yaml",
"repo_id": "plugins",
"token_count": 315
} | 1,139 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,140 |
rootProject.name = 'in_app_purchase'
| plugins/packages/in_app_purchase/in_app_purchase_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 14
} | 1,141 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../billing_client_wrappers.dart';
import '../in_app_purchase_android.dart';
/// [IAPError.code] code for failed purchases.
const String kPurchaseErrorCode = 'purchase_error';
/// [IAPError.code] code used when a consuming a purchased item fails.
const String kConsumptionFailedErrorCode = 'consume_purchase_failed';
/// [IAPError.code] code used when a query for previous transaction has failed.
const String kRestoredPurchaseErrorCode = 'restore_transactions_failed';
/// Indicates store front is Google Play
const String kIAPSource = 'google_play';
/// An [InAppPurchasePlatform] that wraps Android BillingClient.
///
/// This translates various `BillingClient` calls and responses into the
/// generic plugin API.
class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform {
InAppPurchaseAndroidPlatform._() {
billingClient = BillingClient((PurchasesResultWrapper resultWrapper) async {
_purchaseUpdatedController
.add(await _getPurchaseDetailsFromResult(resultWrapper));
});
// Register [InAppPurchaseAndroidPlatformAddition].
InAppPurchasePlatformAddition.instance =
InAppPurchaseAndroidPlatformAddition(billingClient);
_readyFuture = _connect();
_purchaseUpdatedController =
StreamController<List<PurchaseDetails>>.broadcast();
}
/// Registers this class as the default instance of [InAppPurchasePlatform].
static void registerPlatform() {
// Register the platform instance with the plugin platform
// interface.
InAppPurchasePlatform.instance = InAppPurchaseAndroidPlatform._();
}
static late StreamController<List<PurchaseDetails>>
_purchaseUpdatedController;
@override
Stream<List<PurchaseDetails>> get purchaseStream =>
_purchaseUpdatedController.stream;
/// The [BillingClient] that's abstracted by [GooglePlayConnection].
///
/// This field should not be used out of test code.
@visibleForTesting
late final BillingClient billingClient;
late Future<void> _readyFuture;
static final Set<String> _productIdsToConsume = <String>{};
@override
Future<bool> isAvailable() async {
await _readyFuture;
return billingClient.isReady();
}
@override
Future<ProductDetailsResponse> queryProductDetails(
Set<String> identifiers) async {
List<SkuDetailsResponseWrapper> responses;
PlatformException? exception;
try {
responses = await Future.wait(<Future<SkuDetailsResponseWrapper>>[
billingClient.querySkuDetails(
skuType: SkuType.inapp, skusList: identifiers.toList()),
billingClient.querySkuDetails(
skuType: SkuType.subs, skusList: identifiers.toList())
]);
} on PlatformException catch (e) {
exception = e;
responses = <SkuDetailsResponseWrapper>[
// ignore: invalid_use_of_visible_for_testing_member
SkuDetailsResponseWrapper(
billingResult: BillingResultWrapper(
responseCode: BillingResponse.error, debugMessage: e.code),
skuDetailsList: const <SkuDetailsWrapper>[]),
// ignore: invalid_use_of_visible_for_testing_member
SkuDetailsResponseWrapper(
billingResult: BillingResultWrapper(
responseCode: BillingResponse.error, debugMessage: e.code),
skuDetailsList: const <SkuDetailsWrapper>[])
];
}
final List<ProductDetails> productDetailsList =
responses.expand((SkuDetailsResponseWrapper response) {
return response.skuDetailsList;
}).map((SkuDetailsWrapper skuDetailWrapper) {
return GooglePlayProductDetails.fromSkuDetails(skuDetailWrapper);
}).toList();
final Set<String> successIDS = productDetailsList
.map((ProductDetails productDetails) => productDetails.id)
.toSet();
final List<String> notFoundIDS =
identifiers.difference(successIDS).toList();
return ProductDetailsResponse(
productDetails: productDetailsList,
notFoundIDs: notFoundIDS,
error: exception == null
? null
: IAPError(
source: kIAPSource,
code: exception.code,
message: exception.message ?? '',
details: exception.details));
}
@override
Future<bool> buyNonConsumable({required PurchaseParam purchaseParam}) async {
ChangeSubscriptionParam? changeSubscriptionParam;
if (purchaseParam is GooglePlayPurchaseParam) {
changeSubscriptionParam = purchaseParam.changeSubscriptionParam;
}
final BillingResultWrapper billingResultWrapper =
await billingClient.launchBillingFlow(
sku: purchaseParam.productDetails.id,
accountId: purchaseParam.applicationUserName,
oldSku: changeSubscriptionParam?.oldPurchaseDetails.productID,
purchaseToken: changeSubscriptionParam
?.oldPurchaseDetails.verificationData.serverVerificationData,
prorationMode: changeSubscriptionParam?.prorationMode);
return billingResultWrapper.responseCode == BillingResponse.ok;
}
@override
Future<bool> buyConsumable(
{required PurchaseParam purchaseParam, bool autoConsume = true}) {
if (autoConsume) {
_productIdsToConsume.add(purchaseParam.productDetails.id);
}
return buyNonConsumable(purchaseParam: purchaseParam);
}
@override
Future<BillingResultWrapper> completePurchase(
PurchaseDetails purchase) async {
assert(
purchase is GooglePlayPurchaseDetails,
'On Android, the `purchase` should always be of type `GooglePlayPurchaseDetails`.',
);
final GooglePlayPurchaseDetails googlePurchase =
purchase as GooglePlayPurchaseDetails;
if (googlePurchase.billingClientPurchase.isAcknowledged) {
return const BillingResultWrapper(responseCode: BillingResponse.ok);
}
if (googlePurchase.verificationData == null) {
throw ArgumentError(
'completePurchase unsuccessful. The `purchase.verificationData` is not valid');
}
return billingClient
.acknowledgePurchase(purchase.verificationData.serverVerificationData);
}
@override
Future<void> restorePurchases({
String? applicationUserName,
}) async {
List<PurchasesResultWrapper> responses;
responses = await Future.wait(<Future<PurchasesResultWrapper>>[
billingClient.queryPurchases(SkuType.inapp),
billingClient.queryPurchases(SkuType.subs)
]);
final Set<String> errorCodeSet = responses
.where((PurchasesResultWrapper response) =>
response.responseCode != BillingResponse.ok)
.map((PurchasesResultWrapper response) =>
response.responseCode.toString())
.toSet();
final String errorMessage =
errorCodeSet.isNotEmpty ? errorCodeSet.join(', ') : '';
final List<PurchaseDetails> pastPurchases =
responses.expand((PurchasesResultWrapper response) {
return response.purchasesList;
}).map((PurchaseWrapper purchaseWrapper) {
final GooglePlayPurchaseDetails purchaseDetails =
GooglePlayPurchaseDetails.fromPurchase(purchaseWrapper);
purchaseDetails.status = PurchaseStatus.restored;
return purchaseDetails;
}).toList();
if (errorMessage.isNotEmpty) {
throw InAppPurchaseException(
source: kIAPSource,
code: kRestoredPurchaseErrorCode,
message: errorMessage,
);
}
_purchaseUpdatedController.add(pastPurchases);
}
Future<void> _connect() =>
billingClient.startConnection(onBillingServiceDisconnected: () {});
Future<PurchaseDetails> _maybeAutoConsumePurchase(
PurchaseDetails purchaseDetails) async {
if (!(purchaseDetails.status == PurchaseStatus.purchased &&
_productIdsToConsume.contains(purchaseDetails.productID))) {
return purchaseDetails;
}
final BillingResultWrapper billingResult =
await (InAppPurchasePlatformAddition.instance!
as InAppPurchaseAndroidPlatformAddition)
.consumePurchase(purchaseDetails);
final BillingResponse consumedResponse = billingResult.responseCode;
if (consumedResponse != BillingResponse.ok) {
purchaseDetails.status = PurchaseStatus.error;
purchaseDetails.error = IAPError(
source: kIAPSource,
code: kConsumptionFailedErrorCode,
message: consumedResponse.toString(),
details: billingResult.debugMessage,
);
}
_productIdsToConsume.remove(purchaseDetails.productID);
return purchaseDetails;
}
Future<List<PurchaseDetails>> _getPurchaseDetailsFromResult(
PurchasesResultWrapper resultWrapper) async {
IAPError? error;
if (resultWrapper.responseCode != BillingResponse.ok) {
error = IAPError(
source: kIAPSource,
code: kPurchaseErrorCode,
message: resultWrapper.responseCode.toString(),
details: resultWrapper.billingResult.debugMessage,
);
}
final List<Future<PurchaseDetails>> purchases =
resultWrapper.purchasesList.map((PurchaseWrapper purchase) {
final GooglePlayPurchaseDetails googlePlayPurchaseDetails =
GooglePlayPurchaseDetails.fromPurchase(purchase)..error = error;
if (resultWrapper.responseCode == BillingResponse.userCanceled) {
googlePlayPurchaseDetails.status = PurchaseStatus.canceled;
}
return _maybeAutoConsumePurchase(googlePlayPurchaseDetails);
}).toList();
if (purchases.isNotEmpty) {
return Future.wait(purchases);
} else {
PurchaseStatus status = PurchaseStatus.error;
if (resultWrapper.responseCode == BillingResponse.userCanceled) {
status = PurchaseStatus.canceled;
} else if (resultWrapper.responseCode == BillingResponse.ok) {
status = PurchaseStatus.purchased;
}
return <PurchaseDetails>[
PurchaseDetails(
purchaseID: '',
productID: '',
status: status,
transactionDate: null,
verificationData: PurchaseVerificationData(
localVerificationData: '',
serverVerificationData: '',
source: kIAPSource))
..error = error
];
}
}
}
| plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart",
"repo_id": "plugins",
"token_count": 3763
} | 1,142 |
// 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:ios_platform_images/ios_platform_images.dart';
void main() {
const MethodChannel channel =
MethodChannel('plugins.flutter.io/ios_platform_images');
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
return '42';
});
});
tearDown(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
test('resolveURL', () async {
expect(await IosPlatformImages.resolveURL('foobar'), '42');
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/ios_platform_images/test/ios_platform_images_test.dart/0 | {
"file_path": "plugins/packages/ios_platform_images/test/ios_platform_images_test.dart",
"repo_id": "plugins",
"token_count": 408
} | 1,143 |
<resources>
<dimen name="body_text_size">14sp</dimen>
<dimen name="medium_text_size">16sp</dimen>
<dimen name="huge_text_size">20sp</dimen>
</resources>
| plugins/packages/local_auth/local_auth_android/android/src/main/res/values/dimens.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/values/dimens.xml",
"repo_id": "plugins",
"token_count": 65
} | 1,144 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.0.22
* Removes unused Guava dependency.
## 2.0.21
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
* Upgrades `androidx.annotation` version to 1.5.0.
* Upgrades Android Gradle plugin version to 7.3.1.
## 2.0.20
* Reverts changes in versions 2.0.18 and 2.0.19.
## 2.0.19
* Bumps kotlin to 1.7.10
## 2.0.18
* Bumps `androidx.annotation:annotation` version to 1.4.0.
* Bumps gradle version to 7.2.2.
## 2.0.17
* Lower minimim version back to 2.8.1.
## 2.0.16
* Fixes bug with `getExternalStoragePaths(null)`.
## 2.0.15
* Switches the medium from MethodChannels to Pigeon.
## 2.0.14
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.13
* Fixes typing build warning.
## 2.0.12
* Returns to using a different platform channel name, undoing the revert in
2.0.11, but updates the minimum Flutter version to 2.8 to avoid the issue
that caused the revert.
## 2.0.11
* Temporarily reverts the platform channel name change from 2.0.10 in order to
restore compatibility with Flutter versions earlier than 2.8.
## 2.0.10
* Switches to a package-internal implementation of the platform interface.
## 2.0.9
* Updates Android compileSdkVersion to 31.
## 2.0.8
* Updates example app Android compileSdkVersion to 31.
* Fixes typing build warning.
## 2.0.7
* Fixes link in README.
## 2.0.6
* Split from `path_provider` as a federated implementation.
| plugins/packages/path_provider/path_provider_android/CHANGELOG.md/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 558
} | 1,145 |
// 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(
input: 'pigeons/messages.dart',
javaOut:
'android/src/main/java/io/flutter/plugins/pathprovider/Messages.java',
javaOptions: JavaOptions(
className: 'Messages', package: 'io.flutter.plugins.pathprovider'),
dartOut: 'lib/messages.g.dart',
dartTestOut: 'test/messages_test.g.dart',
copyrightHeader: 'pigeons/copyright.txt',
))
enum StorageDirectory {
root,
music,
podcasts,
ringtones,
alarms,
notifications,
pictures,
movies,
downloads,
dcim,
documents,
}
@HostApi(dartHostTestHandler: 'TestPathProviderApi')
abstract class PathProviderApi {
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
String? getTemporaryPath();
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
String? getApplicationSupportPath();
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
String? getApplicationDocumentsPath();
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
String? getExternalStoragePath();
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
List<String?> getExternalCachePaths();
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
List<String?> getExternalStoragePaths(StorageDirectory directory);
}
| plugins/packages/path_provider/path_provider_android/pigeons/messages.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/pigeons/messages.dart",
"repo_id": "plugins",
"token_count": 455
} | 1,146 |
// 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 (v5.0.0), 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, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports
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';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider_foundation/messages.g.dart';
abstract class TestPathProviderApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
String? getDirectoryPath(DirectoryType type);
static void setup(TestPathProviderApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getDirectoryPath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.PathProviderApi.getDirectoryPath was null.');
final List<Object?> args = (message as List<Object?>?)!;
final DirectoryType? arg_type =
args[0] == null ? null : DirectoryType.values[args[0] as int];
assert(arg_type != null,
'Argument for dev.flutter.pigeon.PathProviderApi.getDirectoryPath was null, expected non-null DirectoryType.');
final String? output = api.getDirectoryPath(arg_type!);
return <Object?>[output];
});
}
}
}
}
| plugins/packages/path_provider/path_provider_foundation/test/messages_test.g.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_foundation/test/messages_test.g.dart",
"repo_id": "plugins",
"token_count": 729
} | 1,147 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.0.5
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 2.0.4
* Minor fixes for new analysis options.
* Removes unnecessary imports.
## 2.0.3
* Removes dependency on `meta`.
## 2.0.2
* Update to use the `verify` method introduced in plugin_platform_interface 2.1.0.
## 2.0.1
* Update platform_plugin_interface version requirement.
## 2.0.0
* Migrate to null safety.
## 1.0.5
* Update Flutter SDK constraint.
## 1.0.4
* Remove unused `test` dependency.
## 1.0.3
* Increase upper range of `package:platform` constraint to allow 3.X versions.
## 1.0.2
* Update lower bound of dart dependency to 2.1.0.
## 1.0.1
* Rename enum to StorageDirectory for backwards compatibility.
## 1.0.0
* Initial release.
| plugins/packages/path_provider/path_provider_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/path_provider/path_provider_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 286
} | 1,148 |
## NEXT
* Updates minimum supported Dart version.
## 2.1.3
* Minor fixes for new analysis options.
* Adds additional tests for `PlatformInterface` and `MockPlatformInterfaceMixin`.
* Modifies `PlatformInterface` to use an expando for detecting if a customer
tries to implement PlatformInterface using `implements` rather than `extends`.
This ensures that `verify` will continue to work as advertized after
https://github.com/dart-lang/language/issues/2020 is implemented.
## 2.1.2
* Updates README to demonstrate `verify` rather than `verifyToken`, and to note
that the test mixin applies to fakes as well as mocks.
* Adds an additional test for `verifyToken`.
## 2.1.1
* Fixes `verify` to work with fake objects, not just mocks.
## 2.1.0
* Introduce `verify`, which prevents use of `const Object()` as instance token.
* Add a comment indicating that `verifyToken` will be deprecated in a future release.
## 2.0.2
* Update package description.
## 2.0.1
* Fix `federated flutter plugins` link in the README.md.
## 2.0.0
* Migrate to null safety.
## 1.0.3
* Fix homepage in `pubspec.yaml`.
## 1.0.2
* Make the pedantic dev_dependency explicit.
## 1.0.1
* Fixed a bug that made all platform interfaces appear as mocks in release builds (https://github.com/flutter/flutter/issues/46941).
## 1.0.0 - Initial release.
* Provides `PlatformInterface` with common mechanism for enforcing that a platform interface
is not implemented with `implements`.
* Provides test only `MockPlatformInterface` to enable using Mockito to mock platform interfaces.
| plugins/packages/plugin_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/plugin_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 467
} | 1,149 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:quick_actions_ios/quick_actions_ios.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Can set shortcuts', (WidgetTester tester) async {
final QuickActionsIos quickActions = QuickActionsIos();
await quickActions.initialize((String value) {});
const ShortcutItem shortCutItem = ShortcutItem(
type: 'action_one',
localizedTitle: 'Action one',
icon: 'AppIcon',
);
expect(
quickActions.setShortcutItems(<ShortcutItem>[shortCutItem]), completes);
});
}
| plugins/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart",
"repo_id": "plugins",
"token_count": 275
} | 1,150 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart';
export 'package:quick_actions_platform_interface/types/types.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/quick_actions_ios');
/// An implementation of [QuickActionsPlatform] for iOS.
class QuickActionsIos extends QuickActionsPlatform {
/// Registers this class as the default instance of [QuickActionsPlatform].
static void registerWith() {
QuickActionsPlatform.instance = QuickActionsIos();
}
/// The MethodChannel that is being used by this implementation of the plugin.
@visibleForTesting
MethodChannel get channel => _channel;
@override
Future<void> initialize(QuickActionHandler handler) async {
channel.setMethodCallHandler((MethodCall call) async {
assert(call.method == 'launch');
handler(call.arguments as String);
});
final String? action =
await channel.invokeMethod<String?>('getLaunchAction');
if (action != null) {
handler(action);
}
}
@override
Future<void> setShortcutItems(List<ShortcutItem> items) async {
final List<Map<String, String?>> itemsList =
items.map(_serializeItem).toList();
await channel.invokeMethod<void>('setShortcutItems', itemsList);
}
@override
Future<void> clearShortcutItems() =>
channel.invokeMethod<void>('clearShortcutItems');
Map<String, String?> _serializeItem(ShortcutItem item) {
return <String, String?>{
'type': item.type,
'localizedTitle': item.localizedTitle,
'icon': item.icon,
};
}
}
| plugins/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart",
"repo_id": "plugins",
"token_count": 587
} | 1,151 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert' show json;
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:flutter/foundation.dart' show debugPrint, visibleForTesting;
import 'package:path/path.dart' as path;
import 'package:path_provider_linux/path_provider_linux.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
/// The Linux implementation of [SharedPreferencesStorePlatform].
///
/// This class implements the `package:shared_preferences` functionality for Linux.
class SharedPreferencesLinux extends SharedPreferencesStorePlatform {
/// Deprecated instance of [SharedPreferencesLinux].
/// Use [SharedPreferencesStorePlatform.instance] instead.
@Deprecated('Use `SharedPreferencesStorePlatform.instance` instead.')
static SharedPreferencesLinux instance = SharedPreferencesLinux();
/// Registers the Linux implementation.
static void registerWith() {
SharedPreferencesStorePlatform.instance = SharedPreferencesLinux();
}
/// Local copy of preferences
Map<String, Object>? _cachedPreferences;
/// File system used to store to disk. Exposed for testing only.
@visibleForTesting
FileSystem fs = const LocalFileSystem();
/// The path_provider_linux instance used to find the support directory.
@visibleForTesting
PathProviderLinux pathProvider = PathProviderLinux();
/// Gets the file where the preferences are stored.
Future<File?> _getLocalDataFile() async {
final String? directory = await pathProvider.getApplicationSupportPath();
if (directory == null) {
return null;
}
return fs.file(path.join(directory, 'shared_preferences.json'));
}
/// Gets the preferences from the stored file. Once read, the preferences are
/// maintained in memory.
Future<Map<String, Object>> _readPreferences() async {
if (_cachedPreferences != null) {
return _cachedPreferences!;
}
Map<String, Object> preferences = <String, Object>{};
final File? localDataFile = await _getLocalDataFile();
if (localDataFile != null && localDataFile.existsSync()) {
final String stringMap = localDataFile.readAsStringSync();
if (stringMap.isNotEmpty) {
final Object? data = json.decode(stringMap);
if (data is Map) {
preferences = data.cast<String, Object>();
}
}
}
_cachedPreferences = preferences;
return preferences;
}
/// Writes the cached preferences to disk. Returns [true] if the operation
/// succeeded.
Future<bool> _writePreferences(Map<String, Object> preferences) async {
try {
final File? localDataFile = await _getLocalDataFile();
if (localDataFile == null) {
debugPrint('Unable to determine where to write preferences.');
return false;
}
if (!localDataFile.existsSync()) {
localDataFile.createSync(recursive: true);
}
final String stringMap = json.encode(preferences);
localDataFile.writeAsStringSync(stringMap);
} catch (e) {
debugPrint('Error saving preferences to disk: $e');
return false;
}
return true;
}
@override
Future<bool> clear() async {
final Map<String, Object> preferences = await _readPreferences();
preferences.clear();
return _writePreferences(preferences);
}
@override
Future<Map<String, Object>> getAll() async {
return _readPreferences();
}
@override
Future<bool> remove(String key) async {
final Map<String, Object> preferences = await _readPreferences();
preferences.remove(key);
return _writePreferences(preferences);
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
final Map<String, Object> preferences = await _readPreferences();
preferences[key] = value;
return _writePreferences(preferences);
}
}
| plugins/packages/shared_preferences/shared_preferences_linux/lib/shared_preferences_linux.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_linux/lib/shared_preferences_linux.dart",
"repo_id": "plugins",
"token_count": 1271
} | 1,152 |
name: url_launcher_ios
description: iOS implementation of the url_launcher plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 6.1.0
environment:
sdk: '>=2.18.0 <3.0.0'
flutter: ">=3.3.0"
flutter:
plugin:
implements: url_launcher
platforms:
ios:
pluginClass: FLTURLLauncherPlugin
dartPluginClass: UrlLauncherIOS
dependencies:
flutter:
sdk: flutter
url_launcher_platform_interface: ^2.0.3
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
test: ^1.16.3
| plugins/packages/url_launcher/url_launcher_ios/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_ios/pubspec.yaml",
"repo_id": "plugins",
"token_count": 316
} | 1,153 |
name: url_launcher_platform_interface
description: A common platform interface for the url_launcher plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 2.1.1
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
| plugins/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml",
"repo_id": "plugins",
"token_count": 267
} | 1,154 |
name: video_player_for_web_integration_tests
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
js: ^0.6.0
video_player_platform_interface: ">=4.2.0 <7.0.0"
video_player_web:
path: ../
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
| plugins/packages/video_player/video_player_web/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/video_player/video_player_web/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 184
} | 1,155 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import webview_flutter;
// OCMock library doesn't generate a valid modulemap.
#import <OCMock/OCMock.h>
@interface FLTWKNavigationDelegateTests : XCTestCase
@property(strong, nonatomic) FlutterMethodChannel *mockMethodChannel;
@property(strong, nonatomic) FLTWKNavigationDelegate *navigationDelegate;
@end
@implementation FLTWKNavigationDelegateTests
- (void)setUp {
self.mockMethodChannel = OCMClassMock(FlutterMethodChannel.class);
self.navigationDelegate =
[[FLTWKNavigationDelegate alloc] initWithChannel:self.mockMethodChannel];
}
- (void)testWebViewWebContentProcessDidTerminateCallsRecourseErrorChannel {
WKWebView *webview = OCMClassMock(WKWebView.class);
[self.navigationDelegate webViewWebContentProcessDidTerminate:webview];
OCMVerify([self.mockMethodChannel invokeMethod:@"onWebResourceError"
arguments:[OCMArg checkWithBlock:^BOOL(NSDictionary *args) {
XCTAssertEqualObjects(args[@"errorType"],
@"webContentProcessTerminated");
return true;
}]]);
}
@end
| plugins/packages/webview_flutter/webview_flutter/example/ios/RunnerTests/FLTWKNavigationDelegateTests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/example/ios/RunnerTests/FLTWKNavigationDelegateTests.m",
"repo_id": "plugins",
"token_count": 608
} | 1,156 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import io.flutter.plugins.webviewflutter.DownloadListenerHostApiImpl.DownloadListenerCreator;
import io.flutter.plugins.webviewflutter.DownloadListenerHostApiImpl.DownloadListenerImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class DownloadListenerTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public DownloadListenerFlutterApiImpl mockFlutterApi;
InstanceManager instanceManager;
DownloadListenerHostApiImpl hostApiImpl;
DownloadListenerImpl downloadListener;
@Before
public void setUp() {
instanceManager = InstanceManager.open(identifier -> {});
final DownloadListenerCreator downloadListenerCreator =
new DownloadListenerCreator() {
@Override
public DownloadListenerImpl createDownloadListener(
DownloadListenerFlutterApiImpl flutterApi) {
downloadListener = super.createDownloadListener(flutterApi);
return downloadListener;
}
};
hostApiImpl =
new DownloadListenerHostApiImpl(instanceManager, downloadListenerCreator, mockFlutterApi);
hostApiImpl.create(0L);
}
@After
public void tearDown() {
instanceManager.close();
}
@Test
public void postMessage() {
downloadListener.onDownloadStart(
"https://www.google.com", "userAgent", "contentDisposition", "mimetype", 54);
verify(mockFlutterApi)
.onDownloadStart(
eq(downloadListener),
eq("https://www.google.com"),
eq("userAgent"),
eq("contentDisposition"),
eq("mimetype"),
eq(54L),
any());
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/DownloadListenerTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/DownloadListenerTest.java",
"repo_id": "plugins",
"token_count": 782
} | 1,157 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
void main() {
runApp(const MaterialApp(home: WebViewExample()));
}
const String kNavigationExamplePage = '''
<!DOCTYPE html><html>
<head><title>Navigation Delegate Example</title></head>
<body>
<p>
The navigation delegate is set to block navigation to the youtube website.
</p>
<ul>
<ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
<ul><a href="https://www.google.com/">https://www.google.com/</a></ul>
</ul>
</body>
</html>
''';
const String kLocalExamplePage = '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Load file or HTML string example</title>
</head>
<body>
<h1>Local demo page</h1>
<p>
This is an example page used to demonstrate how to load a local file or HTML
string using the <a href="https://pub.dev/packages/webview_flutter">Flutter
webview</a> plugin.
</p>
</body>
</html>
''';
const String kTransparentBackgroundPage = '''
<!DOCTYPE html>
<html>
<head>
<title>Transparent background test</title>
</head>
<style type="text/css">
body { background: transparent; margin: 0; padding: 0; }
#container { position: relative; margin: 0; padding: 0; width: 100vw; height: 100vh; }
#shape { background: #FF0000; width: 200px; height: 100%; margin: 0; padding: 0; position: absolute; top: 0; bottom: 0; left: calc(50% - 100px); }
p { text-align: center; }
</style>
<body>
<div id="container">
<p>Transparent background test</p>
<div id="shape"></div>
</div>
</body>
</html>
''';
class WebViewExample extends StatefulWidget {
const WebViewExample({Key? key, this.cookieManager}) : super(key: key);
final PlatformWebViewCookieManager? cookieManager;
@override
State<WebViewExample> createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
late final PlatformWebViewController _controller;
@override
void initState() {
super.initState();
_controller = PlatformWebViewController(
AndroidWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x80000000))
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)
..setOnProgress((int progress) {
debugPrint('WebView is loading (progress : $progress%)');
})
..setOnPageStarted((String url) {
debugPrint('Page started loading: $url');
})
..setOnPageFinished((String url) {
debugPrint('Page finished loading: $url');
})
..setOnWebResourceError((WebResourceError error) {
debugPrint('''
Page resource error:
code: ${error.errorCode}
description: ${error.description}
errorType: ${error.errorType}
isForMainFrame: ${error.isForMainFrame}
''');
})
..setOnNavigationRequest((NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
debugPrint('blocking navigation to ${request.url}');
return NavigationDecision.prevent;
}
debugPrint('allowing navigation to ${request.url}');
return NavigationDecision.navigate;
}),
)
..addJavaScriptChannel(JavaScriptChannelParams(
name: 'Toaster',
onMessageReceived: (JavaScriptMessage message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message.message)),
);
},
))
..loadRequest(LoadRequestParams(
uri: Uri.parse('https://flutter.dev'),
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF4CAF50),
appBar: AppBar(
title: const Text('Flutter WebView example'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
NavigationControls(webViewController: _controller),
SampleMenu(
webViewController: _controller,
cookieManager: widget.cookieManager,
),
],
),
body: PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: _controller),
).build(context),
floatingActionButton: favoriteButton(),
);
}
Widget favoriteButton() {
return FloatingActionButton(
onPressed: () async {
final String? url = await _controller.currentUrl();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Favorited $url')),
);
}
},
child: const Icon(Icons.favorite),
);
}
}
enum MenuOptions {
showUserAgent,
listCookies,
clearCookies,
addToCache,
listCache,
clearCache,
navigationDelegate,
doPostRequest,
loadLocalFile,
loadFlutterAsset,
loadHtmlString,
transparentBackground,
setCookie,
}
class SampleMenu extends StatelessWidget {
SampleMenu({
Key? key,
required this.webViewController,
PlatformWebViewCookieManager? cookieManager,
}) : cookieManager = cookieManager ??
PlatformWebViewCookieManager(
const PlatformWebViewCookieManagerCreationParams(),
),
super(key: key);
final PlatformWebViewController webViewController;
late final PlatformWebViewCookieManager cookieManager;
@override
Widget build(BuildContext context) {
return PopupMenuButton<MenuOptions>(
key: const ValueKey<String>('ShowPopupMenu'),
onSelected: (MenuOptions value) {
switch (value) {
case MenuOptions.showUserAgent:
_onShowUserAgent();
break;
case MenuOptions.listCookies:
_onListCookies(context);
break;
case MenuOptions.clearCookies:
_onClearCookies(context);
break;
case MenuOptions.addToCache:
_onAddToCache(context);
break;
case MenuOptions.listCache:
_onListCache();
break;
case MenuOptions.clearCache:
_onClearCache(context);
break;
case MenuOptions.navigationDelegate:
_onNavigationDelegateExample();
break;
case MenuOptions.doPostRequest:
_onDoPostRequest();
break;
case MenuOptions.loadLocalFile:
_onLoadLocalFileExample();
break;
case MenuOptions.loadFlutterAsset:
_onLoadFlutterAssetExample();
break;
case MenuOptions.loadHtmlString:
_onLoadHtmlStringExample();
break;
case MenuOptions.transparentBackground:
_onTransparentBackground();
break;
case MenuOptions.setCookie:
_onSetCookie();
break;
}
},
itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
const PopupMenuItem<MenuOptions>(
value: MenuOptions.showUserAgent,
child: Text('Show user agent'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCookies,
child: Text('List cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCookies,
child: Text('Clear cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.addToCache,
child: Text('Add to cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCache,
child: Text('List cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCache,
child: Text('Clear cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.navigationDelegate,
child: Text('Navigation Delegate example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.doPostRequest,
child: Text('Post Request'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadHtmlString,
child: Text('Load HTML string'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadLocalFile,
child: Text('Load local file'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadFlutterAsset,
child: Text('Load Flutter Asset'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.setCookie,
child: Text('Set cookie'),
),
const PopupMenuItem<MenuOptions>(
key: ValueKey<String>('ShowTransparentBackgroundExample'),
value: MenuOptions.transparentBackground,
child: Text('Transparent background example'),
),
],
);
}
Future<void> _onShowUserAgent() {
// Send a message with the user agent string to the Toaster JavaScript channel we registered
// with the WebView.
return webViewController.runJavaScript(
'Toaster.postMessage("User Agent: " + navigator.userAgent);',
);
}
Future<void> _onListCookies(BuildContext context) async {
final String cookies = await webViewController
.runJavaScriptReturningResult('document.cookie') as String;
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Cookies:'),
_getCookieList(cookies),
],
),
));
}
}
Future<void> _onAddToCache(BuildContext context) async {
await webViewController.runJavaScript(
'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";',
);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Added a test entry to cache.'),
));
}
}
Future<void> _onListCache() {
return webViewController.runJavaScript('caches.keys()'
// ignore: missing_whitespace_between_adjacent_strings
'.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))'
'.then((caches) => Toaster.postMessage(caches))');
}
Future<void> _onClearCache(BuildContext context) async {
await webViewController.clearCache();
await webViewController.clearLocalStorage();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Cache cleared.'),
));
}
}
Future<void> _onClearCookies(BuildContext context) async {
final bool hadCookies = await cookieManager.clearCookies();
String message = 'There were cookies. Now, they are gone!';
if (!hadCookies) {
message = 'There are no cookies.';
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
));
}
}
Future<void> _onNavigationDelegateExample() {
final String contentBase64 = base64Encode(
const Utf8Encoder().convert(kNavigationExamplePage),
);
return webViewController.loadRequest(
LoadRequestParams(
uri: Uri.parse('data:text/html;base64,$contentBase64'),
),
);
}
Future<void> _onSetCookie() async {
await cookieManager.setCookie(
const WebViewCookie(
name: 'foo',
value: 'bar',
domain: 'httpbin.org',
path: '/anything',
),
);
await webViewController.loadRequest(LoadRequestParams(
uri: Uri.parse('https://httpbin.org/anything'),
));
}
Future<void> _onDoPostRequest() {
return webViewController.loadRequest(LoadRequestParams(
uri: Uri.parse('https://httpbin.org/post'),
method: LoadRequestMethod.post,
headers: const <String, String>{
'foo': 'bar',
'Content-Type': 'text/plain',
},
body: Uint8List.fromList('Test Body'.codeUnits),
));
}
Future<void> _onLoadLocalFileExample() async {
final String pathToIndex = await _prepareLocalFile();
await webViewController.loadFile(pathToIndex);
}
Future<void> _onLoadFlutterAssetExample() {
return webViewController.loadFlutterAsset('assets/www/index.html');
}
Future<void> _onLoadHtmlStringExample() {
return webViewController.loadHtmlString(kLocalExamplePage);
}
Future<void> _onTransparentBackground() {
return webViewController.loadHtmlString(kTransparentBackgroundPage);
}
Widget _getCookieList(String cookies) {
if (cookies == null || cookies == '""') {
return Container();
}
final List<String> cookieList = cookies.split(';');
final Iterable<Text> cookieWidgets =
cookieList.map((String cookie) => Text(cookie));
return Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: cookieWidgets.toList(),
);
}
static Future<String> _prepareLocalFile() async {
final String tmpDir = (await getTemporaryDirectory()).path;
final File indexFile = File(
<String>{tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator));
await indexFile.create(recursive: true);
await indexFile.writeAsString(kLocalExamplePage);
return indexFile.path;
}
}
class NavigationControls extends StatelessWidget {
const NavigationControls({Key? key, required this.webViewController})
: super(key: key);
final PlatformWebViewController webViewController;
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () async {
if (await webViewController.canGoBack()) {
await webViewController.goBack();
} else {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No back history item')),
);
}
}
},
),
IconButton(
icon: const Icon(Icons.arrow_forward_ios),
onPressed: () async {
if (await webViewController.canGoForward()) {
await webViewController.goForward();
} else {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No forward history item')),
);
}
}
},
),
IconButton(
icon: const Icon(Icons.replay),
onPressed: () => webViewController.reload(),
),
],
);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/example/lib/main.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 6349
} | 1,158 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFObjectHostApiTests : XCTestCase
@end
@implementation FWFObjectHostApiTests
/**
* Creates a partially mocked FWFObject and adds it to instanceManager.
*
* @param instanceManager Instance manager to add the delegate to.
* @param identifier Identifier for the delegate added to the instanceManager.
*
* @return A mock FWFObject.
*/
- (id)mockObjectWithManager:(FWFInstanceManager *)instanceManager identifier:(long)identifier {
FWFObject *object =
[[FWFObject alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
[instanceManager addDartCreatedInstance:object withIdentifier:0];
return OCMPartialMock(object);
}
/**
* Creates a mock FWFObjectFlutterApiImpl with instanceManager.
*
* @param instanceManager Instance manager passed to the Flutter API.
*
* @return A mock FWFObjectFlutterApiImpl.
*/
- (id)mockFlutterApiWithManager:(FWFInstanceManager *)instanceManager {
FWFObjectFlutterApiImpl *flutterAPI = [[FWFObjectFlutterApiImpl alloc]
initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
return OCMPartialMock(flutterAPI);
}
- (void)testAddObserver {
NSObject *mockObject = OCMClassMock([NSObject class]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockObject withIdentifier:0];
FWFObjectHostApiImpl *hostAPI =
[[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager];
NSObject *observerObject = [[NSObject alloc] init];
[instanceManager addDartCreatedInstance:observerObject withIdentifier:1];
FlutterError *error;
[hostAPI
addObserverForObjectWithIdentifier:@0
observerIdentifier:@1
keyPath:@"myKey"
options:@[
[FWFNSKeyValueObservingOptionsEnumData
makeWithValue:FWFNSKeyValueObservingOptionsEnumOldValue],
[FWFNSKeyValueObservingOptionsEnumData
makeWithValue:FWFNSKeyValueObservingOptionsEnumNewValue]
]
error:&error];
OCMVerify([mockObject addObserver:observerObject
forKeyPath:@"myKey"
options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew)
context:nil]);
XCTAssertNil(error);
}
- (void)testRemoveObserver {
NSObject *mockObject = OCMClassMock([NSObject class]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockObject withIdentifier:0];
FWFObjectHostApiImpl *hostAPI =
[[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager];
NSObject *observerObject = [[NSObject alloc] init];
[instanceManager addDartCreatedInstance:observerObject withIdentifier:1];
FlutterError *error;
[hostAPI removeObserverForObjectWithIdentifier:@0
observerIdentifier:@1
keyPath:@"myKey"
error:&error];
OCMVerify([mockObject removeObserver:observerObject forKeyPath:@"myKey"]);
XCTAssertNil(error);
}
- (void)testDispose {
NSObject *object = [[NSObject alloc] init];
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:object withIdentifier:0];
FWFObjectHostApiImpl *hostAPI =
[[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
[hostAPI disposeObjectWithIdentifier:@0 error:&error];
// Only the strong reference is removed, so the weak reference will remain until object is set to
// nil.
object = nil;
XCTAssertFalse([instanceManager containsInstance:object]);
XCTAssertNil(error);
}
- (void)testObserveValueForKeyPath {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFObject *mockObject = [self mockObjectWithManager:instanceManager identifier:0];
FWFObjectFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager];
OCMStub([mockObject objectApi]).andReturn(mockFlutterAPI);
NSObject *object = [[NSObject alloc] init];
[instanceManager addDartCreatedInstance:object withIdentifier:1];
[mockObject observeValueForKeyPath:@"keyPath"
ofObject:object
change:@{NSKeyValueChangeOldKey : @"key"}
context:nil];
OCMVerify([mockFlutterAPI
observeValueForObjectWithIdentifier:@0
keyPath:@"keyPath"
objectIdentifier:@1
changeKeys:[OCMArg checkWithBlock:^BOOL(
NSArray<FWFNSKeyValueChangeKeyEnumData *>
*value) {
return value[0].value == FWFNSKeyValueChangeKeyEnumOldValue;
}]
changeValues:[OCMArg checkWithBlock:^BOOL(id value) {
return [@"key" isEqual:value[0]];
}]
completion:OCMOCK_ANY]);
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFObjectHostApiTests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFObjectHostApiTests.m",
"repo_id": "plugins",
"token_count": 2518
} | 1,159 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
// ignore: implementation_imports
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import '../common/weak_reference_utils.dart';
import '../foundation/foundation.dart';
import '../web_kit/web_kit.dart';
/// A [Widget] that displays a [WKWebView].
class WebKitWebViewWidget extends StatefulWidget {
/// Constructs a [WebKitWebViewWidget].
const WebKitWebViewWidget({
super.key,
required this.creationParams,
required this.callbacksHandler,
required this.javascriptChannelRegistry,
required this.onBuildWidget,
this.configuration,
@visibleForTesting this.webViewProxy = const WebViewWidgetProxy(),
});
/// The initial parameters used to setup the WebView.
final CreationParams creationParams;
/// The handler of callbacks made made by [NavigationDelegate].
final WebViewPlatformCallbacksHandler callbacksHandler;
/// Manager of named JavaScript channels and forwarding incoming messages on the correct channel.
final JavascriptChannelRegistry javascriptChannelRegistry;
/// A collection of properties used to initialize a web view.
///
/// If null, a default configuration is used.
final WKWebViewConfiguration? configuration;
/// The handler for constructing [WKWebView]s and calling static methods.
///
/// This should only be changed for testing purposes.
final WebViewWidgetProxy webViewProxy;
/// A callback to build a widget once [WKWebView] has been initialized.
final Widget Function(WebKitWebViewPlatformController controller)
onBuildWidget;
@override
State<StatefulWidget> createState() => _WebKitWebViewWidgetState();
}
class _WebKitWebViewWidgetState extends State<WebKitWebViewWidget> {
late final WebKitWebViewPlatformController controller;
@override
void initState() {
super.initState();
controller = WebKitWebViewPlatformController(
creationParams: widget.creationParams,
callbacksHandler: widget.callbacksHandler,
javascriptChannelRegistry: widget.javascriptChannelRegistry,
configuration: widget.configuration,
webViewProxy: widget.webViewProxy,
);
}
@override
Widget build(BuildContext context) {
return widget.onBuildWidget(controller);
}
}
/// An implementation of [WebViewPlatformController] with the WebKit api.
class WebKitWebViewPlatformController extends WebViewPlatformController {
/// Construct a [WebKitWebViewPlatformController].
WebKitWebViewPlatformController({
required CreationParams creationParams,
required this.callbacksHandler,
required this.javascriptChannelRegistry,
WKWebViewConfiguration? configuration,
@visibleForTesting this.webViewProxy = const WebViewWidgetProxy(),
}) : super(callbacksHandler) {
_setCreationParams(
creationParams,
configuration: configuration ?? WKWebViewConfiguration(),
);
}
bool _zoomEnabled = true;
bool _hasNavigationDelegate = false;
bool _progressObserverSet = false;
final Map<String, WKScriptMessageHandler> _scriptMessageHandlers =
<String, WKScriptMessageHandler>{};
/// Handles callbacks that are made by navigation.
final WebViewPlatformCallbacksHandler callbacksHandler;
/// Manages named JavaScript channels and forwarding incoming messages on the correct channel.
final JavascriptChannelRegistry javascriptChannelRegistry;
/// Handles constructing a [WKWebView].
///
/// This should only be changed when used for testing.
final WebViewWidgetProxy webViewProxy;
/// Represents the WebView maintained by platform code.
late final WKWebView webView;
/// Used to integrate custom user interface elements into web view interactions.
@visibleForTesting
late final WKUIDelegate uiDelegate = webViewProxy.createUIDelgate(
onCreateWebView: (
WKWebView webView,
WKWebViewConfiguration configuration,
WKNavigationAction navigationAction,
) {
if (!navigationAction.targetFrame.isMainFrame) {
webView.loadRequest(navigationAction.request);
}
},
);
/// Methods for handling navigation changes and tracking navigation requests.
@visibleForTesting
late final WKNavigationDelegate navigationDelegate = withWeakRefenceTo(
this,
(WeakReference<WebKitWebViewPlatformController> weakReference) {
return webViewProxy.createNavigationDelegate(
didFinishNavigation: (WKWebView webView, String? url) {
weakReference.target?.callbacksHandler.onPageFinished(url ?? '');
},
didStartProvisionalNavigation: (WKWebView webView, String? url) {
weakReference.target?.callbacksHandler.onPageStarted(url ?? '');
},
decidePolicyForNavigationAction: (
WKWebView webView,
WKNavigationAction action,
) async {
if (weakReference.target == null) {
return WKNavigationActionPolicy.allow;
}
if (!weakReference.target!._hasNavigationDelegate) {
return WKNavigationActionPolicy.allow;
}
final bool allow =
await weakReference.target!.callbacksHandler.onNavigationRequest(
url: action.request.url,
isForMainFrame: action.targetFrame.isMainFrame,
);
return allow
? WKNavigationActionPolicy.allow
: WKNavigationActionPolicy.cancel;
},
didFailNavigation: (WKWebView webView, NSError error) {
weakReference.target?.callbacksHandler.onWebResourceError(
_toWebResourceError(error),
);
},
didFailProvisionalNavigation: (WKWebView webView, NSError error) {
weakReference.target?.callbacksHandler.onWebResourceError(
_toWebResourceError(error),
);
},
webViewWebContentProcessDidTerminate: (WKWebView webView) {
weakReference.target?.callbacksHandler.onWebResourceError(
WebResourceError(
errorCode: WKErrorCode.webContentProcessTerminated,
// Value from https://developer.apple.com/documentation/webkit/wkerrordomain?language=objc.
domain: 'WKErrorDomain',
description: '',
errorType: WebResourceErrorType.webContentProcessTerminated,
),
);
},
);
},
);
Future<void> _setCreationParams(
CreationParams params, {
required WKWebViewConfiguration configuration,
}) async {
_setWebViewConfiguration(
configuration,
allowsInlineMediaPlayback: params.webSettings?.allowsInlineMediaPlayback,
autoMediaPlaybackPolicy: params.autoMediaPlaybackPolicy,
);
webView = webViewProxy.createWebView(
configuration,
observeValue: withWeakRefenceTo(
callbacksHandler,
(WeakReference<WebViewPlatformCallbacksHandler> weakReference) {
return (
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) {
final double progress =
change[NSKeyValueChangeKey.newValue]! as double;
weakReference.target?.onProgress((progress * 100).round());
};
},
),
);
webView.setUIDelegate(uiDelegate);
await addJavascriptChannels(params.javascriptChannelNames);
webView.setNavigationDelegate(navigationDelegate);
if (params.userAgent != null) {
webView.setCustomUserAgent(params.userAgent);
}
if (params.webSettings != null) {
updateSettings(params.webSettings!);
}
if (params.backgroundColor != null) {
webView.setOpaque(false);
webView.setBackgroundColor(Colors.transparent);
webView.scrollView.setBackgroundColor(params.backgroundColor);
}
if (params.initialUrl != null) {
await loadUrl(params.initialUrl!, null);
}
}
void _setWebViewConfiguration(
WKWebViewConfiguration configuration, {
required bool? allowsInlineMediaPlayback,
required AutoMediaPlaybackPolicy autoMediaPlaybackPolicy,
}) {
if (allowsInlineMediaPlayback != null) {
configuration.setAllowsInlineMediaPlayback(allowsInlineMediaPlayback);
}
late final bool requiresUserAction;
switch (autoMediaPlaybackPolicy) {
case AutoMediaPlaybackPolicy.require_user_action_for_all_media_types:
requiresUserAction = true;
break;
case AutoMediaPlaybackPolicy.always_allow:
requiresUserAction = false;
break;
}
configuration
.setMediaTypesRequiringUserActionForPlayback(<WKAudiovisualMediaType>{
if (requiresUserAction) WKAudiovisualMediaType.all,
if (!requiresUserAction) WKAudiovisualMediaType.none,
});
}
@override
Future<void> loadHtmlString(String html, {String? baseUrl}) {
return webView.loadHtmlString(html, baseUrl: baseUrl);
}
@override
Future<void> loadFile(String absoluteFilePath) async {
await webView.loadFileUrl(
absoluteFilePath,
readAccessUrl: path.dirname(absoluteFilePath),
);
}
@override
Future<void> clearCache() {
return webView.configuration.websiteDataStore.removeDataOfTypes(
<WKWebsiteDataType>{
WKWebsiteDataType.memoryCache,
WKWebsiteDataType.diskCache,
WKWebsiteDataType.offlineWebApplicationCache,
WKWebsiteDataType.localStorage,
},
DateTime.fromMillisecondsSinceEpoch(0),
);
}
@override
Future<void> loadFlutterAsset(String key) async {
assert(key.isNotEmpty);
return webView.loadFlutterAsset(key);
}
@override
Future<void> loadUrl(String url, Map<String, String>? headers) async {
final NSUrlRequest request = NSUrlRequest(
url: url,
allHttpHeaderFields: headers ?? <String, String>{},
);
return webView.loadRequest(request);
}
@override
Future<void> loadRequest(WebViewRequest request) async {
if (!request.uri.hasScheme) {
throw ArgumentError('WebViewRequest#uri is required to have a scheme.');
}
final NSUrlRequest urlRequest = NSUrlRequest(
url: request.uri.toString(),
allHttpHeaderFields: request.headers,
httpMethod: describeEnum(request.method),
httpBody: request.body,
);
return webView.loadRequest(urlRequest);
}
@override
Future<bool> canGoBack() => webView.canGoBack();
@override
Future<bool> canGoForward() => webView.canGoForward();
@override
Future<void> goBack() => webView.goBack();
@override
Future<void> goForward() => webView.goForward();
@override
Future<void> reload() => webView.reload();
@override
Future<String> evaluateJavascript(String javascript) async {
final Object? result = await webView.evaluateJavaScript(javascript);
return _asObjectiveCString(result);
}
@override
Future<void> runJavascript(String javascript) async {
try {
await webView.evaluateJavaScript(javascript);
} on PlatformException catch (exception) {
// WebKit will throw an error when the type of the evaluated value is
// unsupported. This also goes for `null` and `undefined` on iOS 14+. For
// example, when running a void function. For ease of use, this specific
// error is ignored when no return value is expected.
final Object? details = exception.details;
if (details is! NSError ||
details.code != WKErrorCode.javaScriptResultTypeIsUnsupported) {
rethrow;
}
}
}
@override
Future<String> runJavascriptReturningResult(String javascript) async {
final Object? result = await webView.evaluateJavaScript(javascript);
if (result == null) {
throw ArgumentError(
'Result of JavaScript execution returned a `null` value. '
'Use `runJavascript` when expecting a null return value.',
);
}
return _asObjectiveCString(result);
}
@override
Future<String?> getTitle() => webView.getTitle();
@override
Future<String?> currentUrl() => webView.getUrl();
@override
Future<void> scrollTo(int x, int y) async {
webView.scrollView.setContentOffset(Point<double>(
x.toDouble(),
y.toDouble(),
));
}
@override
Future<void> scrollBy(int x, int y) async {
await webView.scrollView.scrollBy(Point<double>(
x.toDouble(),
y.toDouble(),
));
}
@override
Future<int> getScrollX() async {
final Point<double> offset = await webView.scrollView.getContentOffset();
return offset.x.toInt();
}
@override
Future<int> getScrollY() async {
final Point<double> offset = await webView.scrollView.getContentOffset();
return offset.y.toInt();
}
@override
Future<void> updateSettings(WebSettings setting) async {
if (setting.hasNavigationDelegate != null) {
_hasNavigationDelegate = setting.hasNavigationDelegate!;
}
await Future.wait(<Future<void>>[
_setUserAgent(setting.userAgent),
if (setting.hasProgressTracking != null)
_setHasProgressTracking(setting.hasProgressTracking!),
if (setting.javascriptMode != null)
_setJavaScriptMode(setting.javascriptMode!),
if (setting.zoomEnabled != null) _setZoomEnabled(setting.zoomEnabled!),
if (setting.gestureNavigationEnabled != null)
webView.setAllowsBackForwardNavigationGestures(
setting.gestureNavigationEnabled!,
),
]);
}
@override
Future<void> addJavascriptChannels(Set<String> javascriptChannelNames) async {
await Future.wait<void>(
javascriptChannelNames.where(
(String channelName) {
return !_scriptMessageHandlers.containsKey(channelName);
},
).map<Future<void>>(
(String channelName) {
final WKScriptMessageHandler handler =
webViewProxy.createScriptMessageHandler(
didReceiveScriptMessage: withWeakRefenceTo(
javascriptChannelRegistry,
(WeakReference<JavascriptChannelRegistry> weakReference) {
return (
WKUserContentController userContentController,
WKScriptMessage message,
) {
weakReference.target?.onJavascriptChannelMessage(
message.name,
message.body!.toString(),
);
};
},
),
);
_scriptMessageHandlers[channelName] = handler;
final String wrapperSource =
'window.$channelName = webkit.messageHandlers.$channelName;';
final WKUserScript wrapperScript = WKUserScript(
wrapperSource,
WKUserScriptInjectionTime.atDocumentStart,
isMainFrameOnly: false,
);
webView.configuration.userContentController
.addUserScript(wrapperScript);
return webView.configuration.userContentController
.addScriptMessageHandler(
handler,
channelName,
);
},
),
);
}
@override
Future<void> removeJavascriptChannels(
Set<String> javascriptChannelNames,
) async {
if (javascriptChannelNames.isEmpty) {
return;
}
await _resetUserScripts(removedJavaScriptChannels: javascriptChannelNames);
}
Future<void> _setHasProgressTracking(bool hasProgressTracking) async {
if (hasProgressTracking) {
_progressObserverSet = true;
await webView.addObserver(
webView,
keyPath: 'estimatedProgress',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.newValue,
},
);
} else if (_progressObserverSet) {
// Calls to removeObserver before addObserver causes a crash.
_progressObserverSet = false;
await webView.removeObserver(webView, keyPath: 'estimatedProgress');
}
}
Future<void> _setJavaScriptMode(JavascriptMode mode) {
switch (mode) {
case JavascriptMode.disabled:
return webView.configuration.preferences.setJavaScriptEnabled(false);
case JavascriptMode.unrestricted:
return webView.configuration.preferences.setJavaScriptEnabled(true);
}
}
Future<void> _setUserAgent(WebSetting<String?> userAgent) async {
if (userAgent.isPresent) {
await webView.setCustomUserAgent(userAgent.value);
}
}
Future<void> _setZoomEnabled(bool zoomEnabled) async {
if (_zoomEnabled == zoomEnabled) {
return;
}
_zoomEnabled = zoomEnabled;
if (!zoomEnabled) {
return _disableZoom();
}
return _resetUserScripts();
}
Future<void> _disableZoom() {
const WKUserScript userScript = WKUserScript(
"var meta = document.createElement('meta');\n"
"meta.name = 'viewport';\n"
"meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, "
"user-scalable=no';\n"
"var head = document.getElementsByTagName('head')[0];head.appendChild(meta);",
WKUserScriptInjectionTime.atDocumentEnd,
isMainFrameOnly: true,
);
return webView.configuration.userContentController
.addUserScript(userScript);
}
// WkWebView does not support removing a single user script, so all user
// scripts and all message handlers are removed instead. And the JavaScript
// channels that shouldn't be removed are re-registered. Note that this
// workaround could interfere with exposing support for custom scripts from
// applications.
Future<void> _resetUserScripts({
Set<String> removedJavaScriptChannels = const <String>{},
}) async {
webView.configuration.userContentController.removeAllUserScripts();
// TODO(bparrishMines): This can be replaced with
// `removeAllScriptMessageHandlers` once Dart supports runtime version
// checking. (e.g. The equivalent to @availability in Objective-C.)
_scriptMessageHandlers.keys.forEach(
webView.configuration.userContentController.removeScriptMessageHandler,
);
removedJavaScriptChannels.forEach(_scriptMessageHandlers.remove);
final Set<String> remainingNames = _scriptMessageHandlers.keys.toSet();
_scriptMessageHandlers.clear();
await Future.wait(<Future<void>>[
addJavascriptChannels(remainingNames),
// Zoom is disabled with a WKUserScript, so this adds it back if it was
// removed above.
if (!_zoomEnabled) _disableZoom(),
]);
}
static WebResourceError _toWebResourceError(NSError error) {
WebResourceErrorType? errorType;
switch (error.code) {
case WKErrorCode.unknown:
errorType = WebResourceErrorType.unknown;
break;
case WKErrorCode.webContentProcessTerminated:
errorType = WebResourceErrorType.webContentProcessTerminated;
break;
case WKErrorCode.webViewInvalidated:
errorType = WebResourceErrorType.webViewInvalidated;
break;
case WKErrorCode.javaScriptExceptionOccurred:
errorType = WebResourceErrorType.javaScriptExceptionOccurred;
break;
case WKErrorCode.javaScriptResultTypeIsUnsupported:
errorType = WebResourceErrorType.javaScriptResultTypeIsUnsupported;
break;
}
return WebResourceError(
errorCode: error.code,
domain: error.domain,
description: error.localizedDescription,
errorType: errorType,
);
}
// The legacy implementation of webview_flutter_wkwebview would convert
// objects to strings before returning them to Dart. This method attempts
// to converts Dart objects to Strings the way it is done in Objective-C
// to avoid breaking users expecting the same String format.
// TODO(bparrishMines): Remove this method with the next breaking change.
// See https://github.com/flutter/flutter/issues/107491
String _asObjectiveCString(Object? value, {bool inContainer = false}) {
if (value == null) {
// An NSNull inside an NSArray or NSDictionary is represented as a String
// differently than a nil.
if (inContainer) {
return '"<null>"';
}
return '(null)';
} else if (value is bool) {
return value ? '1' : '0';
} else if (value is double && value.truncate() == value) {
return value.truncate().toString();
} else if (value is List) {
final List<String> stringValues = <String>[];
for (final Object? listValue in value) {
stringValues.add(_asObjectiveCString(listValue, inContainer: true));
}
return '(${stringValues.join(',')})';
} else if (value is Map) {
final List<String> stringValues = <String>[];
for (final MapEntry<Object?, Object?> entry in value.entries) {
stringValues.add(
'${_asObjectiveCString(entry.key, inContainer: true)} '
'= '
'${_asObjectiveCString(entry.value, inContainer: true)}',
);
}
return '{${stringValues.join(';')}}';
}
return value.toString();
}
}
/// Handles constructing objects and calling static methods.
///
/// This should only be used for testing purposes.
@visibleForTesting
class WebViewWidgetProxy {
/// Constructs a [WebViewWidgetProxy].
const WebViewWidgetProxy();
/// Constructs a [WKWebView].
WKWebView createWebView(
WKWebViewConfiguration configuration, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)?
observeValue,
}) {
return WKWebView(configuration, observeValue: observeValue);
}
/// Constructs a [WKScriptMessageHandler].
WKScriptMessageHandler createScriptMessageHandler({
required void Function(
WKUserContentController userContentController,
WKScriptMessage message,
)
didReceiveScriptMessage,
}) {
return WKScriptMessageHandler(
didReceiveScriptMessage: didReceiveScriptMessage,
);
}
/// Constructs a [WKUIDelegate].
WKUIDelegate createUIDelgate({
void Function(
WKWebView webView,
WKWebViewConfiguration configuration,
WKNavigationAction navigationAction,
)?
onCreateWebView,
}) {
return WKUIDelegate(onCreateWebView: onCreateWebView);
}
/// Constructs a [WKNavigationDelegate].
WKNavigationDelegate createNavigationDelegate({
void Function(WKWebView webView, String? url)? didFinishNavigation,
void Function(WKWebView webView, String? url)?
didStartProvisionalNavigation,
Future<WKNavigationActionPolicy> Function(
WKWebView webView,
WKNavigationAction navigationAction,
)?
decidePolicyForNavigationAction,
void Function(WKWebView webView, NSError error)? didFailNavigation,
void Function(WKWebView webView, NSError error)?
didFailProvisionalNavigation,
void Function(WKWebView webView)? webViewWebContentProcessDidTerminate,
}) {
return WKNavigationDelegate(
didFinishNavigation: didFinishNavigation,
didStartProvisionalNavigation: didStartProvisionalNavigation,
decidePolicyForNavigationAction: decidePolicyForNavigationAction,
didFailNavigation: didFailNavigation,
didFailProvisionalNavigation: didFailProvisionalNavigation,
webViewWebContentProcessDidTerminate:
webViewWebContentProcessDidTerminate,
);
}
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/legacy/web_kit_webview_widget.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/legacy/web_kit_webview_widget.dart",
"repo_id": "plugins",
"token_count": 8583
} | 1,160 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.example.androidView
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import dev.flutter.example.androidView.databinding.AndroidCardBinding
import io.flutter.embedding.android.FlutterView
import io.flutter.plugin.common.MethodChannel
import java.util.*
import kotlin.random.Random
/**
* A demo-specific implementation of a [RecyclerView.Adapter] to setup the demo environment used
* to display view-level Flutter cells inside a list.
*
* The only instructional parts of this class are to show when to call
* [FlutterViewEngine.attachFlutterView] and [FlutterViewEngine.detachActivity] on a
* [FlutterViewEngine] equivalent class that you may want to create in your own application.
*/
class ListAdapter(context: Context, private val flutterViewEngine: FlutterViewEngine) : RecyclerView.Adapter<ListAdapter.Cell>() {
// Save the previous cells determined to be Flutter cells to avoid a confusing visual effect
// that the Flutter cells change position when scrolling back.
var previousFlutterCells = TreeSet<Int>();
private val matchParentLayout = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
private val random = Random.Default
private val flutterView = FlutterView(context)
private val flutterChannel = MethodChannel(flutterViewEngine.engine.dartExecutor, "dev.flutter.example/cell")
private var flutterCell: Cell? = null
/**
* A [RecyclerView.ViewHolder] based on the `android_card` layout XML.
*/
inner class Cell(val binding: AndroidCardBinding) : RecyclerView.ViewHolder(binding.root) {
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): Cell {
val binding = AndroidCardBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
// Let the default view holder have an "Android card" inflated from the layout XML. When
// needed, hide the Android card and show a Flutter one instead.
return Cell(binding)
}
override fun onBindViewHolder(cell: Cell, position: Int) {
// While scrolling forward, if no Flutter is presently showing, let the next one have a 1/3
// chance of being Flutter.
//
// While scrolling backward, let it be deterministic, and only show cells that were
// previously Flutter cells as Flutter cells.
if (previousFlutterCells.contains(position)
|| ((previousFlutterCells.isEmpty() || position > previousFlutterCells.last())
&& flutterCell == null
&& random.nextInt(3) == 0)) {
// If we're restoring a cell at a previous location, the current cell may not have
// recycled yet since that JVM timing is indeterministic. Yank it from the current one.
//
// This shouldn't produce any visual glitches since in the forward direction,
// Flutter cells were only introduced once the previous Flutter cell recycled.
if (flutterCell != null) {
Log.w("FeedAdapter", "While restoring a previous Flutter cell, a current "
+ "yet to be recycled Flutter cell was detached.")
flutterCell!!.binding.root.removeView(flutterView)
flutterViewEngine.detachFlutterView()
flutterCell = null
}
// Add the Flutter card and hide the Android card for the cells chosen to be Flutter
// cells.
cell.binding.root.addView(flutterView, matchParentLayout)
cell.binding.androidCard.visibility = View.GONE
// Keep track of the cell so we know which one to restore back to the "Android cell"
// state when the view gets recycled.
flutterCell = cell
// Keep track that this position has once been a Flutter cell. Let it be a Flutter cell
// again when scrolling back to this position.
previousFlutterCells.add(position)
// This is what makes the Flutter cell start rendering.
flutterViewEngine.attachFlutterView(flutterView)
// Tell Flutter which index it's at so Flutter could show the cell number too in its
// own widget tree.
flutterChannel.invokeMethod("setCellNumber", position)
} else {
// If it's not selected as a Flutter cell, just show the Android card.
cell.binding.androidCard.visibility = View.VISIBLE
cell.binding.cellNumber.text = position.toString();
}
}
override fun getItemCount() = 100
override fun onViewRecycled(cell: Cell) {
if (cell == flutterCell) {
cell.binding.root.removeView(flutterView)
flutterViewEngine.detachFlutterView()
flutterCell = null
}
super.onViewRecycled(cell)
}
}
| samples/add_to_app/android_view/android_view/app/src/main/java/dev/flutter/example/androidView/ListAdapter.kt/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/java/dev/flutter/example/androidView/ListAdapter.kt",
"repo_id": "samples",
"token_count": 1853
} | 1,161 |
// Autogenerated from Pigeon (v1.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
package dev.flutter.example.books;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StandardMessageCodec;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Generated class from Pigeon. */
@SuppressWarnings(
{"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"})
public class Api {
/** Generated class from Pigeon that represents data sent in messages. */
public static class Book {
private String title;
public String getTitle() { return title; }
public void setTitle(String setterArg) { this.title = setterArg; }
private String subtitle;
public String getSubtitle() { return subtitle; }
public void setSubtitle(String setterArg) { this.subtitle = setterArg; }
private String author;
public String getAuthor() { return author; }
public void setAuthor(String setterArg) { this.author = setterArg; }
private String summary;
public String getSummary() { return summary; }
public void setSummary(String setterArg) { this.summary = setterArg; }
private String publishDate;
public String getPublishDate() { return publishDate; }
public void setPublishDate(String setterArg) {
this.publishDate = setterArg;
}
private Long pageCount;
public Long getPageCount() { return pageCount; }
public void setPageCount(Long setterArg) { this.pageCount = setterArg; }
private Thumbnail thumbnail;
public Thumbnail getThumbnail() { return thumbnail; }
public void setThumbnail(Thumbnail setterArg) {
this.thumbnail = setterArg;
}
Map<String, Object> toMap() {
Map<String, Object> toMapResult = new HashMap<>();
toMapResult.put("title", title);
toMapResult.put("subtitle", subtitle);
toMapResult.put("author", author);
toMapResult.put("summary", summary);
toMapResult.put("publishDate", publishDate);
toMapResult.put("pageCount", pageCount);
toMapResult.put("thumbnail",
(thumbnail == null) ? null : thumbnail.toMap());
return toMapResult;
}
static Book fromMap(Map<String, Object> map) {
Book fromMapResult = new Book();
Object title = map.get("title");
fromMapResult.title = (String)title;
Object subtitle = map.get("subtitle");
fromMapResult.subtitle = (String)subtitle;
Object author = map.get("author");
fromMapResult.author = (String)author;
Object summary = map.get("summary");
fromMapResult.summary = (String)summary;
Object publishDate = map.get("publishDate");
fromMapResult.publishDate = (String)publishDate;
Object pageCount = map.get("pageCount");
fromMapResult.pageCount =
(pageCount == null)
? null
: ((pageCount instanceof Integer) ? (Integer)pageCount
: (Long)pageCount);
Object thumbnail = map.get("thumbnail");
fromMapResult.thumbnail = Thumbnail.fromMap((Map)thumbnail);
return fromMapResult;
}
}
/** Generated class from Pigeon that represents data sent in messages. */
public static class Thumbnail {
private String url;
public String getUrl() { return url; }
public void setUrl(String setterArg) { this.url = setterArg; }
Map<String, Object> toMap() {
Map<String, Object> toMapResult = new HashMap<>();
toMapResult.put("url", url);
return toMapResult;
}
static Thumbnail fromMap(Map<String, Object> map) {
Thumbnail fromMapResult = new Thumbnail();
Object url = map.get("url");
fromMapResult.url = (String)url;
return fromMapResult;
}
}
private static class FlutterBookApiCodec extends StandardMessageCodec {
public static final FlutterBookApiCodec INSTANCE =
new FlutterBookApiCodec();
private FlutterBookApiCodec() {}
@Override
protected Object readValueOfType(byte type, ByteBuffer buffer) {
switch (type) {
case (byte)128:
return Book.fromMap((Map<String, Object>)readValue(buffer));
default:
return super.readValueOfType(type, buffer);
}
}
@Override
protected void writeValue(ByteArrayOutputStream stream, Object value) {
if (value instanceof Book) {
stream.write(128);
writeValue(stream, ((Book)value).toMap());
} else {
super.writeValue(stream, value);
}
}
}
/**
* Generated class from Pigeon that represents Flutter messages that can be
* called from Java.
*/
public static class FlutterBookApi {
private final BinaryMessenger binaryMessenger;
public FlutterBookApi(BinaryMessenger argBinaryMessenger) {
this.binaryMessenger = argBinaryMessenger;
}
public interface Reply<T> {
void reply(T reply);
}
static MessageCodec<Object> getCodec() {
return FlutterBookApiCodec.INSTANCE;
}
public void displayBookDetails(Book bookArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel = new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.FlutterBookApi.displayBookDetails", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(bookArg)),
channelReply -> { callback.reply(null); });
}
}
private static class HostBookApiCodec extends StandardMessageCodec {
public static final HostBookApiCodec INSTANCE = new HostBookApiCodec();
private HostBookApiCodec() {}
@Override
protected Object readValueOfType(byte type, ByteBuffer buffer) {
switch (type) {
case (byte)128:
return Book.fromMap((Map<String, Object>)readValue(buffer));
default:
return super.readValueOfType(type, buffer);
}
}
@Override
protected void writeValue(ByteArrayOutputStream stream, Object value) {
if (value instanceof Book) {
stream.write(128);
writeValue(stream, ((Book)value).toMap());
} else {
super.writeValue(stream, value);
}
}
}
/**
* Generated interface from Pigeon that represents a handler of messages from
* Flutter.
*/
public interface HostBookApi {
void cancel();
void finishEditingBook(Book book);
/** The codec used by HostBookApi. */
static MessageCodec<Object> getCodec() { return HostBookApiCodec.INSTANCE; }
/**
* Sets up an instance of `HostBookApi` to handle messages through the
* `binaryMessenger`.
*/
static void setup(BinaryMessenger binaryMessenger, HostBookApi api) {
{
BasicMessageChannel<Object> channel = new BasicMessageChannel<>(
binaryMessenger, "dev.flutter.pigeon.HostBookApi.cancel",
getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
api.cancel();
wrapped.put("result", null);
} catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel = new BasicMessageChannel<>(
binaryMessenger, "dev.flutter.pigeon.HostBookApi.finishEditingBook",
getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
Book bookArg = (Book)args.get(0);
if (bookArg == null) {
throw new NullPointerException("bookArg unexpectedly null.");
}
api.finishEditingBook(bookArg);
wrapped.put("result", null);
} catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
private static Map<String, Object> wrapError(Throwable exception) {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("message", exception.toString());
errorMap.put("code", exception.getClass().getSimpleName());
errorMap.put("details", null);
return errorMap;
}
}
| samples/add_to_app/books/android_books/app/src/main/java/dev/flutter/example/books/Api.java/0 | {
"file_path": "samples/add_to_app/books/android_books/app/src/main/java/dev/flutter/example/books/Api.java",
"repo_id": "samples",
"token_count": 3428
} | 1,162 |
include: package:analysis_defaults/flutter.yaml
| samples/add_to_app/books/flutter_module_books/analysis_options.yaml/0 | {
"file_path": "samples/add_to_app/books/flutter_module_books/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,163 |
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 33
defaultConfig {
applicationId "dev.flutter.example.androidfullscreen"
minSdkVersion 19
targetSdkVersion 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
signingConfig debug.signingConfig
}
}
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
namespace 'dev.flutter.example.androidfullscreen'
}
dependencies {
implementation 'androidx.multidex:multidex:2.0.1'
implementation project(':flutter')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'androidx.core:core-ktx:1.10.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation project(':espresso')
androidTestImplementation "com.google.truth:truth:1.1.3"
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
api 'androidx.test:core:1.5.0'
}
| samples/add_to_app/fullscreen/android_fullscreen/app/build.gradle/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/build.gradle",
"repo_id": "samples",
"token_count": 554
} | 1,164 |
#Mon Dec 11 09:57:20 AEDT 2023
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
| samples/add_to_app/multiple_flutters/multiple_flutters_android/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "samples",
"token_count": 88
} | 1,165 |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Foundation
/// A protocol that receives updates when the datamodel is changed.
protocol DataModelObserver: AnyObject {
func onCountUpdate(newCount: Int64)
}
/// A wrapper object around a weak reference to an object that implements DataModelObserver.
///
/// This is required since you can't directly hold weak references to protocols in data structures.
private struct DataModelObserverWrapper {
weak var wrapped: DataModelObserver?
init(_ wrapped: DataModelObserver) {
self.wrapped = wrapped
}
}
/// A singleton data model that is observable.
class DataModel {
private var _count: Int64 = 0
var count: Int64 {
get {
return self._count
}
set {
self._count = newValue
for observer in observers {
if let wrapped = observer.wrapped {
wrapped.onCountUpdate(newCount: self._count)
}
}
}
}
private var observers: [DataModelObserverWrapper] = []
static let shared = DataModel()
func addObserver(observer: DataModelObserver) {
observers.append(DataModelObserverWrapper(observer))
}
func removeObserver(observer: DataModelObserver) {
observers.removeAll { (element: DataModelObserverWrapper) -> Bool in
if let wrapped = element.wrapped {
return wrapped === observer
} else {
// Handle observers who dealloc'd without removing themselves.
return true
}
}
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/DataModel.swift/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/DataModel.swift",
"repo_id": "samples",
"token_count": 510
} | 1,166 |
include ':app'
rootProject.name='AndroidUsingPlugin'
setBinding(new Binding([gradle: this]))
evaluate(new File(
settingsDir.parentFile,
'flutter_module_using_plugin/.android/include_flutter.groovy'
))
| samples/add_to_app/plugin/android_using_plugin/settings.gradle/0 | {
"file_path": "samples/add_to_app/plugin/android_using_plugin/settings.gradle",
"repo_id": "samples",
"token_count": 80
} | 1,167 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.splash_screen_sample
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.os.Bundle
import android.transition.AutoTransition
import android.transition.Transition
import android.transition.TransitionManager
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.View
import android.widget.FrameLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.animation.doOnEnd
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.splashscreen.SplashScreenViewProvider
import androidx.core.view.postDelayed
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
var flutterUIReady : Boolean = false
var initialAnimationFinished : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This activity will be handling the splash screen transition.
val splashScreen = installSplashScreen()
// The splash screen goes edge to edge, so for a smooth transition to our app, also
// want to draw edge to edge.
WindowCompat.setDecorFitsSystemWindows(window, false)
val insetsController = WindowCompat.getInsetsController(window, window.decorView)
insetsController?.isAppearanceLightNavigationBars = true
insetsController?.isAppearanceLightStatusBars = true
// The content view needs to be set before calling setOnExitAnimationListener
// to ensure that the SplashScreenView is attached to the right view root.
val rootLayout = findViewById(android.R.id.content) as FrameLayout
View.inflate(this, R.layout.main_activity_2, rootLayout)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
view.setPadding(insets.left, insets.top, insets.right, insets.bottom)
windowInsets.inset(insets)
}
// Setting an OnExitAnimationListener on the splash screen indicates
// to the system that the application will handle the exit animation.
// The listener will be called once the app is ready.
splashScreen.setOnExitAnimationListener { splashScreenViewProvider ->
onSplashScreenExit(splashScreenViewProvider)
}
}
override fun onFlutterUiDisplayed(){
flutterUIReady = true
if (initialAnimationFinished) {
hideSplashScreenAnimation()
}
}
override fun onFlutterUiNoLongerDisplayed(){
flutterUIReady = false
}
/**
* Hides the splash screen only when the entire animation has finished and the Flutter UI is ready to display.
*/
private fun hideSplashScreenAnimation(){
val splashView = findViewById(R.id.container) as ConstraintLayout
splashView
.animate()
.alpha(0.0f)
.setDuration(SPLASHSCREEN_FINAL_ANIMATION_ALPHA_ANIMATION_DURATION)
}
/**
* Handles the transition from the splash screen to the application.
*/
private fun onSplashScreenExit(splashScreenViewProvider: SplashScreenViewProvider) {
val accelerateInterpolator = FastOutLinearInInterpolator()
val splashScreenView = splashScreenViewProvider.view
val iconView = splashScreenViewProvider.iconView
// Change the alpha of the main view.
val alpha = ValueAnimator.ofInt(255, 0)
alpha.duration = SPLASHSCREEN_ALPHA_ANIMATION_DURATION
alpha.interpolator = accelerateInterpolator
// And translate the icon down.
val translationY = ObjectAnimator.ofFloat(
iconView,
View.TRANSLATION_Y,
iconView.translationY,
splashScreenView.height.toFloat()
)
translationY.duration = SPLASHSCREEN_TY_ANIMATION_DURATION
translationY.interpolator = accelerateInterpolator
// And play all of the animation together.
val animatorSet = AnimatorSet()
animatorSet.playTogether(alpha)
// Apply layout constraints of starting frame of animation to
// FrameLayout's container for the TransitionManager to know
// where to start the transition.
val root = findViewById<ConstraintLayout>(R.id.container)
val set1 = ConstraintSet().apply {
clone(this@MainActivity, R.layout.main_activity)
}
set1.applyTo(root)
// Retrieve layout constraints of final frame of animation
// for TransitionManager to know where to end the transition.
val set2 = ConstraintSet().apply {
clone(this@MainActivity, R.layout.main_activity_2)
}
var transitionStarted = false
val autoTransition = AutoTransition().apply {
interpolator = AccelerateDecelerateInterpolator()
}
autoTransition.addListener(object: Transition.TransitionListener {
override fun onTransitionEnd(transition: Transition) {
initialAnimationFinished = true
if (flutterUIReady) {
hideSplashScreenAnimation()
}
}
override fun onTransitionCancel(transition: Transition){}
override fun onTransitionPause(transition: Transition) {}
override fun onTransitionResume(transition: Transition) {}
override fun onTransitionStart(transition: Transition) {}
})
val alphaUpdateListener: (ValueAnimator) -> Unit = { valueAnimator ->
if (!transitionStarted && valueAnimator.animatedFraction > 0.5) {
transitionStarted = true
TransitionManager.beginDelayedTransition(root, autoTransition)
iconView.visibility = View.GONE
// Apply constraints of final frame of animation to
// FrameLayout's container once the transition is in progress.
set2.applyTo(root)
}
splashScreenView.background.alpha = valueAnimator.animatedValue as Int
}
alpha.addUpdateListener(alphaUpdateListener)
// Once the application is finished, remove the splash screen from our view
// hierarchy.
animatorSet.doOnEnd {
splashScreenViewProvider.remove()
}
waitForAnimatedIconToFinish(splashScreenViewProvider, splashScreenView) {
animatorSet.start()
}
}
/**
* Wait until the AVD animation is finished before starting the splash screen dismiss animation.
*/
private fun SplashScreenViewProvider.remainingAnimationDuration() = iconAnimationStartMillis +
iconAnimationDurationMillis - System.currentTimeMillis()
private fun waitForAnimatedIconToFinish(
splashScreenViewProvider: SplashScreenViewProvider,
view: View,
onAnimationFinished: () -> Unit
) {
// If wanting to wait for our Animated Vector Drawable to finish animating, can compute
// the remaining time to delay the start of the exit animation.
val delayMillis: Long =
if (WAIT_FOR_AVD_TO_FINISH) splashScreenViewProvider.remainingAnimationDuration() else 0
view.postDelayed(delayMillis, onAnimationFinished)
}
private companion object {
const val SPLASHSCREEN_ALPHA_ANIMATION_DURATION = 500 as Long
const val SPLASHSCREEN_TY_ANIMATION_DURATION = 500 as Long
const val SPLASHSCREEN_FINAL_ANIMATION_ALPHA_ANIMATION_DURATION = 250 as Long
const val WAIT_FOR_AVD_TO_FINISH = false
}
}
| samples/android_splash_screen/android/app/src/main/kotlin/com/example/splash_screen_sample/MainActivity.kt/0 | {
"file_path": "samples/android_splash_screen/android/app/src/main/kotlin/com/example/splash_screen_sample/MainActivity.kt",
"repo_id": "samples",
"token_count": 2544
} | 1,168 |
buildscript {
ext.kotlin_version = '1.5.31'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| samples/android_splash_screen/android/build.gradle/0 | {
"file_path": "samples/android_splash_screen/android/build.gradle",
"repo_id": "samples",
"token_count": 252
} | 1,169 |
package dev.flutter.animations
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/animations/android/app/src/main/kotlin/dev/flutter/animations/MainActivity.kt/0 | {
"file_path": "samples/animations/android/app/src/main/kotlin/dev/flutter/animations/MainActivity.kt",
"repo_id": "samples",
"token_count": 38
} | 1,170 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class AnimationControllerDemo extends StatefulWidget {
const AnimationControllerDemo({super.key});
static const String routeName = 'basics/animation_controller';
@override
State<AnimationControllerDemo> createState() =>
_AnimationControllerDemoState();
}
class _AnimationControllerDemoState extends State<AnimationControllerDemo>
with SingleTickerProviderStateMixin {
// Using the SingleTickerProviderStateMixin can ensure that our
// AnimationController only animates while the Widget is visible on the
// screen. This is a useful optimization that saves resources when the
// Widget is not visible.
static const Duration _duration = Duration(seconds: 1);
late final AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(vsync: this, duration: _duration)
// The Widget's build needs to be called every time the animation's
// value changes. So add a listener here that will call setState()
// and trigger the build() method to be called by the framework.
// If your Widget's build is relatively simple, this is a good option.
// However, if your build method returns a tree of child Widgets and
// most of them are not animated you should consider using
// AnimatedBuilder instead.
..addListener(() {
setState(() {});
});
}
@override
void dispose() {
// AnimationController is a stateful resource that needs to be disposed when
// this State gets disposed.
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// When building the widget you can read the AnimationController's value property
// when building child widgets. You can also check the status to see if the animation
// has completed.
return Scaffold(
appBar: AppBar(
title: const Text('Animation Controller'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 200),
child: Text(
controller.value.toStringAsFixed(2),
style: Theme.of(context).textTheme.displaySmall,
textScaler: TextScaler.linear(1 + controller.value),
),
),
ElevatedButton(
child: const Text('animate'),
onPressed: () {
switch (controller.status) {
case AnimationStatus.completed:
controller.reverse();
default:
controller.forward();
}
},
)
],
),
),
);
}
}
| samples/animations/lib/src/basics/animation_controller.dart/0 | {
"file_path": "samples/animations/lib/src/basics/animation_controller.dart",
"repo_id": "samples",
"token_count": 1105
} | 1,171 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class HeroAnimationDemo extends StatelessWidget {
const HeroAnimationDemo({super.key});
static const String routeName = 'misc/hero_animation';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Hero Animation'),
),
body: GestureDetector(
child: Hero(
tag: 'hero-page-child',
child: _createHeroContainer(
size: 50.0,
color: Colors.grey.shade300,
),
),
onTap: () => Navigator.of(context).push<void>(
MaterialPageRoute(builder: (context) => const HeroPage())),
),
);
}
}
class HeroPage extends StatelessWidget {
const HeroPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightBlue,
appBar: AppBar(),
body: Center(
child: Hero(
tag: 'hero-page-child',
child: _createHeroContainer(
size: 100.0,
color: Colors.white,
),
),
),
);
}
}
StatelessWidget _createHeroContainer({
required double size,
required Color color,
}) {
return Container(
height: size,
width: size,
padding: const EdgeInsets.all(10.0),
margin: size < 100.0 ? const EdgeInsets.all(10.0) : const EdgeInsets.all(0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color,
),
child: const FlutterLogo(),
);
}
| samples/animations/lib/src/misc/hero_animation.dart/0 | {
"file_path": "samples/animations/lib/src/misc/hero_animation.dart",
"repo_id": "samples",
"token_count": 697
} | 1,172 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:animations/src/misc/expand_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Widget createExpandCardScreen() => const MaterialApp(
home: ExpandCardDemo(),
);
void main() {
group('ExpandCard Tests', () {
testWidgets('ExpandCard changes size on tap', (tester) async {
await tester.pumpWidget(createExpandCardScreen());
// Get the initial size of ExpandCard.
var initialSize = tester.getSize(find.byType(ExpandCard));
// Tap on the ExpandCard.
await tester.tap(find.byType(ExpandCard));
await tester.pumpAndSettle();
// The size of ExpandCard must change once tapped.
// The initialSize should be less than current ExpandCard size.
expect(
initialSize,
lessThan(tester.getSize(find.byType(ExpandCard))),
);
});
testWidgets('ExpandCard changes image on tap', (tester) async {
await tester.pumpWidget(createExpandCardScreen());
var initialImage = tester.widget(find.byType(Image).last);
// Tap on ExpandCard.
await tester.tap(find.byType(ExpandCard));
await tester.pumpAndSettle();
// Once tapped, the image should change.
expect(
initialImage,
isNot(equals(tester.widget(find.byType(Image).last))),
);
});
});
}
| samples/animations/test/misc/expand_card_test.dart/0 | {
"file_path": "samples/animations/test/misc/expand_card_test.dart",
"repo_id": "samples",
"token_count": 566
} | 1,173 |
name: background_isolate_channels
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
intl: ^0.19.0
path: ^1.8.2
path_provider: ^2.0.11
shared_preferences: ^2.0.15
uuid: ^4.0.0
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| samples/background_isolate_channels/pubspec.yaml/0 | {
"file_path": "samples/background_isolate_channels/pubspec.yaml",
"repo_id": "samples",
"token_count": 216
} | 1,174 |
#import "GeneratedPluginRegistrant.h"
| samples/code_sharing/client/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/code_sharing/client/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,175 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/code_sharing/client/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/code_sharing/client/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,176 |
/// Common data models required by our client and server.
library shared;
export 'src/models.dart';
| samples/code_sharing/shared/lib/shared.dart/0 | {
"file_path": "samples/code_sharing/shared/lib/shared.dart",
"repo_id": "samples",
"token_count": 27
} | 1,177 |
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'context_menu_region.dart';
import 'platform_selector.dart';
class ImagePage extends StatelessWidget {
const ImagePage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'image';
static const String title = 'ContextMenu on an Image';
static const String subtitle =
'A ContextMenu the displays on an Image widget';
static const String url = '$kCodeUrl/image_page.dart';
final PlatformCallback onChangedPlatform;
DialogRoute _showDialog(BuildContext context) {
return DialogRoute<void>(
context: context,
builder: (context) =>
const AlertDialog(title: Text('Image saved! (not really though)')),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(ImagePage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ContextMenuRegion(
contextMenuBuilder: (context, offset) {
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: TextSelectionToolbarAnchors(
primaryAnchor: offset,
),
buttonItems: <ContextMenuButtonItem>[
ContextMenuButtonItem(
onPressed: () {
ContextMenuController.removeAny();
Navigator.of(context).push(_showDialog(context));
},
label: 'Save',
),
],
);
},
child: const SizedBox(
width: 200.0,
height: 200.0,
child: FlutterLogo(),
),
),
Container(height: 20.0),
const Text(
'Right click or long press on the image to see a special menu.',
),
],
),
);
}
}
| samples/context_menus/lib/image_page.dart/0 | {
"file_path": "samples/context_menus/lib/image_page.dart",
"repo_id": "samples",
"token_count": 1162
} | 1,178 |
#import "GeneratedPluginRegistrant.h"
| samples/deeplink_store_example/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/deeplink_store_example/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,179 |
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter_test/flutter_test.dart';
import 'package:deeplink_store_example/main.dart';
import 'package:go_router/go_router.dart';
void main() {
testWidgets('Can open home page', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
await tester.pumpAndSettle();
expect(find.text('Material Store'), findsOneWidget);
});
testWidgets('Can open detail page', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
await tester.pumpAndSettle();
expect(find.text('Vagabond sack'), findsOneWidget);
await tester.tap(find.text('Vagabond sack'));
await tester.pumpAndSettle();
expect(find.text('Material Store'), findsNothing);
expect(find.text('Vagabond sack'), findsOneWidget);
expect(find.text('\$120'), findsOneWidget);
});
testWidgets('Can show category page', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
await tester.pumpAndSettle();
tester.element(find.text('Material Store')).go('/category/home');
await tester.pumpAndSettle();
expect(find.text('Home Decorations'), findsOneWidget);
});
}
| samples/deeplink_store_example/test/widget_test.dart/0 | {
"file_path": "samples/deeplink_store_example/test/widget_test.dart",
"repo_id": "samples",
"token_count": 498
} | 1,180 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:logging/logging.dart';
import 'package:menubar/menubar.dart' as menubar;
import 'package:provider/provider.dart';
import 'package:window_size/window_size.dart';
import 'src/model/photo_search_model.dart';
import 'src/unsplash/unsplash.dart';
import 'src/widgets/photo_search_dialog.dart';
import 'src/widgets/policy_dialog.dart';
import 'src/widgets/unsplash_notice.dart';
import 'src/widgets/unsplash_search_content.dart';
import 'unsplash_access_key.dart';
void main() {
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((rec) {
// ignore: avoid_print
print('${rec.loggerName} ${rec.level.name}: ${rec.time}: ${rec.message}');
});
if (unsplashAccessKey.isEmpty) {
Logger('main').severe('Unsplash Access Key is required. '
'Please add to `lib/unsplash_access_key.dart`.');
exit(1);
}
setupWindow();
runApp(
ChangeNotifierProvider<PhotoSearchModel>(
create: (context) => PhotoSearchModel(
Unsplash(accessKey: unsplashAccessKey),
),
child: const UnsplashSearchApp(),
),
);
}
const double windowWidth = 1024;
const double windowHeight = 800;
void setupWindow() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
WidgetsFlutterBinding.ensureInitialized();
setWindowMinSize(const Size(windowWidth, windowHeight));
}
}
class UnsplashSearchApp extends StatelessWidget {
const UnsplashSearchApp({super.key});
@override
Widget build(BuildContext context) {
return const FluentApp(
title: 'Photo Search',
home: UnsplashHomePage(title: 'Photo Search'),
);
}
}
class UnsplashHomePage extends StatelessWidget {
const UnsplashHomePage({required this.title, super.key});
final String title;
@override
Widget build(BuildContext context) {
final photoSearchModel = Provider.of<PhotoSearchModel>(context);
menubar.setApplicationMenu([
menubar.NativeSubmenu(label: 'Search', children: [
menubar.NativeMenuItem(
label: 'Search…',
onSelected: () {
showDialog<void>(
context: context,
builder: (context) =>
PhotoSearchDialog(callback: photoSearchModel.addSearch),
);
},
),
if (!Platform.isMacOS)
menubar.NativeMenuItem(
label: 'Quit',
onSelected: () {
SystemNavigator.pop();
},
),
]),
menubar.NativeSubmenu(label: 'About', children: [
menubar.NativeMenuItem(
label: 'About',
onSelected: () {
showDialog<void>(
context: context,
builder: (context) => const PolicyDialog(),
);
},
),
])
]);
return UnsplashNotice(
child: Container(
color: Colors.white,
child: photoSearchModel.entries.isNotEmpty
? const UnsplashSearchContent()
: const Center(
child: Text('Search for Photos using the Search menu'),
),
),
);
}
}
| samples/desktop_photo_search/fluent_ui/lib/main.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/main.dart",
"repo_id": "samples",
"token_count": 1422
} | 1,181 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.federated_plugin
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
class FederatedPlugin : FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel
private var context: Context? = null
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "battery")
channel.setMethodCallHandler(this)
context = flutterPluginBinding.applicationContext
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getBatteryLevel") {
val batteryLevel: Int
batteryLevel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val batteryManager = context?.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val intent = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { intentFilter ->
context?.registerReceiver(null, intentFilter)
}
intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
if (batteryLevel < 0) {
result.error("STATUS_UNAVAILABLE", "Not able to determine battery level.", null)
} else {
result.success(batteryLevel)
}
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
context = null
}
}
| samples/experimental/federated_plugin/federated_plugin/android/src/main/kotlin/dev/flutter/federated_plugin/FederatedPlugin.kt/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/android/src/main/kotlin/dev/flutter/federated_plugin/FederatedPlugin.kt",
"repo_id": "samples",
"token_count": 890
} | 1,182 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:federated_plugin/federated_plugin.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
home: const HomePage(),
);
}
}
/// Demonstrates how to use the getBatteryLevel method from federated_plugin to retrieve
/// current battery level of device.
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int? batteryLevel;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Federated Plugin Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
batteryLevel == null
? const SizedBox.shrink()
: Text(
'Battery Level: $batteryLevel',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 16),
FilledButton(
onPressed: () async {
try {
final result = await getBatteryLevel();
setState(() {
batteryLevel = result;
});
} catch (error) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Theme.of(context).primaryColor,
content: Text(
(error as dynamic).message as String,
),
),
);
}
},
child: const Text('Get Battery Level'),
),
],
),
),
);
}
}
| samples/experimental/federated_plugin/federated_plugin/example/lib/main.dart/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/example/lib/main.dart",
"repo_id": "samples",
"token_count": 1063
} | 1,183 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:federated_plugin/federated_plugin.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Federated Plugin Test', () {
const batteryLevel = 34;
testWidgets('getBatteryLevel method test', (tester) async {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('battery'),
(call) async {
if (call.method == 'getBatteryLevel') {
return batteryLevel;
}
return 0;
},
);
final result = await getBatteryLevel();
expect(result, batteryLevel);
});
});
}
| samples/experimental/federated_plugin/federated_plugin/test/federated_plugin_test.dart/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/test/federated_plugin_test.dart",
"repo_id": "samples",
"token_count": 324
} | 1,184 |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:linting_tool/model/profile.dart';
import 'package:linting_tool/model/rule.dart';
import 'package:linting_tool/repository/repository.dart';
/// Manages fetching rules from the web.
class RuleStore extends ChangeNotifier {
final Repository repository;
RuleStore(http.Client httpClient) : repository = Repository(httpClient) {
fetchRules();
}
bool _isLoading = true;
bool get isLoading => _isLoading;
List<Rule> _rules = [];
List<Rule> get rules => _rules;
String? _error;
String? get error => _error;
List<RulesProfile> get defaultProfiles {
if (isLoading || rules.isEmpty) {
return const [];
}
final Map<String, RulesProfile> setsToProfiles = {};
for (final rule in rules) {
for (final setName in rule.sets) {
final profile = setsToProfiles[setName];
if (profile == null) {
setsToProfiles[setName] = RulesProfile(name: setName, rules: [rule]);
} else {
profile.rules.add(rule);
}
}
}
return setsToProfiles.values.toList(growable: false);
}
Future<void> fetchRules() async {
if (!_isLoading) _isLoading = true;
notifyListeners();
try {
_rules = await repository.getRulesList();
} on SocketException catch (e) {
log(e.toString());
_error = 'Check internet connection.';
} on Exception catch (e) {
log(e.toString());
}
_isLoading = false;
notifyListeners();
}
}
| samples/experimental/linting_tool/lib/model/rules_store.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/model/rules_store.dart",
"repo_id": "samples",
"token_count": 643
} | 1,185 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-all.zip
| samples/experimental/pedometer/example/android/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "samples/experimental/pedometer/example/android/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "samples",
"token_count": 71
} | 1,186 |
android_sdk_config:
add_gradle_deps: true
add_gradle_sources: true
android_example: 'example/'
output:
c:
library_name: health_connect
path: src/health_connect/
dart:
path: lib/health_connect.dart
structure: single_file
classes:
- 'androidx.health.connect.client.HealthConnectClient'
- 'androidx.health.connect.client.PermissionController'
- 'androidx.health.connect.client.records.StepsRecord'
- 'androidx.health.connect.client.time'
- 'android.content.Context'
- 'android.content.Intent'
- 'android.app.Activity'
- 'java.time.Instant'
- 'androidx.health.connect.client.request'
- 'androidx.health.connect.client.aggregate.AggregationResult'
- 'androidx.health.connect.client.aggregate.AggregateMetric'
| samples/experimental/pedometer/jnigen.yaml/0 | {
"file_path": "samples/experimental/pedometer/jnigen.yaml",
"repo_id": "samples",
"token_count": 268
} | 1,187 |
#import "pedometerHelper.h"
#import <CoreMotion/CoreMotion.h>
#import <CoreMotion/CMPedometer.h>
#import <Foundation/Foundation.h>
// TODO(https://github.com/dart-lang/native/issues/835): Generate this wrapper
// automatically.
CMPedometerHandler wrapCallback(CMPedometerHandler callback) {
return [^(CMPedometerData *data, NSError *error) {
return callback([data retain], [error retain]);
} copy];
}
| samples/experimental/pedometer/src/pedometerHelper.m/0 | {
"file_path": "samples/experimental/pedometer/src/pedometerHelper.m",
"repo_id": "samples",
"token_count": 140
} | 1,188 |
// Copyright 2023 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../page_content/pages_flow.dart';
void main() {
runApp(const TypePuzzle());
}
class TypePuzzle extends StatelessWidget {
const TypePuzzle({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Type Jam',
theme: ThemeData(
primarySwatch: Colors.grey,
),
home: const Scaffold(
appBar: null,
body: PagesFlow(),
),
);
}
}
| samples/experimental/varfont_shader_puzzle/lib/main.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/main.dart",
"repo_id": "samples",
"token_count": 253
} | 1,189 |
# web_dashboard
**In progress**
A dashboard app that displays daily entries.
1. How to use an AdaptiveScaffold adaptive layout for large, medium, and small
screens.
2. How to use Firebase [Cloud
Firestore](https://firebase.google.com/docs/firestore) database with Google
Sign-In.
3. How to use [charts](https://pub.dev/packages/charts_flutter) to display
data.
4. (in progress) How to set up routing for a web app
This app is web-first, and isn't guaranteed to run on iOS, Android or desktop
platforms.
## Running
Normal mode (DDC):
```
flutter run -d chrome
```
Skia / CanvasKit mode:
```
flutter run -d chrome --release --dart-define=FLUTTER_WEB_USE_SKIA=true
```
## Running JSON code generator
```
flutter pub run grinder generate
```
## Add Firebase
### Step 1: Create a new Firebase project
Go to [console.firebase.google.com](https://console.firebase.google.com/) and
create a new Firebase project.
### Step 2: Enable Google Sign In for your project
In the Firebase console, go to "Authentication" and enable Google sign in. Click
on "Web SDK Configuration" and copy down your Web client ID.
### Step 3: Add Client ID to `index.html`
Uncomment this line in `index.html` and replace `<YOUR WEB CLIENT ID>` with the
client ID from Step 2:
```html
<!-- Uncomment and add Firebase client ID here: -->
<!-- <meta name="google-signin-client_id" content="<YOUR WEB CLIENT ID>"> -->
```
### Step 4: Create a web app
In the Firebase console, under "Project overview", click "Add app", select Web,
and replace the contents of `web/firebase_init.js`.
```javascript
// web/firebase_init.js
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
```
### Step 4: Create Cloud Firestore
Create a new Cloud Firestore database and add the following rules to disallow
users from reading/writing other users' data:
```
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /users/{userId}/{document=**} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}
```
### Step 5: Run the app
Run the app on port 5000:
```bash
flutter run -d chrome --web-port=5000
```
If you see CORS errors in your browser's console, go to the [Services
section][cloud-console-apis] in the Google Cloud console, go to Credentials, and
verify that `localhost:5000` is whitelisted.
### (optional) Step 7: Set up iOS and Android
If you would like to run the app on iOS or Android, make sure you've installed
the appropriate configuration files described at
[firebase.google.com/docs/flutter/setup][flutter-setup] from step 1, and follow
the instructions detailed in the [google_sign_in README][google-sign-in]
[flutter-setup]: https://firebase.google.com/docs/flutter/setup
[cloud-console-apis]: https://console.developers.google.com/apis/dashboard
[google-sign-in]: https://pub.dev/packages/google_sign_in
| samples/experimental/web_dashboard/README.md/0 | {
"file_path": "samples/experimental/web_dashboard/README.md",
"repo_id": "samples",
"token_count": 1051
} | 1,190 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import '../api/api.dart';
import 'day_helpers.dart';
/// The total value of one or more [Entry]s on a given day.
class EntryTotal {
final DateTime day;
int value;
EntryTotal(this.day, this.value);
}
/// Returns a list of [EntryTotal] objects. Each [EntryTotal] is the sum of
/// the values of all the entries on a given day.
List<EntryTotal> entryTotalsByDay(List<Entry>? entries, int daysAgo,
{DateTime? today}) {
today ??= DateTime.now();
return _entryTotalsByDay(entries, daysAgo, today).toList();
}
Iterable<EntryTotal> _entryTotalsByDay(
List<Entry>? entries, int daysAgo, DateTime today) sync* {
var start = today.subtract(Duration(days: daysAgo));
var entriesByDay = _entriesInRange(start, today, entries);
for (var i = 0; i < entriesByDay.length; i++) {
var list = entriesByDay[i];
var entryTotal = EntryTotal(start.add(Duration(days: i)), 0);
for (var entry in list) {
entryTotal.value += entry.value;
}
yield entryTotal;
}
}
/// Groups entries by day between [start] and [end]. The result is a list of
/// lists. The outer list represents the number of days since [start], and the
/// inner list is the group of entries on that day.
List<List<Entry>> _entriesInRange(
DateTime start, DateTime end, List<Entry>? entries) =>
_entriesInRangeImpl(start, end, entries).toList();
Iterable<List<Entry>> _entriesInRangeImpl(
DateTime start, DateTime end, List<Entry>? entries) sync* {
start = start.atMidnight;
end = end.atMidnight;
var d = start;
while (d.compareTo(end) <= 0) {
var es = <Entry>[];
for (var entry in entries!) {
if (d.isSameDay(entry.time.atMidnight)) {
es.add(entry);
}
}
yield es;
d = d.add(const Duration(days: 1));
}
}
| samples/experimental/web_dashboard/lib/src/utils/chart_utils.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/utils/chart_utils.dart",
"repo_id": "samples",
"token_count": 701
} | 1,191 |
{
"name": "web_dashboard",
"short_name": "web_dashboard",
"start_url": ".",
"display": "minimal-ui",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A desktop-friendly dashboard app",
"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"
}
]
}
| samples/experimental/web_dashboard/web/manifest.json/0 | {
"file_path": "samples/experimental/web_dashboard/web/manifest.json",
"repo_id": "samples",
"token_count": 310
} | 1,192 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO: Install a Google Maps API key that has Google Maps Web Services enabled
// See https://developers.google.com/places/web-service/get-api-key
const String googleMapsApiKey = 'ADD_A_KEY_HERE';
| samples/flutter_maps_firestore/lib/api_key.dart/0 | {
"file_path": "samples/flutter_maps_firestore/lib/api_key.dart",
"repo_id": "samples",
"token_count": 102
} | 1,193 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:logging/logging.dart';
class PreloadedBannerAd {
static final _log = Logger('PreloadedBannerAd');
/// Something like [AdSize.mediumRectangle].
final AdSize size;
final AdRequest _adRequest;
BannerAd? _bannerAd;
final String adUnitId;
final _adCompleter = Completer<BannerAd>();
PreloadedBannerAd({
required this.size,
required this.adUnitId,
AdRequest? adRequest,
}) : _adRequest = adRequest ?? const AdRequest();
Future<BannerAd> get ready => _adCompleter.future;
Future<void> load() {
assert(Platform.isAndroid || Platform.isIOS,
'AdMob currently does not support ${Platform.operatingSystem}');
_bannerAd = BannerAd(
// This is a test ad unit ID from
// https://developers.google.com/admob/android/test-ads. When ready,
// you replace this with your own, production ad unit ID,
// created in https://apps.admob.com/.
adUnitId: adUnitId,
size: size,
request: _adRequest,
listener: BannerAdListener(
onAdLoaded: (ad) {
_log.info(() => 'Ad loaded: ${_bannerAd.hashCode}');
_adCompleter.complete(_bannerAd);
},
onAdFailedToLoad: (ad, error) {
_log.warning('Banner failedToLoad: $error');
_adCompleter.completeError(error);
ad.dispose();
},
onAdImpression: (ad) {
_log.info('Ad impression registered');
},
onAdClicked: (ad) {
_log.info('Ad click registered');
},
),
);
return _bannerAd!.load();
}
void dispose() {
_log.info('preloaded banner ad being disposed');
_bannerAd?.dispose();
}
}
| samples/game_template/lib/src/ads/preloaded_banner_ad.dart/0 | {
"file_path": "samples/game_template/lib/src/ads/preloaded_banner_ad.dart",
"repo_id": "samples",
"token_count": 782
} | 1,194 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// An interface of persistence stores for the player's progress.
///
/// Implementations can range from simple in-memory storage through
/// local preferences to cloud saves.
abstract class PlayerProgressPersistence {
Future<int> getHighestLevelReached();
Future<void> saveHighestLevelReached(int level);
}
| samples/game_template/lib/src/player_progress/persistence/player_progress_persistence.dart/0 | {
"file_path": "samples/game_template/lib/src/player_progress/persistence/player_progress_persistence.dart",
"repo_id": "samples",
"token_count": 129
} | 1,195 |
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <audioplayers_windows/audioplayers_windows_plugin.h>
#include <firebase_core/firebase_core_plugin_c_api.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
AudioplayersWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin"));
FirebaseCorePluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FirebaseCorePluginCApi"));
}
| samples/game_template/windows/flutter/generated_plugin_registrant.cc/0 | {
"file_path": "samples/game_template/windows/flutter/generated_plugin_registrant.cc",
"repo_id": "samples",
"token_count": 176
} | 1,196 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'api/item.dart';
/// This is the widget responsible for building the item in the list,
/// once we have the actual data [item].
class ItemTile extends StatelessWidget {
final Item item;
const ItemTile({required this.item, super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
leading: AspectRatio(
aspectRatio: 1,
child: Container(
color: item.color,
),
),
title: Text(item.name, style: Theme.of(context).textTheme.titleLarge),
trailing: Text('\$ ${(item.price / 100).toStringAsFixed(2)}'),
),
);
}
}
/// This is the widget responsible for building the "still loading" item
/// in the list (represented with "..." and a crossed square).
class LoadingItemTile extends StatelessWidget {
const LoadingItemTile({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
leading: const AspectRatio(
aspectRatio: 1,
child: Placeholder(),
),
title: Text('...', style: Theme.of(context).textTheme.titleLarge),
trailing: const Text('\$ ...'),
),
);
}
}
| samples/infinite_list/lib/src/item_tile.dart/0 | {
"file_path": "samples/infinite_list/lib/src/item_tile.dart",
"repo_id": "samples",
"token_count": 561
} | 1,197 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/infinite_list/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/infinite_list/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,198 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const Demo());
}
// The same content is shown for both the main app target and in the App
// Clip.
class Demo extends StatefulWidget {
const Demo({super.key});
@override
State<Demo> createState() => _DemoState();
}
class _DemoState extends State<Demo> {
String deviceInfo = '';
@override
void initState() {
DeviceInfoPlugin().iosInfo.then((info) {
setState(() {
deviceInfo = '${info.name} on ${info.systemName} version '
'${info.systemVersion}';
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('App Clip'),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(deviceInfo),
const Padding(padding: EdgeInsets.only(top: 18)),
const FlutterLogo(size: 128),
],
),
),
),
);
}
}
| samples/ios_app_clip/lib/main.dart/0 | {
"file_path": "samples/ios_app_clip/lib/main.dart",
"repo_id": "samples",
"token_count": 572
} | 1,199 |
#import "GeneratedPluginRegistrant.h"
| samples/material_3_demo/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/material_3_demo/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,200 |
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_types_on_closure_parameters
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_3_demo/color_palettes_screen.dart';
import 'package:material_3_demo/main.dart';
import 'component_screen_test.dart';
void main() {
testWidgets(
'Color palettes screen shows correctly when color icon is clicked '
'on NavigationBar', (tester) async {
widgetSetup(tester, 449);
addTearDown(tester.view.resetPhysicalSize);
await tester.pumpWidget(const App());
expect(find.text('Light ColorScheme'), findsNothing);
expect(find.text('Dark ColorScheme'), findsNothing);
expect(find.byType(NavigationBar), findsOneWidget);
Finder colorIconOnBar = find.descendant(
of: find.byType(NavigationBar),
matching: find.widgetWithIcon(
NavigationDestination, Icons.format_paint_outlined));
expect(colorIconOnBar, findsOneWidget);
await tester.tap(colorIconOnBar);
await tester.pumpAndSettle(const Duration(microseconds: 500));
expect(colorIconOnBar, findsNothing);
Finder selectedColorIconOnBar = find.descendant(
of: find.byType(NavigationBar),
matching:
find.widgetWithIcon(NavigationDestination, Icons.format_paint));
expect(selectedColorIconOnBar, findsOneWidget);
expect(find.text('Light ColorScheme'), findsOneWidget);
expect(find.text('Dark ColorScheme'), findsOneWidget);
});
testWidgets(
'Color palettes screen shows correctly when color icon is clicked '
'on NavigationRail', (tester) async {
widgetSetup(
tester, 1200); // NavigationRail shows only when width is > 1000.
addTearDown(tester.view.resetPhysicalSize);
await tester.pumpWidget(const App());
await tester.pumpAndSettle();
expect(find.text('Light ColorScheme'), findsNothing);
expect(find.text('Dark ColorScheme'), findsNothing);
Finder colorIconOnRail = find.descendant(
of: find.byType(NavigationRail),
matching: find.byIcon(Icons.format_paint_outlined));
expect(colorIconOnRail, findsOneWidget);
await tester.tap(colorIconOnRail);
await tester.pumpAndSettle(const Duration(microseconds: 500));
expect(colorIconOnRail, findsNothing);
Finder selectedColorIconOnRail = find.descendant(
of: find.byType(NavigationRail),
matching: find.byIcon(Icons.format_paint));
expect(selectedColorIconOnRail, findsOneWidget);
expect(find.text('Light ColorScheme'), findsOneWidget);
expect(find.text('Dark ColorScheme'), findsOneWidget);
});
testWidgets('Color screen shows correct content', (tester) async {
await tester.pumpWidget(const MaterialApp(
home: Scaffold(body: Row(children: [ColorPalettesScreen()])),
));
expect(find.text('Light ColorScheme'), findsOneWidget);
expect(find.text('Dark ColorScheme'), findsOneWidget);
expect(find.byType(ColorGroup, skipOffstage: false), findsNWidgets(16));
});
}
| samples/material_3_demo/test/color_screen_test.dart/0 | {
"file_path": "samples/material_3_demo/test/color_screen_test.dart",
"repo_id": "samples",
"token_count": 1103
} | 1,201 |
include: package:analysis_defaults/flutter.yaml
| samples/navigation_and_routing/analysis_options.yaml/0 | {
"file_path": "samples/navigation_and_routing/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,202 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:platform_channels/src/counter_method_channel.dart';
/// The widget demonstrates how to use [MethodChannel] to invoke platform methods.
/// It has two [FilledButton]s to increment and decrement the value of
/// [count], and a [Text] widget to display its value.
class MethodChannelDemo extends StatefulWidget {
const MethodChannelDemo({super.key});
@override
State<MethodChannelDemo> createState() => _MethodChannelDemoState();
}
class _MethodChannelDemoState extends State<MethodChannelDemo> {
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('MethodChannel Demo'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Value of count is $count',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(
height: 16,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// Whenever users press the FilledButton, it invokes
// Counter.increment method to increment the value of count.
FilledButton.icon(
onPressed: () async {
try {
final value = await Counter.increment(counterValue: count);
setState(() => count = value);
} catch (error) {
if (!context.mounted) return;
showErrorMessage(
context,
(error as PlatformException).message!,
);
}
},
icon: const Icon(Icons.add),
label: const Text('Increment'),
),
// Whenever users press the FilledButton, it invokes
// Counter.decrement method to decrement the value of count.
FilledButton.icon(
onPressed: () async {
try {
final value = await Counter.decrement(counterValue: count);
setState(() => count = value);
} catch (error) {
if (!context.mounted) return;
showErrorMessage(
context,
(error as PlatformException).message!,
);
}
},
icon: const Icon(Icons.remove),
label: const Text('Decrement'),
)
],
)
],
),
);
}
void showErrorMessage(BuildContext context, String errorMessage) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage),
),
);
}
}
| samples/platform_channels/lib/src/method_channel_demo.dart/0 | {
"file_path": "samples/platform_channels/lib/src/method_channel_demo.dart",
"repo_id": "samples",
"token_count": 1478
} | 1,203 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| samples/platform_design/android/gradle.properties/0 | {
"file_path": "samples/platform_design/android/gradle.properties",
"repo_id": "samples",
"token_count": 30
} | 1,204 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'song_detail_tab.dart';
import 'utils.dart';
import 'widgets.dart';
class SongsTab extends StatefulWidget {
static const title = 'Songs';
static const androidIcon = Icon(Icons.music_note);
static const iosIcon = Icon(CupertinoIcons.music_note);
const SongsTab({super.key, this.androidDrawer});
final Widget? androidDrawer;
@override
State<SongsTab> createState() => _SongsTabState();
}
class _SongsTabState extends State<SongsTab> {
static const _itemsLength = 50;
final _androidRefreshKey = GlobalKey<RefreshIndicatorState>();
late List<MaterialColor> colors;
late List<String> songNames;
@override
void initState() {
_setData();
super.initState();
}
void _setData() {
colors = getRandomColors(_itemsLength);
songNames = getRandomNames(_itemsLength);
}
Future<void> _refreshData() {
return Future.delayed(
// This is just an arbitrary delay that simulates some network activity.
const Duration(seconds: 2),
() => setState(() => _setData()),
);
}
Widget _listBuilder(BuildContext context, int index) {
if (index >= _itemsLength) return Container();
// Show a slightly different color palette. Show poppy-ier colors on iOS
// due to lighter contrasting bars and tone it down on Android.
final color = defaultTargetPlatform == TargetPlatform.iOS
? colors[index]
: colors[index].shade400;
return SafeArea(
top: false,
bottom: false,
child: Hero(
tag: index,
child: HeroAnimatingSongCard(
song: songNames[index],
color: color,
heroAnimation: const AlwaysStoppedAnimation(0),
onPressed: () => Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (context) => SongDetailTab(
id: index,
song: songNames[index],
color: color,
),
),
),
),
),
);
}
void _togglePlatform() {
if (defaultTargetPlatform == TargetPlatform.iOS) {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
} else {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
}
// This rebuilds the application. This should obviously never be
// done in a real app but it's done here since this app
// unrealistically toggles the current platform for demonstration
// purposes.
WidgetsBinding.instance.reassembleApplication();
}
// ===========================================================================
// Non-shared code below because:
// - Android and iOS have different scaffolds
// - There are different items in the app bar / nav bar
// - Android has a hamburger drawer, iOS has bottom tabs
// - The iOS nav bar is scrollable, Android is not
// - Pull-to-refresh works differently, and Android has a button to trigger it too
//
// And these are all design time choices that doesn't have a single 'right'
// answer.
// ===========================================================================
Widget _buildAndroid(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(SongsTab.title),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () async =>
await _androidRefreshKey.currentState!.show(),
),
IconButton(
icon: const Icon(Icons.shuffle),
onPressed: _togglePlatform,
),
],
),
drawer: widget.androidDrawer,
body: RefreshIndicator(
key: _androidRefreshKey,
onRefresh: _refreshData,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 12),
itemCount: _itemsLength,
itemBuilder: _listBuilder,
),
),
);
}
Widget _buildIos(BuildContext context) {
return CustomScrollView(
slivers: [
CupertinoSliverNavigationBar(
trailing: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _togglePlatform,
child: const Icon(CupertinoIcons.shuffle),
),
),
CupertinoSliverRefreshControl(
onRefresh: _refreshData,
),
SliverSafeArea(
top: false,
sliver: SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 12),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
_listBuilder,
childCount: _itemsLength,
),
),
),
),
],
);
}
@override
Widget build(context) {
return PlatformWidget(
androidBuilder: _buildAndroid,
iosBuilder: _buildIos,
);
}
}
| samples/platform_design/lib/songs_tab.dart/0 | {
"file_path": "samples/platform_design/lib/songs_tab.dart",
"repo_id": "samples",
"token_count": 2010
} | 1,205 |
package com.example.provider_counter
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/provider_counter/android/app/src/main/kotlin/com/example/provider_counter/MainActivity.kt/0 | {
"file_path": "samples/provider_counter/android/app/src/main/kotlin/com/example/provider_counter/MainActivity.kt",
"repo_id": "samples",
"token_count": 39
} | 1,206 |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Provider Shopper rebuild script
steps:
- name: Remove runners
rmdirs:
- android
- ios
- linux
- macos
- web
- windows
- name: Flutter recreate
flutter: create --org dev.flutter .
- name: Update dependencies
flutter: pub upgrade --major-versions
- name: Build iOS simulator bundle
platforms: [ macos ]
flutter: build ios --simulator
| samples/provider_shopper/codelab_rebuild.yaml/0 | {
"file_path": "samples/provider_shopper/codelab_rebuild.yaml",
"repo_id": "samples",
"token_count": 185
} | 1,207 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:provider_shopper/models/cart.dart';
import 'package:provider_shopper/models/catalog.dart';
class MyCatalog extends StatelessWidget {
const MyCatalog({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
_MyAppBar(),
const SliverToBoxAdapter(child: SizedBox(height: 12)),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => _MyListItem(index)),
),
],
),
);
}
}
class _AddButton extends StatelessWidget {
final Item item;
const _AddButton({required this.item});
@override
Widget build(BuildContext context) {
// The context.select() method will let you listen to changes to
// a *part* of a model. You define a function that "selects" (i.e. returns)
// the part you're interested in, and the provider package will not rebuild
// this widget unless that particular part of the model changes.
//
// This can lead to significant performance improvements.
var isInCart = context.select<CartModel, bool>(
// Here, we are only interested whether [item] is inside the cart.
(cart) => cart.items.contains(item),
);
return TextButton(
onPressed: isInCart
? null
: () {
// If the item is not in cart, we let the user add it.
// We are using context.read() here because the callback
// is executed whenever the user taps the button. In other
// words, it is executed outside the build method.
var cart = context.read<CartModel>();
cart.add(item);
},
style: ButtonStyle(
overlayColor: MaterialStateProperty.resolveWith<Color?>((states) {
if (states.contains(MaterialState.pressed)) {
return Theme.of(context).primaryColor;
}
return null; // Defer to the widget's default.
}),
),
child: isInCart
? const Icon(Icons.check, semanticLabel: 'ADDED')
: const Text('ADD'),
);
}
}
class _MyAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SliverAppBar(
title: Text('Catalog', style: Theme.of(context).textTheme.displayLarge),
floating: true,
actions: [
IconButton(
icon: const Icon(Icons.shopping_cart),
onPressed: () => context.go('/catalog/cart'),
),
],
);
}
}
class _MyListItem extends StatelessWidget {
final int index;
const _MyListItem(this.index);
@override
Widget build(BuildContext context) {
var item = context.select<CatalogModel, Item>(
// Here, we are only interested in the item at [index]. We don't care
// about any other change.
(catalog) => catalog.getByPosition(index),
);
var textTheme = Theme.of(context).textTheme.titleLarge;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: LimitedBox(
maxHeight: 48,
child: Row(
children: [
AspectRatio(
aspectRatio: 1,
child: Container(
color: item.color,
),
),
const SizedBox(width: 24),
Expanded(
child: Text(item.name, style: textTheme),
),
const SizedBox(width: 24),
_AddButton(item: item),
],
),
),
);
}
}
| samples/provider_shopper/lib/screens/catalog.dart/0 | {
"file_path": "samples/provider_shopper/lib/screens/catalog.dart",
"repo_id": "samples",
"token_count": 1606
} | 1,208 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/provider_shopper/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/provider_shopper/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,209 |
#include "Generated.xcconfig"
| samples/simple_shader/ios/Flutter/Release.xcconfig/0 | {
"file_path": "samples/simple_shader/ios/Flutter/Release.xcconfig",
"repo_id": "samples",
"token_count": 12
} | 1,210 |
#include "ephemeral/Flutter-Generated.xcconfig"
| samples/simple_shader/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "samples/simple_shader/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "samples",
"token_count": 19
} | 1,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.