code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
part of oxygen;
abstract class PoolObject<T> {
/// The pool from which the object came from.
ObjectPool? _pool;
/// Initialize this object.
///
/// See [ObjectPool.acquire] for more information on how this gets called.
void init([T? data]);
/// Reset this object.
void reset();
/// Release this object back into the pool.
void dispose() => _pool?.release(this);
}
| oxygen/lib/src/pooling/pool_object.dart/0 | {'file_path': 'oxygen/lib/src/pooling/pool_object.dart', 'repo_id': 'oxygen', 'token_count': 115} |
name: animations_example
description: A catalog containing example animations from package:animations.
publish_to: none
version: 0.0.1
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
dependencies:
animations:
path: ../../animations
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/avatar_logo.png
- assets/placeholder_image.png
| packages/packages/animations/example/pubspec.yaml/0 | {'file_path': 'packages/packages/animations/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 191} |
// 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:animations/src/fade_through_transition.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'FadeThroughPageTransitionsBuilder builds a FadeThroughTransition',
(WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
);
await tester.pumpWidget(
const FadeThroughPageTransitionsBuilder().buildTransitions<void>(
null,
null,
animation,
secondaryAnimation,
const Placeholder(),
));
expect(find.byType(FadeThroughTransition), findsOneWidget);
});
testWidgets('FadeThroughTransition runs forward',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
// Bottom route is full size and fully visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
// top route is at 95% of full size and not visible yet.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
// Jump to half-way through the fade out (total duration is 300ms, 6/12th of
// that are fade out, so half-way is 300 * 6/12 / 2 = 45ms.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is fading out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
final double bottomOpacity = _getOpacity(bottomRoute, tester);
expect(bottomOpacity, lessThan(1.0));
expect(bottomOpacity, greaterThan(0.0));
// Top route is still invisible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
// Let's jump to the end of the fade-out.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is completely faded out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is still invisible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
// Let's jump to the middle of the fade-in.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is fading/scaling in.
expect(find.text(topRoute), findsOneWidget);
final double topScale = _getScale(topRoute, tester);
final double topOpacity = _getOpacity(topRoute, tester);
expect(topScale, greaterThan(0.92));
expect(topScale, lessThan(1.0));
expect(topOpacity, greaterThan(0.0));
expect(topOpacity, lessThan(1.0));
// Let's jump to the end of the animation.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route fully scaled in and visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(bottomRoute), findsNothing);
expect(find.text(topRoute), findsOneWidget);
});
testWidgets('FadeThroughTransition runs backwards',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
),
);
navigator.currentState!.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
expect(find.text(bottomRoute), findsNothing);
navigator.currentState!.pop();
await tester.pump();
// Top route is full size and fully visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
// Bottom route is at 95% of full size and not visible yet.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 0.92);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Jump to half-way through the fade out (total duration is 300ms, 6/12th of
// that are fade out, so half-way is 300 * 6/12 / 2 = 45ms.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is fading out.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
final double topOpacity = _getOpacity(topRoute, tester);
expect(topOpacity, lessThan(1.0));
expect(topOpacity, greaterThan(0.0));
// Top route is still invisible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 0.92);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Let's jump to the end of the fade-out.
await tester.pump(const Duration(milliseconds: 45));
// Bottom route is completely faded out.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Top route is still invisible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getScale(bottomRoute, tester),
moreOrLessEquals(0.92, epsilon: 0.005),
);
expect(
_getOpacity(bottomRoute, tester),
moreOrLessEquals(0.0, epsilon: 0.005),
);
// Let's jump to the middle of the fade-in.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Top route is fading/scaling in.
expect(find.text(bottomRoute), findsOneWidget);
final double bottomScale = _getScale(bottomRoute, tester);
final double bottomOpacity = _getOpacity(bottomRoute, tester);
expect(bottomScale, greaterThan(0.96));
expect(bottomScale, lessThan(1.0));
expect(bottomOpacity, greaterThan(0.1));
expect(bottomOpacity, lessThan(1.0));
// Let's jump to the end of the animation.
await tester.pump(const Duration(milliseconds: 105));
// Bottom route is not visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 0.0);
// Top route fully scaled in and visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
});
testWidgets('FadeThroughTransition does not jump when interrupted',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
// Jump to halfway point of transition.
await tester.pump(const Duration(milliseconds: 150));
// Bottom route is fully faded out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is fading/scaling in.
expect(find.text(topRoute), findsOneWidget);
final double topScale = _getScale(topRoute, tester);
final double topOpacity = _getOpacity(topRoute, tester);
expect(topScale, greaterThan(0.92));
expect(topScale, lessThan(1.0));
expect(topOpacity, greaterThan(0.0));
expect(topOpacity, lessThan(1.0));
// Interrupt the transition with a pop.
navigator.currentState!.pop();
await tester.pump();
// Noting changed.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 0.0);
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), topScale);
expect(_getOpacity(topRoute, tester), topOpacity);
// Jump to the halfway point.
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
final double bottomOpacity = _getOpacity(bottomRoute, tester);
expect(bottomOpacity, greaterThan(0.0));
expect(bottomOpacity, lessThan(1.0));
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), lessThan(topScale));
expect(_getOpacity(topRoute, tester), lessThan(topOpacity));
// Jump to the end.
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.92);
expect(_getOpacity(topRoute, tester), 0.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
});
testWidgets('State is not lost when transitioning',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
contentBuilder: (RouteSettings settings) {
return _StatefulTestWidget(
key: ValueKey<String?>(settings.name),
name: settings.name,
);
},
),
);
final _StatefulTestWidgetState bottomState =
tester.state(find.byKey(const ValueKey<String?>(bottomRoute)));
expect(bottomState.widget.name, bottomRoute);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(
const ValueKey<String?>(bottomRoute),
skipOffstage: false,
)),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
navigator.currentState!.pop();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
});
testWidgets('should keep state', (WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: FadeThroughTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
child: const _StatefulTestWidget(name: 'Foo'),
),
),
));
final State<StatefulWidget> state = tester.state(
find.byType(_StatefulTestWidget),
);
expect(state, isNotNull);
animation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
animation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
});
}
double _getOpacity(String key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(ValueKey<String?>(key)),
matching: find.byType(FadeTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final FadeTransition transition = widget as FadeTransition;
return a * transition.opacity.value;
});
}
double _getScale(String key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(ValueKey<String?>(key)),
matching: find.byType(ScaleTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final ScaleTransition transition = widget as ScaleTransition;
return a * transition.scale.value;
});
}
class _TestWidget extends StatelessWidget {
const _TestWidget({this.navigatorKey, this.contentBuilder});
final Key? navigatorKey;
final _ContentBuilder? contentBuilder;
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey as GlobalKey<NavigatorState>?,
theme: ThemeData(
platform: TargetPlatform.android,
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeThroughPageTransitionsBuilder(),
},
),
),
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
return contentBuilder != null
? contentBuilder!(settings)
: Center(
key: ValueKey<String?>(settings.name),
child: Text(settings.name!),
);
},
);
},
);
}
}
class _StatefulTestWidget extends StatefulWidget {
const _StatefulTestWidget({super.key, this.name});
final String? name;
@override
State<_StatefulTestWidget> createState() => _StatefulTestWidgetState();
}
class _StatefulTestWidgetState extends State<_StatefulTestWidget> {
@override
Widget build(BuildContext context) {
return Text(widget.name!);
}
}
typedef _ContentBuilder = Widget Function(RouteSettings settings);
| packages/packages/animations/test/fade_through_transition_test.dart/0 | {'file_path': 'packages/packages/animations/test/fade_through_transition_test.dart', 'repo_id': 'packages', 'token_count': 6765} |
name: camera_example
description: Demonstrates how to use the camera plugin.
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
dependencies:
camera:
# When depending on this package from a real application you should use:
# camera: ^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: ../
flutter:
sdk: flutter
path_provider: ^2.0.0
video_player: ^2.7.0
dev_dependencies:
build_runner: ^2.1.10
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/camera/camera/example/pubspec.yaml/0 | {'file_path': 'packages/packages/camera/camera/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 294} |
// 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' show BinaryMessenger;
import 'package:meta/meta.dart' show immutable;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// Represents exposure related information of a camera.
///
/// See https://developer.android.com/reference/androidx/camera/core/ExposureState.
@immutable
class ExposureState extends JavaObject {
/// Constructs a [ExposureState] that is not automatically attached to a native object.
ExposureState.detached(
{super.binaryMessenger,
super.instanceManager,
required this.exposureCompensationRange,
required this.exposureCompensationStep})
: super.detached() {
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
/// Gets the maximum and minimum exposure compensation values for the camera
/// represented by this instance.
final ExposureCompensationRange exposureCompensationRange;
/// Gets the smallest step by which the exposure compensation can be changed for
/// the camera represented by this instance.
final double exposureCompensationStep;
}
/// Flutter API implementation of [ExposureState].
class ExposureStateFlutterApiImpl implements ExposureStateFlutterApi {
/// Constructs a [ExposureStateFlutterApiImpl].
///
/// An [instanceManager] is typically passed when a copy of an instance
/// contained by an [InstanceManager] is being created.
ExposureStateFlutterApiImpl({
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,
ExposureCompensationRange exposureCompensationRange,
double exposureCompensationStep) {
instanceManager.addHostCreatedInstance(
ExposureState.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
exposureCompensationRange: exposureCompensationRange,
exposureCompensationStep: exposureCompensationStep),
identifier,
onCopy: (ExposureState original) {
return ExposureState.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
exposureCompensationRange: original.exposureCompensationRange,
exposureCompensationStep: original.exposureCompensationStep);
},
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/exposure_state.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/lib/src/exposure_state.dart', 'repo_id': 'packages', 'token_count': 868} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'aspect_ratio_strategy_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[
TestAspectRatioStrategyHostApi,
TestInstanceManagerHostApi,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('AspectRatioStrategy', () {
tearDown(() {
TestAspectRatioStrategyHostApi.setup(null);
TestInstanceManagerHostApi.setup(null);
});
test(
'detached create does not make call to create expected AspectRatioStrategy instance',
() async {
final MockTestAspectRatioStrategyHostApi mockApi =
MockTestAspectRatioStrategyHostApi();
TestAspectRatioStrategyHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int preferredAspectRatio = 1;
const int fallbackRule = 1;
AspectRatioStrategy.detached(
preferredAspectRatio: preferredAspectRatio,
fallbackRule: fallbackRule,
instanceManager: instanceManager,
);
verifyNever(mockApi.create(
argThat(isA<int>()),
preferredAspectRatio,
fallbackRule,
));
});
test(
'HostApi create makes call to create expected AspectRatioStrategy instance',
() {
final MockTestAspectRatioStrategyHostApi mockApi =
MockTestAspectRatioStrategyHostApi();
TestAspectRatioStrategyHostApi.setup(mockApi);
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int preferredAspectRatio = 0;
const int fallbackRule = 0;
final AspectRatioStrategy instance = AspectRatioStrategy(
preferredAspectRatio: preferredAspectRatio,
fallbackRule: fallbackRule,
instanceManager: instanceManager,
);
verify(mockApi.create(
instanceManager.getIdentifier(instance),
preferredAspectRatio,
fallbackRule,
));
});
});
}
| packages/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart', 'repo_id': 'packages', 'token_count': 984} |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/live_data_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestLiveDataHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestLiveDataHostApi extends _i1.Mock
implements _i2.TestLiveDataHostApi {
MockTestLiveDataHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void observe(
int? identifier,
int? observerIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#observe,
[
identifier,
observerIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void removeObservers(int? identifier) => super.noSuchMethod(
Invocation.method(
#removeObservers,
[identifier],
),
returnValueForMissingStub: null,
);
@override
int? getValue(
int? identifier,
_i3.LiveDataSupportedTypeData? type,
) =>
(super.noSuchMethod(Invocation.method(
#getValue,
[
identifier,
type,
],
)) as int?);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i2.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
| packages/packages/camera/camera_android_camerax/test/live_data_test.mocks.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/live_data_test.mocks.dart', 'repo_id': 'packages', 'token_count': 985} |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/recorder_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i7;
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2;
import 'package:camera_android_camerax/src/pending_recording.dart' as _i6;
import 'package:camera_android_camerax/src/quality_selector.dart' as _i4;
import 'package:camera_android_camerax/src/recording.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i5;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeResolutionInfo_0 extends _i1.SmartFake
implements _i2.ResolutionInfo {
_FakeResolutionInfo_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeRecording_1 extends _i1.SmartFake implements _i3.Recording {
_FakeRecording_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [QualitySelector].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockQualitySelector extends _i1.Mock implements _i4.QualitySelector {
MockQualitySelector() {
_i1.throwOnMissingStub(this);
}
@override
List<_i2.VideoQualityData> get qualityList => (super.noSuchMethod(
Invocation.getter(#qualityList),
returnValue: <_i2.VideoQualityData>[],
) as List<_i2.VideoQualityData>);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i5.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestFallbackStrategyHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestFallbackStrategyHostApi extends _i1.Mock
implements _i5.TestFallbackStrategyHostApi {
MockTestFallbackStrategyHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
_i2.VideoQuality? quality,
_i2.VideoResolutionFallbackRule? fallbackRule,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
quality,
fallbackRule,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestRecorderHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestRecorderHostApi extends _i1.Mock
implements _i5.TestRecorderHostApi {
MockTestRecorderHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? aspectRatio,
int? bitRate,
int? qualitySelectorId,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
aspectRatio,
bitRate,
qualitySelectorId,
],
),
returnValueForMissingStub: null,
);
@override
int getAspectRatio(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getAspectRatio,
[identifier],
),
returnValue: 0,
) as int);
@override
int getTargetVideoEncodingBitRate(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getTargetVideoEncodingBitRate,
[identifier],
),
returnValue: 0,
) as int);
@override
int prepareRecording(
int? identifier,
String? path,
) =>
(super.noSuchMethod(
Invocation.method(
#prepareRecording,
[
identifier,
path,
],
),
returnValue: 0,
) as int);
}
/// A class which mocks [TestQualitySelectorHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestQualitySelectorHostApi extends _i1.Mock
implements _i5.TestQualitySelectorHostApi {
MockTestQualitySelectorHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
List<_i2.VideoQualityData?>? videoQualityDataList,
int? fallbackStrategyId,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
videoQualityDataList,
fallbackStrategyId,
],
),
returnValueForMissingStub: null,
);
@override
_i2.ResolutionInfo getResolution(
int? cameraInfoId,
_i2.VideoQuality? quality,
) =>
(super.noSuchMethod(
Invocation.method(
#getResolution,
[
cameraInfoId,
quality,
],
),
returnValue: _FakeResolutionInfo_0(
this,
Invocation.method(
#getResolution,
[
cameraInfoId,
quality,
],
),
),
) as _i2.ResolutionInfo);
}
/// A class which mocks [PendingRecording].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockPendingRecording extends _i1.Mock implements _i6.PendingRecording {
MockPendingRecording() {
_i1.throwOnMissingStub(this);
}
@override
_i7.Future<_i3.Recording> start() => (super.noSuchMethod(
Invocation.method(
#start,
[],
),
returnValue: _i7.Future<_i3.Recording>.value(_FakeRecording_1(
this,
Invocation.method(
#start,
[],
),
)),
) as _i7.Future<_i3.Recording>);
}
| packages/packages/camera/camera_android_camerax/test/recorder_test.mocks.dart/0 | {'file_path': 'packages/packages/camera/camera_android_camerax/test/recorder_test.mocks.dart', 'repo_id': 'packages', 'token_count': 2846} |
// 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 '../types/types.dart';
/// Converts method channel call [data] for `receivedImageStreamData` to a
/// [CameraImageData].
CameraImageData cameraImageFromPlatformData(Map<dynamic, dynamic> data) {
return CameraImageData(
format: _cameraImageFormatFromPlatformData(data['format']),
height: data['height'] as int,
width: data['width'] as int,
lensAperture: data['lensAperture'] as double?,
sensorExposureTime: data['sensorExposureTime'] as int?,
sensorSensitivity: data['sensorSensitivity'] as double?,
planes: List<CameraImagePlane>.unmodifiable(
(data['planes'] as List<dynamic>).map<CameraImagePlane>(
(dynamic planeData) => _cameraImagePlaneFromPlatformData(
planeData as Map<dynamic, dynamic>))));
}
CameraImageFormat _cameraImageFormatFromPlatformData(dynamic data) {
return CameraImageFormat(_imageFormatGroupFromPlatformData(data), raw: data);
}
ImageFormatGroup _imageFormatGroupFromPlatformData(dynamic data) {
if (defaultTargetPlatform == TargetPlatform.android) {
switch (data) {
case 35: // android.graphics.ImageFormat.YUV_420_888
return ImageFormatGroup.yuv420;
case 256: // android.graphics.ImageFormat.JPEG
return ImageFormatGroup.jpeg;
}
}
if (defaultTargetPlatform == TargetPlatform.iOS) {
switch (data) {
case 875704438: // kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
return ImageFormatGroup.yuv420;
case 1111970369: // kCVPixelFormatType_32BGRA
return ImageFormatGroup.bgra8888;
}
}
return ImageFormatGroup.unknown;
}
CameraImagePlane _cameraImagePlaneFromPlatformData(Map<dynamic, dynamic> data) {
return CameraImagePlane(
bytes: data['bytes'] as Uint8List,
bytesPerPixel: data['bytesPerPixel'] as int?,
bytesPerRow: data['bytesPerRow'] as int,
height: data['height'] as int?,
width: data['width'] as int?);
}
| packages/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart/0 | {'file_path': 'packages/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart', 'repo_id': 'packages', 'token_count': 764} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
/// Demonstrates using an XFile result as an [Image] source, for the README.
Image getImageFromResultExample(XFile capturedImage) {
// #docregion ImageFromXFile
final Image image;
if (kIsWeb) {
image = Image.network(capturedImage.path);
} else {
image = Image.file(File(capturedImage.path));
}
// #enddocregion ImageFromXFile
return image;
}
| packages/packages/camera/camera_web/example/lib/readme_excerpts.dart/0 | {'file_path': 'packages/packages/camera/camera_web/example/lib/readme_excerpts.dart', 'repo_id': 'packages', 'token_count': 220} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html' as html;
import 'package:flutter/foundation.dart';
/// The possible range of values for the zoom level configurable
/// on the camera video track.
@immutable
class ZoomLevelCapability {
/// Creates a new instance of [ZoomLevelCapability] with the given
/// zoom level range of [minimum] to [maximum] configurable
/// on the [videoTrack].
const ZoomLevelCapability({
required this.minimum,
required this.maximum,
required this.videoTrack,
});
/// The zoom level constraint name.
/// See: https://w3c.github.io/mediacapture-image/#dom-mediatracksupportedconstraints-zoom
static const String constraintName = 'zoom';
/// The minimum zoom level.
final double minimum;
/// The maximum zoom level.
final double maximum;
/// The video track capable of configuring the zoom level.
final html.MediaStreamTrack videoTrack;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is ZoomLevelCapability &&
other.minimum == minimum &&
other.maximum == maximum &&
other.videoTrack == videoTrack;
}
@override
int get hashCode => Object.hash(minimum, maximum, videoTrack);
}
| packages/packages/camera/camera_web/lib/src/types/zoom_level_capability.dart/0 | {'file_path': 'packages/packages/camera/camera_web/lib/src/types/zoom_level_capability.dart', 'repo_id': 'packages', 'token_count': 418} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import './base.dart';
// ignore_for_file: avoid_unused_constructor_parameters
/// A CrossFile backed by a dart:io File.
class XFile extends XFileBase {
/// Construct a CrossFile object backed by a dart:io File.
///
/// [bytes] is ignored; the parameter exists only to match the web version of
/// the constructor. To construct a dart:io XFile from bytes, use
/// [XFile.fromData].
///
/// [name] is ignored; the parameter exists only to match the web version of
/// the constructor.
///
/// [length] is ignored; the parameter exists only to match the web version of
/// the constructor.
///
// ignore: use_super_parameters
XFile(
String path, {
String? mimeType,
String? name,
int? length,
Uint8List? bytes,
DateTime? lastModified,
}) : _mimeType = mimeType,
_file = File(path),
_bytes = null,
_lastModified = lastModified,
super(path);
/// Construct an CrossFile from its data
///
/// [name] is ignored; the parameter exists only to match the web version of
/// the constructor.
XFile.fromData(
Uint8List bytes, {
String? mimeType,
String? path,
String? name,
int? length,
DateTime? lastModified,
}) : _mimeType = mimeType,
_bytes = bytes,
_file = File(path ?? ''),
_length = length,
_lastModified = lastModified,
super(path) {
if (length == null) {
_length = bytes.length;
}
}
final File _file;
final String? _mimeType;
final DateTime? _lastModified;
int? _length;
final Uint8List? _bytes;
@override
Future<DateTime> lastModified() {
if (_lastModified != null) {
return Future<DateTime>.value(_lastModified);
}
// ignore: avoid_slow_async_io
return _file.lastModified();
}
@override
Future<void> saveTo(String path) async {
if (_bytes == null) {
await _file.copy(path);
} else {
final File fileToSave = File(path);
// TODO(kevmoo): Remove ignore and fix when the MIN Dart SDK is 3.3
// ignore: unnecessary_non_null_assertion
await fileToSave.writeAsBytes(_bytes!);
}
}
@override
String? get mimeType => _mimeType;
@override
String get path => _file.path;
@override
String get name => _file.path.split(Platform.pathSeparator).last;
@override
Future<int> length() {
if (_length != null) {
return Future<int>.value(_length);
}
return _file.length();
}
@override
Future<String> readAsString({Encoding encoding = utf8}) {
if (_bytes != null) {
// TODO(kevmoo): Remove ignore and fix when the MIN Dart SDK is 3.3
// ignore: unnecessary_non_null_assertion
return Future<String>.value(String.fromCharCodes(_bytes!));
}
return _file.readAsString(encoding: encoding);
}
@override
Future<Uint8List> readAsBytes() {
if (_bytes != null) {
return Future<Uint8List>.value(_bytes);
}
return _file.readAsBytes();
}
Stream<Uint8List> _getBytes(int? start, int? end) async* {
final Uint8List bytes = _bytes!;
yield bytes.sublist(start ?? 0, end ?? bytes.length);
}
@override
Stream<Uint8List> openRead([int? start, int? end]) {
if (_bytes != null) {
return _getBytes(start, end);
} else {
return _file
.openRead(start ?? 0, end)
.map((List<int> chunk) => Uint8List.fromList(chunk));
}
}
}
| packages/packages/cross_file/lib/src/types/io.dart/0 | {'file_path': 'packages/packages/cross_file/lib/src/types/io.dart', 'repo_id': 'packages', 'token_count': 1383} |
// 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/rendering.dart';
/// Describes the placement of a child in a [RenderDynamicSliverGrid].
class DynamicSliverGridGeometry extends SliverGridGeometry {
/// Creates an object that describes the placement of a child in a
/// [RenderDynamicSliverGrid].
const DynamicSliverGridGeometry({
required super.scrollOffset,
required super.crossAxisOffset,
required super.mainAxisExtent,
required super.crossAxisExtent,
});
/// Returns [BoxConstraints] that will be tight if the
/// [DynamicSliverGridLayout] has provided fixed extents, forcing the child to
/// have the required size.
///
/// If the [mainAxisExtent] is [double.infinity] the child will be allowed to
/// choose its own size in the main axis. Similarly, an infinite
/// [crossAxisExtent] will result in the child sizing itself in the cross
/// axis. Otherwise, the provided cross axis size or the
/// [SliverConstraints.crossAxisExtent] will be used to create tight
/// constraints in the cross axis.
///
/// This differs from [SliverGridGeometry.getBoxConstraints] in that it allows
/// loose constraints, allowing the child to be its preferred size, or within
/// a range of minimum and maximum extents.
@override
BoxConstraints getBoxConstraints(SliverConstraints constraints) {
final double mainMinExtent = mainAxisExtent.isFinite ? mainAxisExtent : 0;
final double crossMinExtent =
crossAxisExtent.isInfinite ? 0.0 : crossAxisExtent;
switch (constraints.axis) {
case Axis.vertical:
return BoxConstraints(
minHeight: mainMinExtent,
maxHeight: mainAxisExtent,
minWidth: crossMinExtent,
maxWidth: crossAxisExtent,
);
case Axis.horizontal:
return BoxConstraints(
minHeight: crossMinExtent,
maxHeight: crossAxisExtent,
minWidth: mainMinExtent,
maxWidth: mainAxisExtent,
);
}
}
}
/// Manages the size and position of all the tiles in a [RenderSliverGrid].
///
/// Rather than providing a grid with a [SliverGridLayout] directly, you instead
/// provide the grid with a [SliverGridDelegate], which can compute a
/// [SliverGridLayout] given the current [SliverConstraints].
///
/// {@template dynamicLayouts.garbageCollection}
/// This grid does not currently collect leading garbage as the user scrolls
/// further down. This is because the current implementation requires the
/// leading tiles to maintain the current layout. Follow
/// [this github issue](https://github.com/flutter/flutter/issues/112234) for
/// tracking progress on dynamic leading garbage collection.
/// {@endtemplate}
abstract class DynamicSliverGridLayout extends SliverGridLayout {
/// The estimated size and position of the child with the given index.
///
/// The [DynamicSliverGridGeometry] that is returned will
/// provide looser constraints to the child, whose size after layout can be
/// reported back to the layout object in [updateGeometryForChildIndex].
@override
DynamicSliverGridGeometry getGeometryForChildIndex(int index);
/// Update the size and position of the child with the given index,
/// considering the size of the child after layout.
///
/// This is used to update the layout object after the child has laid out,
/// allowing the layout pattern to adapt to the child's size.
DynamicSliverGridGeometry updateGeometryForChildIndex(
int index,
Size childSize,
);
/// Called by [RenderDynamicSliverGrid] to validate the layout pattern has
/// filled the screen.
///
/// A given child may have reached the target scroll offset of the current
/// layout pass, but there may still be more children to lay out based on the
/// pattern.
bool reachedTargetScrollOffset(double targetOffset);
// These methods are not relevant to dynamic grid building, but extending the
// base [SliverGridLayout] class allows us to re-use existing
// [SliverGridDelegate]s like [SliverGridDelegateWithFixedCrossAxisCount] and
// [SliverGridDelegateWithMaxCrossAxisExtent].
@override
@mustCallSuper
double computeMaxScrollOffset(int childCount) => throw UnimplementedError();
@override
@mustCallSuper
int getMaxChildIndexForScrollOffset(double scrollOffset) =>
throw UnimplementedError();
@override
@mustCallSuper
int getMinChildIndexForScrollOffset(double scrollOffset) =>
throw UnimplementedError();
}
| packages/packages/dynamic_layouts/lib/src/base_grid_layout.dart/0 | {'file_path': 'packages/packages/dynamic_layouts/lib/src/base_grid_layout.dart', 'repo_id': 'packages', 'token_count': 1381} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_linux/file_selector_linux.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FileSelectorLinux plugin;
late List<MethodCall> log;
setUp(() {
plugin = FileSelectorLinux();
log = <MethodCall>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
plugin.channel,
(MethodCall methodCall) async {
log.add(methodCall);
return null;
},
);
});
test('registers instance', () {
FileSelectorLinux.registerWith();
expect(FileSelectorPlatform.instance, isA<FileSelectorLinux>());
});
group('openFile', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'text',
'extensions': <String>['*.txt'],
'mimeTypes': <String>['text/plain'],
},
<String, Object>{
'label': 'image',
'extensions': <String>['*.jpg'],
'mimeTypes': <String>['image/jpg'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.openFile(initialDirectory: '/example/directory');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': false,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.openFile(confirmButtonText: 'Open File');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Open File',
'multiple': false,
},
);
});
test('throws for a type group that does not support Linux', () async {
const XTypeGroup group = XTypeGroup(
label: 'images',
webWildCards: <String>['images/*'],
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('passes a wildcard group correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'any',
);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'any',
'extensions': <String>['*'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
},
);
});
});
group('openFiles', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'text',
'extensions': <String>['*.txt'],
'mimeTypes': <String>['text/plain'],
},
<String, Object>{
'label': 'image',
'extensions': <String>['*.jpg'],
'mimeTypes': <String>['image/jpg'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.openFiles(initialDirectory: '/example/directory');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.openFiles(confirmButtonText: 'Open File');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Open File',
'multiple': true,
},
);
});
test('throws for a type group that does not support Linux', () async {
const XTypeGroup group = XTypeGroup(
label: 'images',
webWildCards: <String>['images/*'],
);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('passes a wildcard group correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'any',
);
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'any',
'extensions': <String>['*'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': true,
},
);
});
});
group('getSaveLocation', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin
.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'text',
'extensions': <String>['*.txt'],
'mimeTypes': <String>['text/plain'],
},
<String, Object>{
'label': 'image',
'extensions': <String>['*.jpg'],
'mimeTypes': <String>['image/jpg'],
},
],
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.getSaveLocation(
options:
const SaveDialogOptions(initialDirectory: '/example/directory'));
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getSaveLocation(
options: const SaveDialogOptions(confirmButtonText: 'Open File'));
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': 'Open File',
},
);
});
test('throws for a type group that does not support Linux', () async {
const XTypeGroup group = XTypeGroup(
label: 'images',
webWildCards: <String>['images/*'],
);
await expectLater(
plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('passes a wildcard group correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'any',
);
await plugin.getSaveLocation(acceptedTypeGroups: <XTypeGroup>[group]);
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'any',
'extensions': <String>['*'],
},
],
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': null,
},
);
});
});
group('getSavePath (deprecated)', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
);
await plugin
.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'text',
'extensions': <String>['*.txt'],
'mimeTypes': <String>['text/plain'],
},
<String, Object>{
'label': 'image',
'extensions': <String>['*.jpg'],
'mimeTypes': <String>['image/jpg'],
},
],
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.getSavePath(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getSavePath(confirmButtonText: 'Open File');
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': 'Open File',
},
);
});
test('throws for a type group that does not support Linux', () async {
const XTypeGroup group = XTypeGroup(
label: 'images',
webWildCards: <String>['images/*'],
);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('passes a wildcard group correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'any',
);
await plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]);
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'any',
'extensions': <String>['*'],
},
],
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': null,
},
);
});
});
group('getDirectoryPath', () {
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPath(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPath(confirmButtonText: 'Select Folder');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Select Folder',
},
);
});
});
group('getDirectoryPaths', () {
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPaths(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPaths(
confirmButtonText: 'Select one or mode folders');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Select one or mode folders',
'multiple': true,
},
);
});
test('passes multiple flag correctly', () async {
await plugin.getDirectoryPaths();
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': null,
'multiple': true,
},
);
});
});
}
void expectMethodCall(
List<MethodCall> log,
String methodName, {
Map<String, dynamic>? arguments,
}) {
expect(log, <Matcher>[isMethodCall(methodName, arguments: arguments)]);
}
| packages/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart', 'repo_id': 'packages', 'token_count': 6615} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'src/messages.g.dart';
/// An implementation of [FileSelectorPlatform] for macOS.
class FileSelectorMacOS extends FileSelectorPlatform {
final FileSelectorApi _hostApi = FileSelectorApi();
/// Registers the macOS implementation.
static void registerWith() {
FileSelectorPlatform.instance = FileSelectorMacOS();
}
@override
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String?> paths =
await _hostApi.displayOpenPanel(OpenPanelOptions(
allowsMultipleSelection: false,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions(
allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups),
directoryPath: initialDirectory,
prompt: confirmButtonText,
)));
return paths.isEmpty ? null : XFile(paths.first!);
}
@override
Future<List<XFile>> openFiles({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String?> paths =
await _hostApi.displayOpenPanel(OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: false,
canChooseFiles: true,
baseOptions: SavePanelOptions(
allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups),
directoryPath: initialDirectory,
prompt: confirmButtonText,
)));
return paths.map((String? path) => XFile(path!)).toList();
}
@override
Future<String?> getSavePath({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) async {
final FileSaveLocation? location = await getSaveLocation(
acceptedTypeGroups: acceptedTypeGroups,
options: SaveDialogOptions(
initialDirectory: initialDirectory,
suggestedName: suggestedName,
confirmButtonText: confirmButtonText,
));
return location?.path;
}
@override
Future<FileSaveLocation?> getSaveLocation({
List<XTypeGroup>? acceptedTypeGroups,
SaveDialogOptions options = const SaveDialogOptions(),
}) async {
final String? path = await _hostApi.displaySavePanel(SavePanelOptions(
allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups),
directoryPath: options.initialDirectory,
nameFieldStringValue: options.suggestedName,
prompt: options.confirmButtonText,
));
return path == null ? null : FileSaveLocation(path);
}
@override
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String?> paths =
await _hostApi.displayOpenPanel(OpenPanelOptions(
allowsMultipleSelection: false,
canChooseDirectories: true,
canChooseFiles: false,
baseOptions: SavePanelOptions(
directoryPath: initialDirectory,
prompt: confirmButtonText,
)));
return paths.isEmpty ? null : paths.first;
}
@override
Future<List<String>> getDirectoryPaths({
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String?> paths =
await _hostApi.displayOpenPanel(OpenPanelOptions(
allowsMultipleSelection: true,
canChooseDirectories: true,
canChooseFiles: false,
baseOptions: SavePanelOptions(
directoryPath: initialDirectory,
prompt: confirmButtonText,
)));
return paths.isEmpty ? <String>[] : List<String>.from(paths);
}
// Converts the type group list into a flat list of all allowed types, since
// macOS doesn't support filter groups.
AllowedTypes? _allowedTypesFromTypeGroups(List<XTypeGroup>? typeGroups) {
if (typeGroups == null || typeGroups.isEmpty) {
return null;
}
final AllowedTypes allowedTypes = AllowedTypes(
extensions: <String>[],
mimeTypes: <String>[],
utis: <String>[],
);
for (final XTypeGroup typeGroup in typeGroups) {
// If any group allows everything, no filtering should be done.
if (typeGroup.allowsAny) {
return null;
}
// Reject a filter that isn't an allow-any, but doesn't set any
// macOS-supported filter categories.
if ((typeGroup.extensions?.isEmpty ?? true) &&
(typeGroup.uniformTypeIdentifiers?.isEmpty ?? true) &&
(typeGroup.mimeTypes?.isEmpty ?? true)) {
throw ArgumentError('Provided type group $typeGroup does not allow '
'all files, but does not set any of the macOS-supported filter '
'categories. At least one of "extensions", '
'"uniformTypeIdentifiers", or "mimeTypes" must be non-empty for '
'macOS if anything is non-empty.');
}
allowedTypes.extensions.addAll(typeGroup.extensions ?? <String>[]);
allowedTypes.mimeTypes.addAll(typeGroup.mimeTypes ?? <String>[]);
allowedTypes.utis.addAll(typeGroup.uniformTypeIdentifiers ?? <String>[]);
}
return allowedTypes;
}
}
| packages/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart', 'repo_id': 'packages', 'token_count': 2097} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/services.dart';
import '../../file_selector_platform_interface.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/file_selector');
/// An implementation of [FileSelectorPlatform] that uses method channels.
class MethodChannelFileSelector extends FileSelectorPlatform {
/// The MethodChannel that is being used by this implementation of the plugin.
@visibleForTesting
MethodChannel get channel => _channel;
@override
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String>? path = await _channel.invokeListMethod<String>(
'openFile',
<String, dynamic>{
'acceptedTypeGroups': acceptedTypeGroups
?.map((XTypeGroup group) => group.toJSON())
.toList(),
'initialDirectory': initialDirectory,
'confirmButtonText': confirmButtonText,
'multiple': false,
},
);
return path == null ? null : XFile(path.first);
}
@override
Future<List<XFile>> openFiles({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String>? pathList = await _channel.invokeListMethod<String>(
'openFile',
<String, dynamic>{
'acceptedTypeGroups': acceptedTypeGroups
?.map((XTypeGroup group) => group.toJSON())
.toList(),
'initialDirectory': initialDirectory,
'confirmButtonText': confirmButtonText,
'multiple': true,
},
);
return pathList?.map((String path) => XFile(path)).toList() ?? <XFile>[];
}
@override
Future<String?> getSavePath({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) async {
return _channel.invokeMethod<String>(
'getSavePath',
<String, dynamic>{
'acceptedTypeGroups': acceptedTypeGroups
?.map((XTypeGroup group) => group.toJSON())
.toList(),
'initialDirectory': initialDirectory,
'suggestedName': suggestedName,
'confirmButtonText': confirmButtonText,
},
);
}
@override
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) async {
return _channel.invokeMethod<String>(
'getDirectoryPath',
<String, dynamic>{
'initialDirectory': initialDirectory,
'confirmButtonText': confirmButtonText,
},
);
}
@override
Future<List<String>> getDirectoryPaths(
{String? initialDirectory, String? confirmButtonText}) async {
final List<String>? pathList = await _channel.invokeListMethod<String>(
'getDirectoryPaths',
<String, dynamic>{
'initialDirectory': initialDirectory,
'confirmButtonText': confirmButtonText,
},
);
return pathList ?? <String>[];
}
}
| packages/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart', 'repo_id': 'packages', 'token_count': 1174} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:js_interop';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:file_selector_web/src/dom_helper.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:web/helpers.dart';
void main() {
group('dom_helper', () {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
late DomHelper domHelper;
late HTMLInputElement input;
FileList? createFileList(List<File> files) {
final DataTransfer dataTransfer = DataTransfer();
for (final File e in files) {
// TODO(srujzs): This is necessary in order to support package:web 0.4.0.
// This was not needed with 0.3.0, hence the lint.
// ignore: unnecessary_cast
dataTransfer.items.add(e as JSAny);
}
return dataTransfer.files;
}
void setFilesAndTriggerEvent(List<File> files, Event event) {
input.files = createFileList(files);
input.dispatchEvent(event);
}
void setFilesAndTriggerChange(List<File> files) {
setFilesAndTriggerEvent(files, Event('change'));
}
void setFilesAndTriggerCancel(List<File> files) {
setFilesAndTriggerEvent(files, Event('cancel'));
}
setUp(() {
domHelper = DomHelper();
input = (createElementTag('input') as HTMLInputElement)..type = 'file';
});
group('getFiles', () {
final File mockFile1 =
// TODO(srujzs): Remove once typed JSArrays (JSArray<T>) get to `stable`.
// ignore: always_specify_types
File(<Object>['123456'].jsify as JSArray, 'file1.txt');
// TODO(srujzs): Remove once typed JSArrays (JSArray<T>) get to `stable`.
// ignore: always_specify_types
final File mockFile2 = File(<Object>[].jsify as JSArray, 'file2.txt');
testWidgets('works', (_) async {
final Future<List<XFile>> futureFiles = domHelper.getFiles(
input: input,
);
setFilesAndTriggerChange(<File>[mockFile1, mockFile2]);
final List<XFile> files = await futureFiles;
expect(files.length, 2);
expect(files[0].name, 'file1.txt');
expect(await files[0].length(), 6);
expect(await files[0].readAsString(), '123456');
expect(await files[0].lastModified(), isNotNull);
expect(files[1].name, 'file2.txt');
expect(await files[1].length(), 0);
expect(await files[1].readAsString(), '');
expect(await files[1].lastModified(), isNotNull);
});
testWidgets('"cancel" returns an empty selection', (_) async {
final Future<List<XFile>> futureFiles = domHelper.getFiles(
input: input,
);
setFilesAndTriggerCancel(<File>[mockFile1, mockFile2]);
final List<XFile> files = await futureFiles;
expect(files.length, 0);
});
testWidgets('works multiple times', (_) async {
Future<List<XFile>> futureFiles;
List<XFile> files;
// It should work the first time
futureFiles = domHelper.getFiles(input: input);
setFilesAndTriggerChange(<File>[mockFile1]);
files = await futureFiles;
expect(files.length, 1);
expect(files.first.name, mockFile1.name);
// The same input should work more than once
futureFiles = domHelper.getFiles(input: input);
setFilesAndTriggerChange(<File>[mockFile2]);
files = await futureFiles;
expect(files.length, 1);
expect(files.first.name, mockFile2.name);
});
testWidgets('sets the <input /> attributes and clicks it', (_) async {
const String accept = '.jpg,.png';
const bool multiple = true;
bool wasClicked = false;
//ignore: unawaited_futures
input.onClick.first.then((_) => wasClicked = true);
final Future<List<XFile>> futureFile = domHelper.getFiles(
accept: accept,
multiple: multiple,
input: input,
);
expect(input.matches('body'), true);
expect(input.accept, accept);
expect(input.multiple, multiple);
expect(
wasClicked,
true,
reason:
'The <input /> should be clicked otherwise no dialog will be shown',
);
setFilesAndTriggerChange(<File>[]);
await futureFile;
// It should be already removed from the DOM after the file is resolved.
expect(input.parentElement, isNull);
});
});
});
}
| packages/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart/0 | {'file_path': 'packages/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart', 'repo_id': 'packages', 'token_count': 1905} |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/flutter_adaptive_scaffold/example/.pluginToolsConfig.yaml/0 | {'file_path': 'packages/packages/flutter_adaptive_scaffold/example/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../demos/basic_markdown_demo.dart';
import '../demos/centered_header_demo.dart';
import '../demos/extended_emoji_demo.dart';
import '../demos/markdown_body_shrink_wrap_demo.dart';
import '../demos/minimal_markdown_demo.dart';
import '../demos/original_demo.dart';
import '../demos/subscript_syntax_demo.dart';
import '../demos/wrap_alignment_demo.dart';
import '../screens/demo_card.dart';
import '../shared/markdown_demo_widget.dart';
// ignore_for_file: public_member_api_docs
class HomeScreen extends StatelessWidget {
HomeScreen({super.key});
static const String routeName = '/homeScreen';
final List<MarkdownDemoWidget> _demos = <MarkdownDemoWidget>[
const MinimalMarkdownDemo(),
const BasicMarkdownDemo(),
const WrapAlignmentDemo(),
const SubscriptSyntaxDemo(),
const ExtendedEmojiDemo(),
OriginalMarkdownDemo(),
const CenteredHeaderDemo(),
const MarkdownBodyShrinkWrapDemo(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('Markdown Demos'),
),
body: SafeArea(
child: ColoredBox(
color: Colors.black12,
child: ListView(
children: <Widget>[
for (final MarkdownDemoWidget demo in _demos)
DemoCard(widget: demo),
],
),
),
),
);
}
}
| packages/packages/flutter_markdown/example/lib/screens/home_screen.dart/0 | {'file_path': 'packages/packages/flutter_markdown/example/lib/screens/home_screen.dart', 'repo_id': 'packages', 'token_count': 652} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:mockito/mockito.dart';
class TestHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext? context) {
return createMockImageHttpClient(context);
}
}
MockHttpClient createMockImageHttpClient(SecurityContext? _) {
final MockHttpClient client = MockHttpClient();
final MockHttpClientRequest request = MockHttpClientRequest();
final MockHttpClientResponse response = MockHttpClientResponse();
final MockHttpHeaders headers = MockHttpHeaders();
final List<int> transparentImage = getTestImageData();
when(client.getUrl(any))
.thenAnswer((_) => Future<MockHttpClientRequest>.value(request));
when(request.headers).thenReturn(headers);
when(request.close())
.thenAnswer((_) => Future<MockHttpClientResponse>.value(response));
when(client.autoUncompress = any).thenAnswer((_) => null);
when(response.contentLength).thenReturn(transparentImage.length);
when(response.statusCode).thenReturn(HttpStatus.ok);
when(response.compressionState)
.thenReturn(HttpClientResponseCompressionState.notCompressed);
// Define an image stream that streams the mock test image for all
// image tests that request an image.
StreamSubscription<List<int>> imageStream(Invocation invocation) {
final void Function(List<int>)? onData =
invocation.positionalArguments[0] as void Function(List<int>)?;
final void Function()? onDone =
invocation.namedArguments[#onDone] as void Function()?;
final void Function(Object, [StackTrace?])? onError = invocation
.namedArguments[#onError] as void Function(Object, [StackTrace?])?;
final bool? cancelOnError =
invocation.namedArguments[#cancelOnError] as bool?;
return Stream<List<int>>.fromIterable(<List<int>>[transparentImage]).listen(
onData,
onError: onError,
onDone: onDone,
cancelOnError: cancelOnError,
);
}
when(response.listen(any,
onError: anyNamed('onError'),
onDone: anyNamed('onDone'),
cancelOnError: anyNamed('cancelOnError')))
.thenAnswer(imageStream);
return client;
}
// This string represents the hexidecial bytes of a transparent image. A
// string is used to make the visual representation of the data compact. A
// List<int> of the same data requires over 60 lines in a source file with
// each element in the array on a single line.
const String _imageBytesAsString = '''
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,
''';
// Convert the string representing the hexidecimal bytes in the image into
// a list of integers that can be consumed as image data in a stream.
final List<int> _transparentImage = const LineSplitter()
.convert(_imageBytesAsString.replaceAllMapped(
RegExp(r' *0x([A-F0-9]{2}),? *\n? *'), (Match m) => '${m[1]}\n'))
.map<int>((String b) => int.parse(b, radix: 16))
.toList();
List<int> getTestImageData() {
return _transparentImage;
}
/// Define the "fake" data types to be used in mock data type definitions. These
/// fake data types are important in the definition of the return values of the
/// properties and methods of the mock data types for null safety.
// ignore: avoid_implementing_value_types
class _FakeDuration extends Fake implements Duration {}
class _FakeHttpClientRequest extends Fake implements HttpClientRequest {}
class _FakeUri extends Fake implements Uri {}
class _FakeHttpHeaders extends Fake implements HttpHeaders {}
class _FakeHttpClientResponse extends Fake implements HttpClientResponse {}
class _FakeSocket extends Fake implements Socket {}
class _FakeStreamSubscription<T> extends Fake
implements StreamSubscription<T> {}
/// A class which mocks [HttpClient].
///
/// See the documentation for Mockito's code generation for more information.
class MockHttpClient extends Mock implements HttpClient {
MockHttpClient() {
throwOnMissingStub(this);
}
@override
Duration get idleTimeout =>
super.noSuchMethod(Invocation.getter(#idleTimeout),
returnValue: _FakeDuration()) as Duration;
@override
set idleTimeout(Duration? idleTimeout) =>
super.noSuchMethod(Invocation.setter(#idleTimeout, idleTimeout));
@override
bool get autoUncompress =>
super.noSuchMethod(Invocation.getter(#autoUncompress), returnValue: false)
as bool;
@override
set autoUncompress(bool? autoUncompress) =>
super.noSuchMethod(Invocation.setter(#autoUncompress, autoUncompress));
@override
Future<HttpClientRequest> open(
String? method, String? host, int? port, String? path) =>
super.noSuchMethod(
Invocation.method(#open, <Object?>[method, host, port, path]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> openUrl(String? method, Uri? url) =>
super.noSuchMethod(Invocation.method(#openUrl, <Object?>[method, url]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> get(String? host, int? port, String? path) =>
super.noSuchMethod(Invocation.method(#get, <Object?>[host, port, path]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> getUrl(Uri? url) => super.noSuchMethod(
Invocation.method(#getUrl, <Object?>[url]),
returnValue:
Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest()))
as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> post(String? host, int? port, String? path) =>
super.noSuchMethod(Invocation.method(#post, <Object?>[host, port, path]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> postUrl(Uri? url) => super.noSuchMethod(
Invocation.method(#postUrl, <Object?>[url]),
returnValue:
Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest()))
as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> put(String? host, int? port, String? path) =>
super.noSuchMethod(Invocation.method(#put, <Object?>[host, port, path]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> putUrl(Uri? url) => super.noSuchMethod(
Invocation.method(#putUrl, <Object?>[url]),
returnValue:
Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest()))
as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> delete(String? host, int? port, String? path) =>
super.noSuchMethod(
Invocation.method(#delete, <Object?>[host, port, path]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> deleteUrl(Uri? url) => super.noSuchMethod(
Invocation.method(#deleteUrl, <Object?>[url]),
returnValue:
Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest()))
as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> patch(String? host, int? port, String? path) =>
super.noSuchMethod(Invocation.method(#patch, <Object?>[host, port, path]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> patchUrl(Uri? url) => super.noSuchMethod(
Invocation.method(#patchUrl, <Object?>[url]),
returnValue:
Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest()))
as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> head(String? host, int? port, String? path) =>
super.noSuchMethod(Invocation.method(#head, <Object?>[host, port, path]),
returnValue: Future<_FakeHttpClientRequest>.value(
_FakeHttpClientRequest())) as Future<HttpClientRequest>;
@override
Future<HttpClientRequest> headUrl(Uri? url) => super.noSuchMethod(
Invocation.method(#headUrl, <Object?>[url]),
returnValue:
Future<_FakeHttpClientRequest>.value(_FakeHttpClientRequest()))
as Future<HttpClientRequest>;
@override
void addCredentials(
Uri? url, String? realm, HttpClientCredentials? credentials) =>
super.noSuchMethod(Invocation.method(
#addCredentials, <Object?>[url, realm, credentials]));
@override
void addProxyCredentials(String? host, int? port, String? realm,
HttpClientCredentials? credentials) =>
super.noSuchMethod(Invocation.method(
#addProxyCredentials, <Object?>[host, port, realm, credentials]));
@override
void close({bool? force = false}) => super.noSuchMethod(
Invocation.method(#close, <Object?>[], <Symbol, Object?>{#force: force}));
}
/// A class which mocks [HttpClientRequest].
///
/// See the documentation for Mockito's code generation for more information.
class MockHttpClientRequest extends Mock implements HttpClientRequest {
MockHttpClientRequest() {
throwOnMissingStub(this);
}
@override
bool get persistentConnection =>
super.noSuchMethod(Invocation.getter(#persistentConnection),
returnValue: false) as bool;
@override
set persistentConnection(bool? persistentConnection) => super.noSuchMethod(
Invocation.setter(#persistentConnection, persistentConnection));
@override
bool get followRedirects => super
.noSuchMethod(Invocation.getter(#followRedirects), returnValue: false)
as bool;
@override
set followRedirects(bool? followRedirects) =>
super.noSuchMethod(Invocation.setter(#followRedirects, followRedirects));
@override
int get maxRedirects =>
super.noSuchMethod(Invocation.getter(#maxRedirects), returnValue: 0)
as int;
@override
set maxRedirects(int? maxRedirects) =>
super.noSuchMethod(Invocation.setter(#maxRedirects, maxRedirects));
@override
int get contentLength =>
super.noSuchMethod(Invocation.getter(#contentLength), returnValue: 0)
as int;
@override
set contentLength(int? contentLength) =>
super.noSuchMethod(Invocation.setter(#contentLength, contentLength));
@override
bool get bufferOutput =>
super.noSuchMethod(Invocation.getter(#bufferOutput), returnValue: false)
as bool;
@override
set bufferOutput(bool? bufferOutput) =>
super.noSuchMethod(Invocation.setter(#bufferOutput, bufferOutput));
@override
String get method =>
super.noSuchMethod(Invocation.getter(#method), returnValue: '') as String;
@override
Uri get uri =>
super.noSuchMethod(Invocation.getter(#uri), returnValue: _FakeUri())
as Uri;
@override
HttpHeaders get headers => super.noSuchMethod(Invocation.getter(#headers),
returnValue: _FakeHttpHeaders()) as HttpHeaders;
@override
List<Cookie> get cookies =>
super.noSuchMethod(Invocation.getter(#cookies), returnValue: <Cookie>[])
as List<Cookie>;
@override
Future<HttpClientResponse> get done => super.noSuchMethod(
Invocation.getter(#done),
returnValue:
Future<_FakeHttpClientResponse>.value(_FakeHttpClientResponse()))
as Future<HttpClientResponse>;
@override
Future<HttpClientResponse> close() => super.noSuchMethod(
Invocation.method(#close, <Object?>[]),
returnValue:
Future<_FakeHttpClientResponse>.value(_FakeHttpClientResponse()))
as Future<HttpClientResponse>;
}
/// A class which mocks [HttpClientResponse].
///
/// See the documentation for Mockito's code generation for more information.
class MockHttpClientResponse extends Mock implements HttpClientResponse {
MockHttpClientResponse() {
throwOnMissingStub(this);
}
// Include an override method for the inherited listen method. This method
// intercepts HttpClientResponse listen calls to return a mock image.
@override
StreamSubscription<List<int>> listen(void Function(List<int> event)? onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) =>
super.noSuchMethod(
Invocation.method(
#listen,
<Object?>[onData],
<Symbol, Object?>{
#onError: onError,
#onDone: onDone,
#cancelOnError: cancelOnError
},
),
returnValue: _FakeStreamSubscription<List<int>>())
as StreamSubscription<List<int>>;
@override
int get statusCode =>
super.noSuchMethod(Invocation.getter(#statusCode), returnValue: 0) as int;
@override
String get reasonPhrase =>
super.noSuchMethod(Invocation.getter(#reasonPhrase), returnValue: '')
as String;
@override
int get contentLength =>
super.noSuchMethod(Invocation.getter(#contentLength), returnValue: 0)
as int;
@override
HttpClientResponseCompressionState get compressionState =>
super.noSuchMethod(Invocation.getter(#compressionState),
returnValue: HttpClientResponseCompressionState.notCompressed)
as HttpClientResponseCompressionState;
@override
bool get persistentConnection =>
super.noSuchMethod(Invocation.getter(#persistentConnection),
returnValue: false) as bool;
@override
bool get isRedirect =>
super.noSuchMethod(Invocation.getter(#isRedirect), returnValue: false)
as bool;
@override
List<RedirectInfo> get redirects =>
super.noSuchMethod(Invocation.getter(#redirects),
returnValue: <RedirectInfo>[]) as List<RedirectInfo>;
@override
HttpHeaders get headers => super.noSuchMethod(Invocation.getter(#headers),
returnValue: _FakeHttpHeaders()) as HttpHeaders;
@override
List<Cookie> get cookies =>
super.noSuchMethod(Invocation.getter(#cookies), returnValue: <Cookie>[])
as List<Cookie>;
@override
Future<HttpClientResponse> redirect(
[String? method, Uri? url, bool? followLoops]) =>
super.noSuchMethod(
Invocation.method(#redirect, <Object?>[method, url, followLoops]),
returnValue: Future<_FakeHttpClientResponse>.value(
_FakeHttpClientResponse())) as Future<HttpClientResponse>;
@override
Future<Socket> detachSocket() => super.noSuchMethod(
Invocation.method(#detachSocket, <Object?>[]),
returnValue: Future<_FakeSocket>.value(_FakeSocket())) as Future<Socket>;
}
/// A class which mocks [HttpHeaders].
///
/// See the documentation for Mockito's code generation for more information.
class MockHttpHeaders extends Mock implements HttpHeaders {
MockHttpHeaders() {
throwOnMissingStub(this);
}
@override
int get contentLength =>
super.noSuchMethod(Invocation.getter(#contentLength), returnValue: 0)
as int;
@override
set contentLength(int? contentLength) =>
super.noSuchMethod(Invocation.setter(#contentLength, contentLength));
@override
bool get persistentConnection =>
super.noSuchMethod(Invocation.getter(#persistentConnection),
returnValue: false) as bool;
@override
set persistentConnection(bool? persistentConnection) => super.noSuchMethod(
Invocation.setter(#persistentConnection, persistentConnection));
@override
bool get chunkedTransferEncoding =>
super.noSuchMethod(Invocation.getter(#chunkedTransferEncoding),
returnValue: false) as bool;
@override
set chunkedTransferEncoding(bool? chunkedTransferEncoding) =>
super.noSuchMethod(
Invocation.setter(#chunkedTransferEncoding, chunkedTransferEncoding));
@override
List<String>? operator [](String? name) =>
super.noSuchMethod(Invocation.method(#[], <Object?>[name]))
as List<String>?;
@override
String? value(String? name) =>
super.noSuchMethod(Invocation.method(#value, <Object?>[name])) as String?;
@override
void add(String? name, Object? value, {bool? preserveHeaderCase = false}) =>
super.noSuchMethod(Invocation.method(#add, <Object?>[name, value],
<Symbol, Object?>{#preserveHeaderCase: preserveHeaderCase}));
@override
void set(String? name, Object? value, {bool? preserveHeaderCase = false}) =>
super.noSuchMethod(Invocation.method(#set, <Object?>[name, value],
<Symbol, Object?>{#preserveHeaderCase: preserveHeaderCase}));
@override
void remove(String? name, Object? value) =>
super.noSuchMethod(Invocation.method(#remove, <Object?>[name, value]));
@override
void removeAll(String? name) =>
super.noSuchMethod(Invocation.method(#removeAll, <Object?>[name]));
@override
void forEach(void Function(String, List<String>)? action) =>
super.noSuchMethod(Invocation.method(#forEach, <Object?>[action]));
@override
void noFolding(String? name) =>
super.noSuchMethod(Invocation.method(#noFolding, <Object?>[name]));
}
| packages/packages/flutter_markdown/test/image_test_mocks.dart/0 | {'file_path': 'packages/packages/flutter_markdown/test/image_test_mocks.dart', 'repo_id': 'packages', 'token_count': 6533} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:process/process.dart';
import 'base/common.dart';
import 'base/file_system.dart';
import 'base/io.dart';
import 'base/logger.dart';
import 'base/signals.dart';
import 'base/terminal.dart';
/// Initializes the boilerplate dependencies needed by the migrate tool.
class MigrateBaseDependencies {
MigrateBaseDependencies() {
processManager = const LocalProcessManager();
fileSystem = LocalFileSystem(
LocalSignals.instance, Signals.defaultExitSignals, ShutdownHooks());
stdio = Stdio();
terminal = AnsiTerminal(stdio: stdio);
final LoggerFactory loggerFactory = LoggerFactory(
outputPreferences: OutputPreferences(
wrapText: stdio.hasTerminal,
showColor: stdout.supportsAnsiEscapes,
stdio: stdio,
),
terminal: terminal,
stdio: stdio,
);
logger = loggerFactory.createLogger(
windows: isWindows,
);
}
late final ProcessManager processManager;
late final LocalFileSystem fileSystem;
late final Stdio stdio;
late final Terminal terminal;
late final Logger logger;
}
/// An abstraction for instantiation of the correct logger type.
///
/// Our logger class hierarchy and runtime requirements are overly complicated.
class LoggerFactory {
LoggerFactory({
required Terminal terminal,
required Stdio stdio,
required OutputPreferences outputPreferences,
StopwatchFactory stopwatchFactory = const StopwatchFactory(),
}) : _terminal = terminal,
_stdio = stdio,
_stopwatchFactory = stopwatchFactory,
_outputPreferences = outputPreferences;
final Terminal _terminal;
final Stdio _stdio;
final StopwatchFactory _stopwatchFactory;
final OutputPreferences _outputPreferences;
/// Create the appropriate logger for the current platform and configuration.
Logger createLogger({
required bool windows,
}) {
Logger logger;
if (windows) {
logger = WindowsStdoutLogger(
terminal: _terminal,
stdio: _stdio,
outputPreferences: _outputPreferences,
stopwatchFactory: _stopwatchFactory,
);
} else {
logger = StdoutLogger(
terminal: _terminal,
stdio: _stdio,
outputPreferences: _outputPreferences,
stopwatchFactory: _stopwatchFactory);
}
return logger;
}
}
| packages/packages/flutter_migrate/lib/src/base_dependencies.dart/0 | {'file_path': 'packages/packages/flutter_migrate/lib/src/base_dependencies.dart', 'repo_id': 'packages', 'token_count': 867} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io show Directory, File, IOOverrides, Link;
import 'package:flutter_migrate/src/base/file_system.dart';
/// An [IOOverrides] that can delegate to [FileSystem] implementation if provided.
///
/// Does not override any of the socket facilities.
///
/// Do not provide a [LocalFileSystem] as a delegate. Since internally this calls
/// out to `dart:io` classes, it will result in a stack overflow error as the
/// IOOverrides and LocalFileSystem call each other endlessly.
///
/// The only safe delegate types are those that do not call out to `dart:io`,
/// like the [MemoryFileSystem].
class FlutterIOOverrides extends io.IOOverrides {
FlutterIOOverrides({FileSystem? fileSystem})
: _fileSystemDelegate = fileSystem;
final FileSystem? _fileSystemDelegate;
@override
io.Directory createDirectory(String path) {
if (_fileSystemDelegate == null) {
return super.createDirectory(path);
}
return _fileSystemDelegate!.directory(path);
}
@override
io.File createFile(String path) {
if (_fileSystemDelegate == null) {
return super.createFile(path);
}
return _fileSystemDelegate!.file(path);
}
@override
io.Link createLink(String path) {
if (_fileSystemDelegate == null) {
return super.createLink(path);
}
return _fileSystemDelegate!.link(path);
}
@override
Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) {
if (_fileSystemDelegate == null) {
return super.fsWatch(path, events, recursive);
}
return _fileSystemDelegate!
.file(path)
.watch(events: events, recursive: recursive);
}
@override
bool fsWatchIsSupported() {
if (_fileSystemDelegate == null) {
return super.fsWatchIsSupported();
}
return _fileSystemDelegate!.isWatchSupported;
}
@override
Future<FileSystemEntityType> fseGetType(String path, bool followLinks) {
if (_fileSystemDelegate == null) {
return super.fseGetType(path, followLinks);
}
return _fileSystemDelegate!.type(path, followLinks: followLinks);
}
@override
FileSystemEntityType fseGetTypeSync(String path, bool followLinks) {
if (_fileSystemDelegate == null) {
return super.fseGetTypeSync(path, followLinks);
}
return _fileSystemDelegate!.typeSync(path, followLinks: followLinks);
}
@override
Future<bool> fseIdentical(String path1, String path2) {
if (_fileSystemDelegate == null) {
return super.fseIdentical(path1, path2);
}
return _fileSystemDelegate!.identical(path1, path2);
}
@override
bool fseIdenticalSync(String path1, String path2) {
if (_fileSystemDelegate == null) {
return super.fseIdenticalSync(path1, path2);
}
return _fileSystemDelegate!.identicalSync(path1, path2);
}
@override
io.Directory getCurrentDirectory() {
if (_fileSystemDelegate == null) {
return super.getCurrentDirectory();
}
return _fileSystemDelegate!.currentDirectory;
}
@override
io.Directory getSystemTempDirectory() {
if (_fileSystemDelegate == null) {
return super.getSystemTempDirectory();
}
return _fileSystemDelegate!.systemTempDirectory;
}
@override
void setCurrentDirectory(String path) {
if (_fileSystemDelegate == null) {
return super.setCurrentDirectory(path);
}
_fileSystemDelegate!.currentDirectory = path;
}
@override
Future<FileStat> stat(String path) {
if (_fileSystemDelegate == null) {
return super.stat(path);
}
return _fileSystemDelegate!.stat(path);
}
@override
FileStat statSync(String path) {
if (_fileSystemDelegate == null) {
return super.statSync(path);
}
return _fileSystemDelegate!.statSync(path);
}
}
| packages/packages/flutter_migrate/test/src/io.dart/0 | {'file_path': 'packages/packages/flutter_migrate/test/src/io.dart', 'repo_id': 'packages', 'token_count': 1338} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../data.dart';
import '../widgets/book_list.dart';
/// The author detail screen.
class AuthorDetailsScreen extends StatelessWidget {
/// Creates an author detail screen.
const AuthorDetailsScreen({
required this.author,
super.key,
});
/// The author to be displayed.
final Author? author;
@override
Widget build(BuildContext context) {
if (author == null) {
return const Scaffold(
body: Center(
child: Text('No author found.'),
),
);
}
return Scaffold(
appBar: AppBar(
title: Text(author!.name),
),
body: Center(
child: Column(
children: <Widget>[
Expanded(
child: BookList(
books: author!.books,
onTap: (Book book) => context.go('/book/${book.id}'),
),
),
],
),
),
);
}
}
| packages/packages/go_router/example/lib/books/src/screens/author_details.dart/0 | {'file_path': 'packages/packages/go_router/example/lib/books/src/screens/author_details.dart', 'repo_id': 'packages', 'token_count': 498} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
/// Family data class.
class Family {
/// Create a family.
const Family({required this.name, required this.people});
/// The last name of the family.
final String name;
/// The people in the family.
final Map<String, Person> people;
}
/// Person data class.
class Person {
/// Creates a person.
const Person({required this.name});
/// The first name of the person.
final String name;
}
const Map<String, Family> _families = <String, Family>{
'f1': Family(
name: 'Doe',
people: <String, Person>{
'p1': Person(name: 'Jane'),
'p2': Person(name: 'John'),
},
),
'f2': Family(
name: 'Wong',
people: <String, Person>{
'p1': Person(name: 'June'),
'p2': Person(name: 'Xin'),
},
),
};
void main() => runApp(App());
/// The main app.
class App extends StatelessWidget {
/// Creates an [App].
App({super.key});
/// The title of the app.
static const String title = 'GoRouter Example: Extra Parameter';
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
title: title,
);
late final GoRouter _router = GoRouter(
routes: <GoRoute>[
GoRoute(
name: 'home',
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
path: 'family',
builder: (BuildContext context, GoRouterState state) {
final Map<String, Object> params =
state.extra! as Map<String, String>;
final String fid = params['fid']! as String;
return FamilyScreen(fid: fid);
},
),
],
),
],
);
}
/// The home screen that shows a list of families.
class HomeScreen extends StatelessWidget {
/// Creates a [HomeScreen].
const HomeScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text(App.title)),
body: ListView(
children: <Widget>[
for (final MapEntry<String, Family> entry in _families.entries)
ListTile(
title: Text(entry.value.name),
onTap: () => context.goNamed('family',
extra: <String, String>{'fid': entry.key}),
)
],
),
);
}
/// The screen that shows a list of persons in a family.
class FamilyScreen extends StatelessWidget {
/// Creates a [FamilyScreen].
const FamilyScreen({required this.fid, super.key});
/// The family to display.
final String fid;
@override
Widget build(BuildContext context) {
final Map<String, Person> people = _families[fid]!.people;
return Scaffold(
appBar: AppBar(title: Text(_families[fid]!.name)),
body: ListView(
children: <Widget>[
for (final Person p in people.values)
ListTile(
title: Text(p.name),
),
],
),
);
}
}
| packages/packages/go_router/example/lib/others/extra_param.dart/0 | {'file_path': 'packages/packages/go_router/example/lib/others/extra_param.dart', 'repo_id': 'packages', 'token_count': 1373} |
// 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:go_router_examples/path_and_query_parameters.dart' as example;
void main() {
testWidgets('example works', (WidgetTester tester) async {
await tester.pumpWidget(example.App());
expect(find.text(example.App.title), findsOneWidget);
// Directly set the url through platform message.
Map<String, dynamic> testRouteInformation = <String, dynamic>{
'location': '/family/f1?sort=asc',
};
ByteData message = const JSONMethodCodec().encodeMethodCall(
MethodCall('pushRouteInformation', testRouteInformation),
);
await tester.binding.defaultBinaryMessenger
.handlePlatformMessage('flutter/navigation', message, (_) {});
await tester.pumpAndSettle();
// 'Chris' should be higher than 'Tom'.
expect(
tester.getCenter(find.text('Jane')).dy <
tester.getCenter(find.text('John')).dy,
isTrue);
testRouteInformation = <String, dynamic>{
'location': '/family/f1?privacy=false',
};
message = const JSONMethodCodec().encodeMethodCall(
MethodCall('pushRouteInformation', testRouteInformation),
);
await tester.binding.defaultBinaryMessenger
.handlePlatformMessage('flutter/navigation', message, (_) {});
await tester.pumpAndSettle();
// 'Chris' should be lower than 'Tom'.
expect(
tester.getCenter(find.text('Jane')).dy >
tester.getCenter(find.text('John')).dy,
isTrue);
});
}
| packages/packages/go_router/example/test/path_and_query_params_test.dart/0 | {'file_path': 'packages/packages/go_router/example/test/path_and_query_params_test.dart', 'repo_id': 'packages', 'token_count': 616} |
// 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:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'match.dart';
// TODO(chunhtai): remove this ignore and migrate the code
// https://github.com/flutter/flutter/issues/124045.
// ignore_for_file: deprecated_member_use
/// The type of the navigation.
///
/// This enum is used by [RouteInformationState] to denote the navigation
/// operations.
enum NavigatingType {
/// Push new location on top of the [RouteInformationState.baseRouteMatchList].
push,
/// Push new location and remove top-most [RouteMatch] of the
/// [RouteInformationState.baseRouteMatchList].
pushReplacement,
/// Push new location and replace top-most [RouteMatch] of the
/// [RouteInformationState.baseRouteMatchList].
replace,
/// Replace the entire [RouteMatchList] with the new location.
go,
/// Restore the current match list with
/// [RouteInformationState.baseRouteMatchList].
restore,
}
/// The data class to be stored in [RouteInformation.state] to be used by
/// [GoRouteInformationParser].
///
/// This state class is used internally in go_router and will not be sent to
/// the engine.
class RouteInformationState<T> {
/// Creates an InternalRouteInformationState.
@visibleForTesting
RouteInformationState({
this.extra,
this.completer,
this.baseRouteMatchList,
required this.type,
}) : assert((type == NavigatingType.go || type == NavigatingType.restore) ==
(completer == null)),
assert((type != NavigatingType.go) == (baseRouteMatchList != null));
/// The extra object used when navigating with [GoRouter].
final Object? extra;
/// The completer that needs to be completed when the newly added route is
/// popped off the screen.
///
/// This is only null if [type] is [NavigatingType.go] or
/// [NavigatingType.restore].
final Completer<T?>? completer;
/// The base route match list to push on top to.
///
/// This is only null if [type] is [NavigatingType.go].
final RouteMatchList? baseRouteMatchList;
/// The type of navigation.
final NavigatingType type;
}
/// The [RouteInformationProvider] created by go_router.
class GoRouteInformationProvider extends RouteInformationProvider
with WidgetsBindingObserver, ChangeNotifier {
/// Creates a [GoRouteInformationProvider].
GoRouteInformationProvider({
required String initialLocation,
required Object? initialExtra,
Listenable? refreshListenable,
}) : _refreshListenable = refreshListenable,
_value = RouteInformation(
location: initialLocation,
state: RouteInformationState<void>(
extra: initialExtra, type: NavigatingType.go),
),
_valueInEngine = _kEmptyRouteInformation {
_refreshListenable?.addListener(notifyListeners);
}
final Listenable? _refreshListenable;
static WidgetsBinding get _binding => WidgetsBinding.instance;
static const RouteInformation _kEmptyRouteInformation =
RouteInformation(location: '');
@override
void routerReportsNewRouteInformation(RouteInformation routeInformation,
{RouteInformationReportingType type =
RouteInformationReportingType.none}) {
// GoRouteInformationParser should always report encoded route match list
// in the state.
assert(routeInformation.state != null);
final bool replace;
switch (type) {
case RouteInformationReportingType.none:
if (_valueInEngine.location == routeInformation.location &&
const DeepCollectionEquality()
.equals(_valueInEngine.state, routeInformation.state)) {
return;
}
replace = _valueInEngine == _kEmptyRouteInformation;
case RouteInformationReportingType.neglect:
replace = true;
case RouteInformationReportingType.navigate:
replace = false;
}
SystemNavigator.selectMultiEntryHistory();
SystemNavigator.routeInformationUpdated(
// TODO(chunhtai): remove this ignore and migrate the code
// https://github.com/flutter/flutter/issues/124045.
// ignore: unnecessary_null_checks, unnecessary_non_null_assertion
location: routeInformation.location!,
state: routeInformation.state,
replace: replace,
);
_value = _valueInEngine = routeInformation;
}
@override
RouteInformation get value => _value;
RouteInformation _value;
@override
// TODO(chunhtai): remove this ignore once package minimum dart version is
// above 3.
// ignore: unnecessary_overrides
void notifyListeners() {
super.notifyListeners();
}
void _setValue(String location, Object state) {
final bool shouldNotify =
_value.location != location || _value.state != state;
_value = RouteInformation(location: location, state: state);
if (shouldNotify) {
notifyListeners();
}
}
/// Pushes the `location` as a new route on top of `base`.
Future<T?> push<T>(String location,
{required RouteMatchList base, Object? extra}) {
final Completer<T?> completer = Completer<T?>();
_setValue(
location,
RouteInformationState<T>(
extra: extra,
baseRouteMatchList: base,
completer: completer,
type: NavigatingType.push,
),
);
return completer.future;
}
/// Replace the current route matches with the `location`.
void go(String location, {Object? extra}) {
_setValue(
location,
RouteInformationState<void>(
extra: extra,
type: NavigatingType.go,
),
);
}
/// Restores the current route matches with the `matchList`.
void restore(String location, {required RouteMatchList matchList}) {
_setValue(
matchList.uri.toString(),
RouteInformationState<void>(
extra: matchList.extra,
baseRouteMatchList: matchList,
type: NavigatingType.restore,
),
);
}
/// Removes the top-most route match from `base` and pushes the `location` as a
/// new route on top.
Future<T?> pushReplacement<T>(String location,
{required RouteMatchList base, Object? extra}) {
final Completer<T?> completer = Completer<T?>();
_setValue(
location,
RouteInformationState<T>(
extra: extra,
baseRouteMatchList: base,
completer: completer,
type: NavigatingType.pushReplacement,
),
);
return completer.future;
}
/// Replaces the top-most route match from `base` with the `location`.
Future<T?> replace<T>(String location,
{required RouteMatchList base, Object? extra}) {
final Completer<T?> completer = Completer<T?>();
_setValue(
location,
RouteInformationState<T>(
extra: extra,
baseRouteMatchList: base,
completer: completer,
type: NavigatingType.replace,
),
);
return completer.future;
}
RouteInformation _valueInEngine;
void _platformReportsNewRouteInformation(RouteInformation routeInformation) {
if (_value == routeInformation) {
return;
}
if (routeInformation.state != null) {
_value = _valueInEngine = routeInformation;
} else {
_value = RouteInformation(
location: routeInformation.location,
state: RouteInformationState<void>(type: NavigatingType.go),
);
_valueInEngine = _kEmptyRouteInformation;
}
notifyListeners();
}
@override
void addListener(VoidCallback listener) {
if (!hasListeners) {
_binding.addObserver(this);
}
super.addListener(listener);
}
@override
void removeListener(VoidCallback listener) {
super.removeListener(listener);
if (!hasListeners) {
_binding.removeObserver(this);
}
}
@override
void dispose() {
if (hasListeners) {
_binding.removeObserver(this);
}
_refreshListenable?.removeListener(notifyListeners);
super.dispose();
}
@override
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
assert(hasListeners);
_platformReportsNewRouteInformation(routeInformation);
return SynchronousFuture<bool>(true);
}
@override
Future<bool> didPushRoute(String route) {
assert(hasListeners);
_platformReportsNewRouteInformation(RouteInformation(location: route));
return SynchronousFuture<bool>(true);
}
}
| packages/packages/go_router/lib/src/information_provider.dart/0 | {'file_path': 'packages/packages/go_router/lib/src/information_provider.dart', 'repo_id': 'packages', 'token_count': 2910} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
const String initialRoute = '/';
const String newRoute = '/new';
void main() {
group('GoRouteInformationProvider', () {
testWidgets('notifies its listeners when set by the app',
(WidgetTester tester) async {
late final GoRouteInformationProvider provider =
GoRouteInformationProvider(
initialLocation: initialRoute, initialExtra: null);
provider.addListener(expectAsync0(() {}));
provider.go(newRoute);
});
testWidgets('notifies its listeners when set by the platform',
(WidgetTester tester) async {
late final GoRouteInformationProvider provider =
GoRouteInformationProvider(
initialLocation: initialRoute, initialExtra: null);
provider.addListener(expectAsync0(() {}));
// TODO(chunhtai): remove this ignore and migrate the code
// https://github.com/flutter/flutter/issues/124045.
// ignore_for_file: deprecated_member_use
provider
.didPushRouteInformation(const RouteInformation(location: newRoute));
});
});
}
| packages/packages/go_router/test/information_provider_test.dart/0 | {'file_path': 'packages/packages/go_router/test/information_provider_test.dart', 'repo_id': 'packages', 'token_count': 470} |
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: always_specify_types, public_member_api_docs
part of 'all_types.dart';
// **************************************************************************
// GoRouterGenerator
// **************************************************************************
List<RouteBase> get $appRoutes => [
$allTypesBaseRoute,
];
RouteBase get $allTypesBaseRoute => GoRouteData.$route(
path: '/',
factory: $AllTypesBaseRouteExtension._fromState,
routes: [
GoRouteData.$route(
path: 'big-int-route/:requiredBigIntField',
factory: $BigIntRouteExtension._fromState,
),
GoRouteData.$route(
path: 'bool-route/:requiredBoolField',
factory: $BoolRouteExtension._fromState,
),
GoRouteData.$route(
path: 'date-time-route/:requiredDateTimeField',
factory: $DateTimeRouteExtension._fromState,
),
GoRouteData.$route(
path: 'double-route/:requiredDoubleField',
factory: $DoubleRouteExtension._fromState,
),
GoRouteData.$route(
path: 'int-route/:requiredIntField',
factory: $IntRouteExtension._fromState,
),
GoRouteData.$route(
path: 'num-route/:requiredNumField',
factory: $NumRouteExtension._fromState,
),
GoRouteData.$route(
path: 'double-route/:requiredDoubleField',
factory: $DoubleRouteExtension._fromState,
),
GoRouteData.$route(
path: 'enum-route/:requiredEnumField',
factory: $EnumRouteExtension._fromState,
),
GoRouteData.$route(
path: 'enhanced-enum-route/:requiredEnumField',
factory: $EnhancedEnumRouteExtension._fromState,
),
GoRouteData.$route(
path: 'string-route/:requiredStringField',
factory: $StringRouteExtension._fromState,
),
GoRouteData.$route(
path: 'uri-route/:requiredUriField',
factory: $UriRouteExtension._fromState,
),
GoRouteData.$route(
path: 'iterable-route',
factory: $IterableRouteExtension._fromState,
),
GoRouteData.$route(
path: 'iterable-route-with-default-values',
factory: $IterableRouteWithDefaultValuesExtension._fromState,
),
],
);
extension $AllTypesBaseRouteExtension on AllTypesBaseRoute {
static AllTypesBaseRoute _fromState(GoRouterState state) =>
const AllTypesBaseRoute();
String get location => GoRouteData.$location(
'/',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $BigIntRouteExtension on BigIntRoute {
static BigIntRoute _fromState(GoRouterState state) => BigIntRoute(
requiredBigIntField:
BigInt.parse(state.pathParameters['requiredBigIntField']!),
bigIntField: _$convertMapValue(
'big-int-field', state.uri.queryParameters, BigInt.parse),
);
String get location => GoRouteData.$location(
'/big-int-route/${Uri.encodeComponent(requiredBigIntField.toString())}',
queryParams: {
if (bigIntField != null) 'big-int-field': bigIntField!.toString(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $BoolRouteExtension on BoolRoute {
static BoolRoute _fromState(GoRouterState state) => BoolRoute(
requiredBoolField:
_$boolConverter(state.pathParameters['requiredBoolField']!),
boolField: _$convertMapValue(
'bool-field', state.uri.queryParameters, _$boolConverter),
boolFieldWithDefaultValue: _$convertMapValue(
'bool-field-with-default-value',
state.uri.queryParameters,
_$boolConverter) ??
true,
);
String get location => GoRouteData.$location(
'/bool-route/${Uri.encodeComponent(requiredBoolField.toString())}',
queryParams: {
if (boolField != null) 'bool-field': boolField!.toString(),
if (boolFieldWithDefaultValue != true)
'bool-field-with-default-value':
boolFieldWithDefaultValue.toString(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $DateTimeRouteExtension on DateTimeRoute {
static DateTimeRoute _fromState(GoRouterState state) => DateTimeRoute(
requiredDateTimeField:
DateTime.parse(state.pathParameters['requiredDateTimeField']!),
dateTimeField: _$convertMapValue(
'date-time-field', state.uri.queryParameters, DateTime.parse),
);
String get location => GoRouteData.$location(
'/date-time-route/${Uri.encodeComponent(requiredDateTimeField.toString())}',
queryParams: {
if (dateTimeField != null)
'date-time-field': dateTimeField!.toString(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $DoubleRouteExtension on DoubleRoute {
static DoubleRoute _fromState(GoRouterState state) => DoubleRoute(
requiredDoubleField:
double.parse(state.pathParameters['requiredDoubleField']!),
doubleField: _$convertMapValue(
'double-field', state.uri.queryParameters, double.parse),
doubleFieldWithDefaultValue: _$convertMapValue(
'double-field-with-default-value',
state.uri.queryParameters,
double.parse) ??
1.0,
);
String get location => GoRouteData.$location(
'/double-route/${Uri.encodeComponent(requiredDoubleField.toString())}',
queryParams: {
if (doubleField != null) 'double-field': doubleField!.toString(),
if (doubleFieldWithDefaultValue != 1.0)
'double-field-with-default-value':
doubleFieldWithDefaultValue.toString(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $IntRouteExtension on IntRoute {
static IntRoute _fromState(GoRouterState state) => IntRoute(
requiredIntField: int.parse(state.pathParameters['requiredIntField']!),
intField: _$convertMapValue(
'int-field', state.uri.queryParameters, int.parse),
intFieldWithDefaultValue: _$convertMapValue(
'int-field-with-default-value',
state.uri.queryParameters,
int.parse) ??
1,
);
String get location => GoRouteData.$location(
'/int-route/${Uri.encodeComponent(requiredIntField.toString())}',
queryParams: {
if (intField != null) 'int-field': intField!.toString(),
if (intFieldWithDefaultValue != 1)
'int-field-with-default-value': intFieldWithDefaultValue.toString(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $NumRouteExtension on NumRoute {
static NumRoute _fromState(GoRouterState state) => NumRoute(
requiredNumField: num.parse(state.pathParameters['requiredNumField']!),
numField: _$convertMapValue(
'num-field', state.uri.queryParameters, num.parse),
numFieldWithDefaultValue: _$convertMapValue(
'num-field-with-default-value',
state.uri.queryParameters,
num.parse) ??
1,
);
String get location => GoRouteData.$location(
'/num-route/${Uri.encodeComponent(requiredNumField.toString())}',
queryParams: {
if (numField != null) 'num-field': numField!.toString(),
if (numFieldWithDefaultValue != 1)
'num-field-with-default-value': numFieldWithDefaultValue.toString(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $EnumRouteExtension on EnumRoute {
static EnumRoute _fromState(GoRouterState state) => EnumRoute(
requiredEnumField: _$PersonDetailsEnumMap
._$fromName(state.pathParameters['requiredEnumField']!),
enumField: _$convertMapValue('enum-field', state.uri.queryParameters,
_$PersonDetailsEnumMap._$fromName),
enumFieldWithDefaultValue: _$convertMapValue(
'enum-field-with-default-value',
state.uri.queryParameters,
_$PersonDetailsEnumMap._$fromName) ??
PersonDetails.favoriteFood,
);
String get location => GoRouteData.$location(
'/enum-route/${Uri.encodeComponent(_$PersonDetailsEnumMap[requiredEnumField]!)}',
queryParams: {
if (enumField != null)
'enum-field': _$PersonDetailsEnumMap[enumField!],
if (enumFieldWithDefaultValue != PersonDetails.favoriteFood)
'enum-field-with-default-value':
_$PersonDetailsEnumMap[enumFieldWithDefaultValue],
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
const _$PersonDetailsEnumMap = {
PersonDetails.hobbies: 'hobbies',
PersonDetails.favoriteFood: 'favorite-food',
PersonDetails.favoriteSport: 'favorite-sport',
};
extension $EnhancedEnumRouteExtension on EnhancedEnumRoute {
static EnhancedEnumRoute _fromState(GoRouterState state) => EnhancedEnumRoute(
requiredEnumField: _$SportDetailsEnumMap
._$fromName(state.pathParameters['requiredEnumField']!),
enumField: _$convertMapValue('enum-field', state.uri.queryParameters,
_$SportDetailsEnumMap._$fromName),
enumFieldWithDefaultValue: _$convertMapValue(
'enum-field-with-default-value',
state.uri.queryParameters,
_$SportDetailsEnumMap._$fromName) ??
SportDetails.football,
);
String get location => GoRouteData.$location(
'/enhanced-enum-route/${Uri.encodeComponent(_$SportDetailsEnumMap[requiredEnumField]!)}',
queryParams: {
if (enumField != null)
'enum-field': _$SportDetailsEnumMap[enumField!],
if (enumFieldWithDefaultValue != SportDetails.football)
'enum-field-with-default-value':
_$SportDetailsEnumMap[enumFieldWithDefaultValue],
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
const _$SportDetailsEnumMap = {
SportDetails.volleyball: 'volleyball',
SportDetails.football: 'football',
SportDetails.tennis: 'tennis',
SportDetails.hockey: 'hockey',
};
extension $StringRouteExtension on StringRoute {
static StringRoute _fromState(GoRouterState state) => StringRoute(
requiredStringField: state.pathParameters['requiredStringField']!,
stringField: state.uri.queryParameters['string-field'],
stringFieldWithDefaultValue:
state.uri.queryParameters['string-field-with-default-value'] ??
'defaultValue',
);
String get location => GoRouteData.$location(
'/string-route/${Uri.encodeComponent(requiredStringField)}',
queryParams: {
if (stringField != null) 'string-field': stringField,
if (stringFieldWithDefaultValue != 'defaultValue')
'string-field-with-default-value': stringFieldWithDefaultValue,
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $UriRouteExtension on UriRoute {
static UriRoute _fromState(GoRouterState state) => UriRoute(
requiredUriField: Uri.parse(state.pathParameters['requiredUriField']!),
uriField: _$convertMapValue(
'uri-field', state.uri.queryParameters, Uri.parse),
);
String get location => GoRouteData.$location(
'/uri-route/${Uri.encodeComponent(requiredUriField.toString())}',
queryParams: {
if (uriField != null) 'uri-field': uriField!.toString(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $IterableRouteExtension on IterableRoute {
static IterableRoute _fromState(GoRouterState state) => IterableRoute(
intIterableField:
state.uri.queryParametersAll['int-iterable-field']?.map(int.parse),
doubleIterableField: state
.uri.queryParametersAll['double-iterable-field']
?.map(double.parse),
stringIterableField: state
.uri.queryParametersAll['string-iterable-field']
?.map((e) => e),
boolIterableField: state.uri.queryParametersAll['bool-iterable-field']
?.map(_$boolConverter),
enumIterableField: state.uri.queryParametersAll['enum-iterable-field']
?.map(_$SportDetailsEnumMap._$fromName),
enumOnlyInIterableField: state
.uri.queryParametersAll['enum-only-in-iterable-field']
?.map(_$CookingRecipeEnumMap._$fromName),
intListField: state.uri.queryParametersAll['int-list-field']
?.map(int.parse)
.toList(),
doubleListField: state.uri.queryParametersAll['double-list-field']
?.map(double.parse)
.toList(),
stringListField: state.uri.queryParametersAll['string-list-field']
?.map((e) => e)
.toList(),
boolListField: state.uri.queryParametersAll['bool-list-field']
?.map(_$boolConverter)
.toList(),
enumListField: state.uri.queryParametersAll['enum-list-field']
?.map(_$SportDetailsEnumMap._$fromName)
.toList(),
enumOnlyInListField: state
.uri.queryParametersAll['enum-only-in-list-field']
?.map(_$CookingRecipeEnumMap._$fromName)
.toList(),
intSetField: state.uri.queryParametersAll['int-set-field']
?.map(int.parse)
.toSet(),
doubleSetField: state.uri.queryParametersAll['double-set-field']
?.map(double.parse)
.toSet(),
stringSetField: state.uri.queryParametersAll['string-set-field']
?.map((e) => e)
.toSet(),
boolSetField: state.uri.queryParametersAll['bool-set-field']
?.map(_$boolConverter)
.toSet(),
enumSetField: state.uri.queryParametersAll['enum-set-field']
?.map(_$SportDetailsEnumMap._$fromName)
.toSet(),
enumOnlyInSetField: state
.uri.queryParametersAll['enum-only-in-set-field']
?.map(_$CookingRecipeEnumMap._$fromName)
.toSet(),
);
String get location => GoRouteData.$location(
'/iterable-route',
queryParams: {
if (intIterableField != null)
'int-iterable-field':
intIterableField?.map((e) => e.toString()).toList(),
if (doubleIterableField != null)
'double-iterable-field':
doubleIterableField?.map((e) => e.toString()).toList(),
if (stringIterableField != null)
'string-iterable-field':
stringIterableField?.map((e) => e).toList(),
if (boolIterableField != null)
'bool-iterable-field':
boolIterableField?.map((e) => e.toString()).toList(),
if (enumIterableField != null)
'enum-iterable-field': enumIterableField
?.map((e) => _$SportDetailsEnumMap[e])
.toList(),
if (enumOnlyInIterableField != null)
'enum-only-in-iterable-field': enumOnlyInIterableField
?.map((e) => _$CookingRecipeEnumMap[e])
.toList(),
if (intListField != null)
'int-list-field': intListField?.map((e) => e.toString()).toList(),
if (doubleListField != null)
'double-list-field':
doubleListField?.map((e) => e.toString()).toList(),
if (stringListField != null)
'string-list-field': stringListField?.map((e) => e).toList(),
if (boolListField != null)
'bool-list-field': boolListField?.map((e) => e.toString()).toList(),
if (enumListField != null)
'enum-list-field':
enumListField?.map((e) => _$SportDetailsEnumMap[e]).toList(),
if (enumOnlyInListField != null)
'enum-only-in-list-field': enumOnlyInListField
?.map((e) => _$CookingRecipeEnumMap[e])
.toList(),
if (intSetField != null)
'int-set-field': intSetField?.map((e) => e.toString()).toList(),
if (doubleSetField != null)
'double-set-field':
doubleSetField?.map((e) => e.toString()).toList(),
if (stringSetField != null)
'string-set-field': stringSetField?.map((e) => e).toList(),
if (boolSetField != null)
'bool-set-field': boolSetField?.map((e) => e.toString()).toList(),
if (enumSetField != null)
'enum-set-field':
enumSetField?.map((e) => _$SportDetailsEnumMap[e]).toList(),
if (enumOnlyInSetField != null)
'enum-only-in-set-field': enumOnlyInSetField
?.map((e) => _$CookingRecipeEnumMap[e])
.toList(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
const _$CookingRecipeEnumMap = {
CookingRecipe.burger: 'burger',
CookingRecipe.pizza: 'pizza',
CookingRecipe.tacos: 'tacos',
};
extension $IterableRouteWithDefaultValuesExtension
on IterableRouteWithDefaultValues {
static IterableRouteWithDefaultValues _fromState(GoRouterState state) =>
IterableRouteWithDefaultValues(
intIterableField: state.uri.queryParametersAll['int-iterable-field']
?.map(int.parse) ??
const <int>[0],
doubleIterableField: state
.uri.queryParametersAll['double-iterable-field']
?.map(double.parse) ??
const <double>[0, 1, 2],
stringIterableField: state
.uri.queryParametersAll['string-iterable-field']
?.map((e) => e) ??
const <String>['defaultValue'],
boolIterableField: state.uri.queryParametersAll['bool-iterable-field']
?.map(_$boolConverter) ??
const <bool>[false],
enumIterableField: state.uri.queryParametersAll['enum-iterable-field']
?.map(_$SportDetailsEnumMap._$fromName) ??
const <SportDetails>[SportDetails.tennis, SportDetails.hockey],
intListField: state.uri.queryParametersAll['int-list-field']
?.map(int.parse)
.toList() ??
const <int>[0],
doubleListField: state.uri.queryParametersAll['double-list-field']
?.map(double.parse)
.toList() ??
const <double>[1, 2, 3],
stringListField: state.uri.queryParametersAll['string-list-field']
?.map((e) => e)
.toList() ??
const <String>['defaultValue0', 'defaultValue1'],
boolListField: state.uri.queryParametersAll['bool-list-field']
?.map(_$boolConverter)
.toList() ??
const <bool>[true],
enumListField: state.uri.queryParametersAll['enum-list-field']
?.map(_$SportDetailsEnumMap._$fromName)
.toList() ??
const <SportDetails>[SportDetails.football],
intSetField: state.uri.queryParametersAll['int-set-field']
?.map(int.parse)
.toSet() ??
const <int>{0, 1},
doubleSetField: state.uri.queryParametersAll['double-set-field']
?.map(double.parse)
.toSet() ??
const <double>{},
stringSetField: state.uri.queryParametersAll['string-set-field']
?.map((e) => e)
.toSet() ??
const <String>{'defaultValue'},
boolSetField: state.uri.queryParametersAll['bool-set-field']
?.map(_$boolConverter)
.toSet() ??
const <bool>{true, false},
enumSetField: state.uri.queryParametersAll['enum-set-field']
?.map(_$SportDetailsEnumMap._$fromName)
.toSet() ??
const <SportDetails>{SportDetails.hockey},
);
String get location => GoRouteData.$location(
'/iterable-route-with-default-values',
queryParams: {
if (intIterableField != const <int>[0])
'int-iterable-field':
intIterableField.map((e) => e.toString()).toList(),
if (doubleIterableField != const <double>[0, 1, 2])
'double-iterable-field':
doubleIterableField.map((e) => e.toString()).toList(),
if (stringIterableField != const <String>['defaultValue'])
'string-iterable-field': stringIterableField.map((e) => e).toList(),
if (boolIterableField != const <bool>[false])
'bool-iterable-field':
boolIterableField.map((e) => e.toString()).toList(),
if (enumIterableField !=
const <SportDetails>[SportDetails.tennis, SportDetails.hockey])
'enum-iterable-field':
enumIterableField.map((e) => _$SportDetailsEnumMap[e]).toList(),
if (intListField != const <int>[0])
'int-list-field': intListField.map((e) => e.toString()).toList(),
if (doubleListField != const <double>[1, 2, 3])
'double-list-field':
doubleListField.map((e) => e.toString()).toList(),
if (stringListField !=
const <String>['defaultValue0', 'defaultValue1'])
'string-list-field': stringListField.map((e) => e).toList(),
if (boolListField != const <bool>[true])
'bool-list-field': boolListField.map((e) => e.toString()).toList(),
if (enumListField != const <SportDetails>[SportDetails.football])
'enum-list-field':
enumListField.map((e) => _$SportDetailsEnumMap[e]).toList(),
if (intSetField != const <int>{0, 1})
'int-set-field': intSetField.map((e) => e.toString()).toList(),
if (doubleSetField != const <double>{})
'double-set-field':
doubleSetField.map((e) => e.toString()).toList(),
if (stringSetField != const <String>{'defaultValue'})
'string-set-field': stringSetField.map((e) => e).toList(),
if (boolSetField != const <bool>{true, false})
'bool-set-field': boolSetField.map((e) => e.toString()).toList(),
if (enumSetField != const <SportDetails>{SportDetails.hockey})
'enum-set-field':
enumSetField.map((e) => _$SportDetailsEnumMap[e]).toList(),
},
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
T? _$convertMapValue<T>(
String key,
Map<String, String> map,
T Function(String) converter,
) {
final value = map[key];
return value == null ? null : converter(value);
}
bool _$boolConverter(String value) {
switch (value) {
case 'true':
return true;
case 'false':
return false;
default:
throw UnsupportedError('Cannot convert "$value" into a bool.');
}
}
extension<T extends Enum> on Map<T, String> {
T _$fromName(String value) =>
entries.singleWhere((element) => element.value == value).key;
}
| packages/packages/go_router_builder/example/lib/all_types.g.dart/0 | {'file_path': 'packages/packages/go_router_builder/example/lib/all_types.g.dart', 'repo_id': 'packages', 'token_count': 11246} |
// 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, unreachable_from_main
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
part 'stateful_shell_route_initial_location_example.g.dart';
void main() => runApp(App());
class App extends StatelessWidget {
App({super.key});
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
);
final GoRouter _router = GoRouter(
routes: $appRoutes,
initialLocation: '/home',
);
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('foo')),
);
}
@TypedStatefulShellRoute<MainShellRouteData>(
branches: <TypedStatefulShellBranch<StatefulShellBranchData>>[
TypedStatefulShellBranch<HomeShellBranchData>(
routes: <TypedRoute<RouteData>>[
TypedGoRoute<HomeRouteData>(
path: '/home',
),
],
),
TypedStatefulShellBranch<NotificationsShellBranchData>(
routes: <TypedRoute<RouteData>>[
TypedGoRoute<NotificationsRouteData>(
path: '/notifications/:section',
),
],
),
TypedStatefulShellBranch<OrdersShellBranchData>(
routes: <TypedRoute<RouteData>>[
TypedGoRoute<OrdersRouteData>(
path: '/orders',
),
],
),
],
)
class MainShellRouteData extends StatefulShellRouteData {
const MainShellRouteData();
@override
Widget builder(
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigationShell,
) {
return MainPageView(
navigationShell: navigationShell,
);
}
}
class HomeShellBranchData extends StatefulShellBranchData {
const HomeShellBranchData();
}
class NotificationsShellBranchData extends StatefulShellBranchData {
const NotificationsShellBranchData();
static String $initialLocation = '/notifications/old';
}
class OrdersShellBranchData extends StatefulShellBranchData {
const OrdersShellBranchData();
}
class HomeRouteData extends GoRouteData {
const HomeRouteData();
@override
Widget build(BuildContext context, GoRouterState state) {
return const HomePageView(label: 'Home page');
}
}
enum NotificationsPageSection {
latest,
old,
archive,
}
class NotificationsRouteData extends GoRouteData {
const NotificationsRouteData({
required this.section,
});
final NotificationsPageSection section;
@override
Widget build(BuildContext context, GoRouterState state) {
return NotificationsPageView(
section: section,
);
}
}
class OrdersRouteData extends GoRouteData {
const OrdersRouteData();
@override
Widget build(BuildContext context, GoRouterState state) {
return const OrdersPageView(label: 'Orders page');
}
}
class MainPageView extends StatelessWidget {
const MainPageView({
required this.navigationShell,
super.key,
});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: navigationShell,
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
label: 'Notifications',
),
BottomNavigationBarItem(
icon: Icon(Icons.list),
label: 'Orders',
),
],
currentIndex: navigationShell.currentIndex,
onTap: (int index) => _onTap(context, index),
),
);
}
void _onTap(BuildContext context, int index) {
navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
);
}
}
class HomePageView extends StatelessWidget {
const HomePageView({
required this.label,
super.key,
});
final String label;
@override
Widget build(BuildContext context) {
return Center(
child: Text(label),
);
}
}
class NotificationsPageView extends StatelessWidget {
const NotificationsPageView({
super.key,
required this.section,
});
final NotificationsPageSection section;
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
initialIndex: NotificationsPageSection.values.indexOf(section),
child: const Column(
children: <Widget>[
TabBar(
tabs: <Tab>[
Tab(
child: Text(
'Latest',
style: TextStyle(color: Colors.black87),
),
),
Tab(
child: Text(
'Old',
style: TextStyle(color: Colors.black87),
),
),
Tab(
child: Text(
'Archive',
style: TextStyle(color: Colors.black87),
),
),
],
),
Expanded(
child: TabBarView(
children: <Widget>[
NotificationsSubPageView(
label: 'Latest notifications',
),
NotificationsSubPageView(
label: 'Old notifications',
),
NotificationsSubPageView(
label: 'Archived notifications',
),
],
),
),
],
),
);
}
}
class NotificationsSubPageView extends StatelessWidget {
const NotificationsSubPageView({
required this.label,
super.key,
});
final String label;
@override
Widget build(BuildContext context) {
return Center(
child: Text(label),
);
}
}
class OrdersPageView extends StatelessWidget {
const OrdersPageView({
required this.label,
super.key,
});
final String label;
@override
Widget build(BuildContext context) {
return Center(
child: Text(label),
);
}
}
| packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart/0 | {'file_path': 'packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart', 'repo_id': 'packages', 'token_count': 2620} |
// 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:go_router/go_router.dart';
@TypedShellRoute<ShellRouteNoConstConstructor>(
routes: <TypedRoute<RouteData>>[],
)
class ShellRouteNoConstConstructor extends ShellRouteData {}
@TypedShellRoute<ShellRouteWithConstConstructor>(
routes: <TypedRoute<RouteData>>[],
)
class ShellRouteWithConstConstructor extends ShellRouteData {
const ShellRouteWithConstConstructor();
}
| packages/packages/go_router_builder/test_inputs/shell_route_data.dart/0 | {'file_path': 'packages/packages/go_router_builder/test_inputs/shell_route_data.dart', 'repo_id': 'packages', 'token_count': 160} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('browser') // Uses package:web
library;
import 'dart:async';
import 'dart:js_interop';
import 'package:google_identity_services_web/loader.dart';
import 'package:google_identity_services_web/src/js_loader.dart';
import 'package:test/test.dart';
import 'package:web/web.dart' as web;
// NOTE: This file needs to be separated from the others because Content
// Security Policies can never be *relaxed* once set.
//
// In order to not introduce a dependency in the order of the tests, we split
// them in different files, depending on the strictness of their CSP:
//
// * js_loader_test.dart : default TT configuration (not enforced)
// * js_loader_tt_custom_test.dart : TT are customized, but allowed
// * js_loader_tt_forbidden_test.dart: TT are completely disallowed
void main() {
group('loadWebSdk (no TrustedTypes)', () {
final web.HTMLDivElement target =
web.document.createElement('div') as web.HTMLDivElement;
test('Injects script into desired target', () async {
// This test doesn't simulate the callback that completes the future, and
// the code being tested runs synchronously.
unawaited(loadWebSdk(target: target));
// Target now should have a child that is a script element
final web.Node? injected = target.firstChild;
expect(injected, isNotNull);
expect(injected, isA<web.HTMLScriptElement>());
final web.HTMLScriptElement script = injected! as web.HTMLScriptElement;
expect(script.defer, isTrue);
expect(script.async, isTrue);
expect(script.src, 'https://accounts.google.com/gsi/client');
});
test('Completes when the script loads', () async {
final Future<void> loadFuture = loadWebSdk(target: target);
Future<void>.delayed(const Duration(milliseconds: 100), () {
// Simulate the library calling `window.onGoogleLibraryLoad`.
web.window.onGoogleLibraryLoad();
});
await expectLater(loadFuture, completes);
});
});
}
extension on web.Window {
void onGoogleLibraryLoad() => _onGoogleLibraryLoad();
@JS('onGoogleLibraryLoad')
external JSFunction? _onGoogleLibraryLoad();
}
| packages/packages/google_identity_services_web/test/js_loader_test.dart/0 | {'file_path': 'packages/packages/google_identity_services_web/test/js_loader_test.dart', 'repo_id': 'packages', 'token_count': 753} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'main.dart';
import 'page.dart';
class MapIdPage extends GoogleMapExampleAppPage {
const MapIdPage({Key? key})
: super(const Icon(Icons.map), 'Cloud-based maps styling', key: key);
@override
Widget build(BuildContext context) {
return const MapIdBody();
}
}
class MapIdBody extends StatefulWidget {
const MapIdBody({super.key});
@override
State<StatefulWidget> createState() => MapIdBodyState();
}
const LatLng _kMapCenter = LatLng(52.4478, -3.5402);
class MapIdBodyState extends State<MapIdBody> {
GoogleMapController? controller;
Key _key = const Key('mapId#');
String? _mapId;
final TextEditingController _mapIdController = TextEditingController();
AndroidMapRenderer? _initializedRenderer;
@override
void initState() {
initializeMapRenderer()
.then<void>((AndroidMapRenderer? initializedRenderer) => setState(() {
_initializedRenderer = initializedRenderer;
}));
super.initState();
}
String _getInitializedsRendererType() {
switch (_initializedRenderer) {
case AndroidMapRenderer.latest:
return 'latest';
case AndroidMapRenderer.legacy:
return 'legacy';
case AndroidMapRenderer.platformDefault:
case null:
break;
}
return 'unknown';
}
void _setMapId() {
setState(() {
_mapId = _mapIdController.text;
// Change key to initialize new map instance for new mapId.
_key = Key(_mapId ?? 'mapId#');
});
}
@override
Widget build(BuildContext context) {
final GoogleMap googleMap = GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: _kMapCenter,
zoom: 7.0,
),
key: _key,
cloudMapId: _mapId);
final List<Widget> columnChildren = <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: googleMap,
),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: _mapIdController,
decoration: const InputDecoration(
hintText: 'Map Id',
),
)),
Padding(
padding: const EdgeInsets.all(10.0),
child: ElevatedButton(
onPressed: () => _setMapId(),
child: const Text(
'Press to use specified map Id',
),
)),
if (!kIsWeb &&
Platform.isAndroid &&
_initializedRenderer != AndroidMapRenderer.latest)
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'On Android, Cloud-based maps styling only works with "latest" renderer.\n\n'
'Current initialized renderer is "${_getInitializedsRendererType()}".'),
),
];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: columnChildren,
);
}
@override
void dispose() {
_mapIdController.dispose();
super.dispose();
}
void _onMapCreated(GoogleMapController controllerParam) {
setState(() {
controller = controllerParam;
});
}
}
| packages/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart', 'repo_id': 'packages', 'token_count': 1567} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'fake_google_maps_flutter_platform.dart';
Widget _mapWithPolygons(Set<Polygon> polygons) {
return Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
polygons: polygons,
),
);
}
List<LatLng> _rectPoints({
required double size,
LatLng center = const LatLng(0, 0),
}) {
final double halfSize = size / 2;
return <LatLng>[
LatLng(center.latitude + halfSize, center.longitude + halfSize),
LatLng(center.latitude - halfSize, center.longitude + halfSize),
LatLng(center.latitude - halfSize, center.longitude - halfSize),
LatLng(center.latitude + halfSize, center.longitude - halfSize),
];
}
Polygon _polygonWithPointsAndHole(PolygonId polygonId) {
_rectPoints(size: 1);
return Polygon(
polygonId: polygonId,
points: _rectPoints(size: 1),
holes: <List<LatLng>>[_rectPoints(size: 0.5)],
);
}
void main() {
late FakeGoogleMapsFlutterPlatform platform;
setUp(() {
platform = FakeGoogleMapsFlutterPlatform();
GoogleMapsFlutterPlatform.instance = platform;
});
testWidgets('Initializing a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToAdd.length, 1);
final Polygon initializedPolygon =
map.polygonUpdates.last.polygonsToAdd.first;
expect(initializedPolygon, equals(p1));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true);
});
testWidgets('Adding a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToAdd.length, 1);
final Polygon addedPolygon = map.polygonUpdates.last.polygonsToAdd.first;
expect(addedPolygon, equals(p2));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true);
});
testWidgets('Removing a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1);
expect(
map.polygonUpdates.last.polygonIdsToRemove.first, equals(p1.polygonId));
expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Updating a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 =
Polygon(polygonId: PolygonId('polygon_1'), geodesic: true);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange.length, 1);
expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Mutate a polygon', (WidgetTester tester) async {
final List<LatLng> points = <LatLng>[const LatLng(0.0, 0.0)];
final Polygon p1 = Polygon(
polygonId: const PolygonId('polygon_1'),
points: points,
);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
p1.points.add(const LatLng(1.0, 1.0));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange.length, 1);
expect(map.polygonUpdates.last.polygonsToChange.first, equals(p1));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1'));
Polygon p2 = const Polygon(polygonId: PolygonId('polygon_2'));
final Set<Polygon> prev = <Polygon>{p1, p2};
p1 = const Polygon(polygonId: PolygonId('polygon_1'), visible: false);
p2 = const Polygon(polygonId: PolygonId('polygon_2'), geodesic: true);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange, cur);
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Polygon p2 = const Polygon(polygonId: PolygonId('polygon_2'));
const Polygon p3 = Polygon(polygonId: PolygonId('polygon_3'));
final Set<Polygon> prev = <Polygon>{p2, p3};
// p1 is added, p2 is updated, p3 is removed.
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
p2 = const Polygon(polygonId: PolygonId('polygon_2'), geodesic: true);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange.length, 1);
expect(map.polygonUpdates.last.polygonsToAdd.length, 1);
expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1);
expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2));
expect(map.polygonUpdates.last.polygonsToAdd.first, equals(p1));
expect(
map.polygonUpdates.last.polygonIdsToRemove.first, equals(p3.polygonId));
});
testWidgets('Partial Update', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
Polygon p3 = const Polygon(polygonId: PolygonId('polygon_3'));
final Set<Polygon> prev = <Polygon>{p1, p2, p3};
p3 = const Polygon(polygonId: PolygonId('polygon_3'), geodesic: true);
final Set<Polygon> cur = <Polygon>{p1, p2, p3};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange, <Polygon>{p3});
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Update non platform related attr', (WidgetTester tester) async {
Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1'));
final Set<Polygon> prev = <Polygon>{p1};
p1 = Polygon(polygonId: const PolygonId('polygon_1'), onTap: () {});
final Set<Polygon> cur = <Polygon>{p1};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true);
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Initializing a polygon with points and hole',
(WidgetTester tester) async {
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToAdd.length, 1);
final Polygon initializedPolygon =
map.polygonUpdates.last.polygonsToAdd.first;
expect(initializedPolygon, equals(p1));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true);
});
testWidgets('Adding a polygon with points and hole',
(WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_2'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToAdd.length, 1);
final Polygon addedPolygon = map.polygonUpdates.last.polygonsToAdd.first;
expect(addedPolygon, equals(p2));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true);
});
testWidgets('Removing a polygon with points and hole',
(WidgetTester tester) async {
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1);
expect(
map.polygonUpdates.last.polygonIdsToRemove.first, equals(p1.polygonId));
expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Updating a polygon by adding points and hole',
(WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p2}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange.length, 1);
expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Mutate a polygon with points and holes',
(WidgetTester tester) async {
final Polygon p1 = Polygon(
polygonId: const PolygonId('polygon_1'),
points: _rectPoints(size: 1),
holes: <List<LatLng>>[_rectPoints(size: 0.5)],
);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
p1.points
..clear()
..addAll(_rectPoints(size: 2));
p1.holes
..clear()
..addAll(<List<LatLng>>[_rectPoints(size: 1)]);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange.length, 1);
expect(map.polygonUpdates.last.polygonsToChange.first, equals(p1));
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update polygons with points and hole',
(WidgetTester tester) async {
Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1'));
Polygon p2 = Polygon(
polygonId: const PolygonId('polygon_2'),
points: _rectPoints(size: 2),
holes: <List<LatLng>>[_rectPoints(size: 1)],
);
final Set<Polygon> prev = <Polygon>{p1, p2};
p1 = const Polygon(polygonId: PolygonId('polygon_1'), visible: false);
p2 = p2.copyWith(
pointsParam: _rectPoints(size: 5),
holesParam: <List<LatLng>>[_rectPoints(size: 2)],
);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange, cur);
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update polygons with points and hole',
(WidgetTester tester) async {
Polygon p2 = Polygon(
polygonId: const PolygonId('polygon_2'),
points: _rectPoints(size: 2),
holes: <List<LatLng>>[_rectPoints(size: 1)],
);
const Polygon p3 = Polygon(polygonId: PolygonId('polygon_3'));
final Set<Polygon> prev = <Polygon>{p2, p3};
// p1 is added, p2 is updated, p3 is removed.
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
p2 = p2.copyWith(
pointsParam: _rectPoints(size: 5),
holesParam: <List<LatLng>>[_rectPoints(size: 3)],
);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange.length, 1);
expect(map.polygonUpdates.last.polygonsToAdd.length, 1);
expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1);
expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2));
expect(map.polygonUpdates.last.polygonsToAdd.first, equals(p1));
expect(
map.polygonUpdates.last.polygonIdsToRemove.first, equals(p3.polygonId));
});
testWidgets('Partial Update polygons with points and hole',
(WidgetTester tester) async {
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
Polygon p3 = Polygon(
polygonId: const PolygonId('polygon_3'),
points: _rectPoints(size: 2),
holes: <List<LatLng>>[_rectPoints(size: 1)],
);
final Set<Polygon> prev = <Polygon>{p1, p2, p3};
p3 = p3.copyWith(
pointsParam: _rectPoints(size: 5),
holesParam: <List<LatLng>>[_rectPoints(size: 3)],
);
final Set<Polygon> cur = <Polygon>{p1, p2, p3};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.last.polygonsToChange, <Polygon>{p3});
expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true);
});
testWidgets('multi-update with delays', (WidgetTester tester) async {
platform.simulatePlatformDelay = true;
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
const Polygon p3 =
Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1);
const Polygon p3updated =
Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2);
// First remove one and add another, then update the new one.
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p3}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p3updated}));
final PlatformMapStateRecorder map = platform.lastCreatedMap;
expect(map.polygonUpdates.length, 3);
expect(map.polygonUpdates[0].polygonsToChange.isEmpty, true);
expect(map.polygonUpdates[0].polygonsToAdd, <Polygon>{p1, p2});
expect(map.polygonUpdates[0].polygonIdsToRemove.isEmpty, true);
expect(map.polygonUpdates[1].polygonsToChange.isEmpty, true);
expect(map.polygonUpdates[1].polygonsToAdd, <Polygon>{p3});
expect(map.polygonUpdates[1].polygonIdsToRemove, <PolygonId>{p2.polygonId});
expect(map.polygonUpdates[2].polygonsToChange, <Polygon>{p3updated});
expect(map.polygonUpdates[2].polygonsToAdd.isEmpty, true);
expect(map.polygonUpdates[2].polygonIdsToRemove.isEmpty, true);
await tester.pumpAndSettle();
});
}
| packages/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart', 'repo_id': 'packages', 'token_count': 6557} |
// 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:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:integration_test/integration_test.dart';
import 'google_maps_tests.dart' show googleMapsTests;
void main() {
late AndroidMapRenderer initializedRenderer;
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
final GoogleMapsFlutterAndroid instance =
GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid;
initializedRenderer =
await instance.initializeWithRenderer(AndroidMapRenderer.legacy);
});
testWidgets('initialized with legacy renderer', (WidgetTester _) async {
expect(initializedRenderer, AndroidMapRenderer.legacy);
});
testWidgets('throws PlatformException on multiple renderer initializations',
(WidgetTester _) async {
final GoogleMapsFlutterAndroid instance =
GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid;
expect(
() async => instance.initializeWithRenderer(AndroidMapRenderer.legacy),
throwsA(isA<PlatformException>().having((PlatformException e) => e.code,
'code', 'Renderer already initialized')));
});
// Run tests.
googleMapsTests();
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/legacy_renderer_test.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/legacy_renderer_test.dart', 'repo_id': 'packages', 'token_count': 499} |
// 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:plugin_platform_interface/plugin_platform_interface.dart';
import '../../google_maps_flutter_platform_interface.dart';
/// The interface that platform-specific implementations of
/// `google_maps_flutter` can extend to support state inpsection in tests.
///
/// Avoid `implements` of this interface. Using `implements` makes adding any
/// new methods here a breaking change for end users of your platform!
///
/// Do `extends GoogleMapsInspectorPlatform` instead, so new methods
/// added here are inherited in your code with the default implementation (that
/// throws at runtime), rather than breaking your users at compile time.
abstract class GoogleMapsInspectorPlatform extends PlatformInterface {
/// Constructs a GoogleMapsFlutterPlatform.
GoogleMapsInspectorPlatform() : super(token: _token);
static final Object _token = Object();
static GoogleMapsInspectorPlatform? _instance;
/// The instance of [GoogleMapsInspectorPlatform], if any.
///
/// This is usually populated by calling
/// [GoogleMapsFlutterPlatform.enableDebugInspection].
static GoogleMapsInspectorPlatform? get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [GoogleMapsInspectorPlatform] in their
/// implementation of [GoogleMapsFlutterPlatform.enableDebugInspection].
static set instance(GoogleMapsInspectorPlatform? instance) {
if (instance != null) {
PlatformInterface.verify(instance, _token);
}
_instance = instance;
}
/// Returns the minimum and maxmimum zoom level settings.
Future<MinMaxZoomPreference> getMinMaxZoomLevels({required int mapId}) {
throw UnimplementedError('getMinMaxZoomLevels() has not been implemented.');
}
/// Returns true if the compass is enabled.
Future<bool> isCompassEnabled({required int mapId}) {
throw UnimplementedError('isCompassEnabled() has not been implemented.');
}
/// Returns true if lite mode is enabled.
Future<bool> isLiteModeEnabled({required int mapId}) {
throw UnimplementedError('isLiteModeEnabled() has not been implemented.');
}
/// Returns true if the map toolbar is enabled.
Future<bool> isMapToolbarEnabled({required int mapId}) {
throw UnimplementedError('isMapToolbarEnabled() has not been implemented.');
}
/// Returns true if the "my location" button is enabled.
Future<bool> isMyLocationButtonEnabled({required int mapId}) {
throw UnimplementedError(
'isMyLocationButtonEnabled() has not been implemented.');
}
/// Returns true if the traffic overlay is enabled.
Future<bool> isTrafficEnabled({required int mapId}) {
throw UnimplementedError('isTrafficEnabled() has not been implemented.');
}
/// Returns true if the building layer is enabled.
Future<bool> areBuildingsEnabled({required int mapId}) {
throw UnimplementedError('areBuildingsEnabled() has not been implemented.');
}
/// Returns true if rotate gestures are enabled.
Future<bool> areRotateGesturesEnabled({required int mapId}) {
throw UnimplementedError(
'areRotateGesturesEnabled() has not been implemented.');
}
/// Returns true if scroll gestures are enabled.
Future<bool> areScrollGesturesEnabled({required int mapId}) {
throw UnimplementedError(
'areScrollGesturesEnabled() has not been implemented.');
}
/// Returns true if tilt gestures are enabled.
Future<bool> areTiltGesturesEnabled({required int mapId}) {
throw UnimplementedError(
'areTiltGesturesEnabled() has not been implemented.');
}
/// Returns true if zoom controls are enabled.
Future<bool> areZoomControlsEnabled({required int mapId}) {
throw UnimplementedError(
'areZoomControlsEnabled() has not been implemented.');
}
/// Returns true if zoom gestures are enabled.
Future<bool> areZoomGesturesEnabled({required int mapId}) {
throw UnimplementedError(
'areZoomGesturesEnabled() has not been implemented.');
}
/// Returns information about the tile overlay with the given ID.
///
/// The returned object will be synthesized from platform data, so will not
/// be the same Dart object as the original [TileOverlay] provided to the
/// platform interface with that ID, and not all fields (e.g.,
/// [TileOverlay.tileProvider]) will be populated.
Future<TileOverlay?> getTileOverlayInfo(TileOverlayId tileOverlayId,
{required int mapId}) {
throw UnimplementedError('getTileOverlayInfo() has not been implemented.');
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart', 'repo_id': 'packages', 'token_count': 1333} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
class _TestTileProvider extends TileProvider {
@override
Future<Tile> getTile(int x, int y, int? zoom) async {
return const Tile(0, 0, null);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('tile overlay id tests', () {
test('equality', () async {
const TileOverlayId id1 = TileOverlayId('1');
const TileOverlayId id2 = TileOverlayId('1');
const TileOverlayId id3 = TileOverlayId('2');
expect(id1, id2);
expect(id1, isNot(id3));
});
test('toString', () async {
const TileOverlayId id1 = TileOverlayId('1');
expect(id1.toString(), 'TileOverlayId(1)');
});
});
group('tile overlay tests', () {
test('toJson returns correct format', () async {
const TileOverlay tileOverlay = TileOverlay(
tileOverlayId: TileOverlayId('id'),
fadeIn: false,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
final Object json = tileOverlay.toJson();
expect(json, <String, Object>{
'tileOverlayId': 'id',
'fadeIn': false,
'transparency': moreOrLessEquals(0.1),
'zIndex': 1,
'visible': false,
'tileSize': 128,
});
});
test('invalid transparency throws', () async {
expect(
() => TileOverlay(
tileOverlayId: const TileOverlayId('id1'), transparency: -0.1),
throwsAssertionError);
expect(
() => TileOverlay(
tileOverlayId: const TileOverlayId('id2'), transparency: 1.2),
throwsAssertionError);
});
test('equality', () async {
final TileProvider tileProvider = _TestTileProvider();
final TileOverlay tileOverlay1 = TileOverlay(
tileOverlayId: const TileOverlayId('id1'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
final TileOverlay tileOverlaySameValues = TileOverlay(
tileOverlayId: const TileOverlayId('id1'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
final TileOverlay tileOverlayDifferentId = TileOverlay(
tileOverlayId: const TileOverlayId('id2'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
const TileOverlay tileOverlayDifferentProvider = TileOverlay(
tileOverlayId: TileOverlayId('id1'),
fadeIn: false,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
expect(tileOverlay1, tileOverlaySameValues);
expect(tileOverlay1, isNot(tileOverlayDifferentId));
expect(tileOverlay1, isNot(tileOverlayDifferentProvider));
});
test('clone', () async {
final TileProvider tileProvider = _TestTileProvider();
// Set non-default values for every parameter.
final TileOverlay tileOverlay = TileOverlay(
tileOverlayId: const TileOverlayId('id1'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
expect(tileOverlay, tileOverlay.clone());
});
test('hashCode', () async {
final TileProvider tileProvider = _TestTileProvider();
const TileOverlayId id = TileOverlayId('id1');
final TileOverlay tileOverlay = TileOverlay(
tileOverlayId: id,
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
expect(
tileOverlay.hashCode,
Object.hash(
tileOverlay.tileOverlayId,
tileOverlay.fadeIn,
tileOverlay.tileProvider,
tileOverlay.transparency,
tileOverlay.zIndex,
tileOverlay.visible,
tileOverlay.tileSize));
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart', 'repo_id': 'packages', 'token_count': 1994} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:html' as html;
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart';
import 'package:integration_test/integration_test.dart';
import 'resources/tile16_base64.dart';
class NoTileProvider implements TileProvider {
const NoTileProvider();
@override
Future<Tile> getTile(int x, int y, int? zoom) async => TileProvider.noTile;
}
class TestTileProvider implements TileProvider {
const TestTileProvider();
@override
Future<Tile> getTile(int x, int y, int? zoom) async =>
Tile(16, 16, const Base64Decoder().convert(tile16Base64));
}
/// Test Overlays
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('TileOverlayController', () {
const TileOverlayId id = TileOverlayId('');
testWidgets('minimal initialization', (WidgetTester tester) async {
final TileOverlayController controller = TileOverlayController(
tileOverlay: const TileOverlay(tileOverlayId: id),
);
final gmaps.Size size = controller.gmMapType.tileSize!;
expect(size.width, TileOverlayController.logicalTileSize);
expect(size.height, TileOverlayController.logicalTileSize);
expect(controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, html.document),
null);
});
testWidgets('produces image tiles', (WidgetTester tester) async {
final TileOverlayController controller = TileOverlayController(
tileOverlay: const TileOverlay(
tileOverlayId: id,
tileProvider: TestTileProvider(),
),
);
final html.ImageElement img =
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, html.document)!
as html.ImageElement;
expect(img.naturalWidth, 0);
expect(img.naturalHeight, 0);
expect(img.hidden, true);
// Wait until the image is fully loaded and decoded before re-reading its attributes.
await img.onLoad.first;
await img.decode();
expect(img.hidden, false);
expect(img.naturalWidth, 16);
expect(img.naturalHeight, 16);
});
testWidgets('update', (WidgetTester tester) async {
final TileOverlayController controller = TileOverlayController(
tileOverlay: const TileOverlay(
tileOverlayId: id,
tileProvider: NoTileProvider(),
),
);
{
final html.ImageElement img =
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, html.document)!
as html.ImageElement;
await null; // let `getTile` `then` complete
expect(
img.src,
isEmpty,
reason: 'The NoTileProvider never updates the img src',
);
}
controller.update(const TileOverlay(
tileOverlayId: id,
tileProvider: TestTileProvider(),
));
{
final html.ImageElement img =
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, html.document)!
as html.ImageElement;
await img.onLoad.first;
expect(
img.src,
isNotEmpty,
reason: 'The img `src` should eventually become the Blob URL.',
);
}
controller.update(const TileOverlay(tileOverlayId: id));
{
expect(
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, html.document),
null,
reason: 'Setting a null tileProvider should work.',
);
}
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart/0 | {'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart', 'repo_id': 'packages', 'token_count': 1523} |
// 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:google_sign_in_ios/google_sign_in_ios.dart';
import 'package:google_sign_in_ios/src/messages.g.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'google_sign_in_ios_test.mocks.dart';
final GoogleSignInUserData _user = GoogleSignInUserData(
email: 'john.doe@gmail.com',
id: '8162538176523816253123',
photoUrl: 'https://lh5.googleusercontent.com/photo.jpg',
displayName: 'John Doe',
serverAuthCode: '789',
idToken: '123');
final GoogleSignInTokenData _token = GoogleSignInTokenData(
idToken: '123',
accessToken: '456',
);
@GenerateMocks(<Type>[GoogleSignInApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late GoogleSignInIOS googleSignIn;
late MockGoogleSignInApi api;
setUp(() {
api = MockGoogleSignInApi();
googleSignIn = GoogleSignInIOS(api: api);
});
test('registered instance', () {
GoogleSignInIOS.registerWith();
expect(GoogleSignInPlatform.instance, isA<GoogleSignInIOS>());
});
test('init throws for SignInOptions.games', () async {
expect(
() => googleSignIn.init(
hostedDomain: 'example.com',
signInOption: SignInOption.games,
clientId: 'fakeClientId'),
throwsA(isInstanceOf<PlatformException>().having(
(PlatformException e) => e.code, 'code', 'unsupported-options')));
});
test('signInSilently transforms platform data to GoogleSignInUserData',
() async {
when(api.signInSilently()).thenAnswer((_) async => UserData(
email: _user.email,
userId: _user.id,
photoUrl: _user.photoUrl,
displayName: _user.displayName,
serverAuthCode: _user.serverAuthCode,
idToken: _user.idToken,
));
final dynamic response = await googleSignIn.signInSilently();
expect(response, _user);
});
test('signInSilently Exceptions -> throws', () async {
when(api.signInSilently())
.thenAnswer((_) async => throw PlatformException(code: 'fail'));
expect(googleSignIn.signInSilently(),
throwsA(isInstanceOf<PlatformException>()));
});
test('signIn transforms platform data to GoogleSignInUserData', () async {
when(api.signIn()).thenAnswer((_) async => UserData(
email: _user.email,
userId: _user.id,
photoUrl: _user.photoUrl,
displayName: _user.displayName,
serverAuthCode: _user.serverAuthCode,
idToken: _user.idToken,
));
final dynamic response = await googleSignIn.signIn();
expect(response, _user);
});
test('signIn Exceptions -> throws', () async {
when(api.signIn())
.thenAnswer((_) async => throw PlatformException(code: 'fail'));
expect(googleSignIn.signIn(), throwsA(isInstanceOf<PlatformException>()));
});
test('getTokens transforms platform data to GoogleSignInTokenData', () async {
const bool recoverAuth = false;
when(api.getAccessToken()).thenAnswer((_) async =>
TokenData(idToken: _token.idToken, accessToken: _token.accessToken));
final GoogleSignInTokenData response = await googleSignIn.getTokens(
email: _user.email, shouldRecoverAuth: recoverAuth);
expect(response, _token);
});
test('clearAuthCache silently no-ops', () async {
expect(googleSignIn.clearAuthCache(token: 'abc'), completes);
});
test('initWithParams passes arguments', () async {
const SignInInitParameters initParams = SignInInitParameters(
hostedDomain: 'example.com',
scopes: <String>['two', 'scopes'],
clientId: 'fakeClientId',
);
await googleSignIn.init(
hostedDomain: initParams.hostedDomain,
scopes: initParams.scopes,
signInOption: initParams.signInOption,
clientId: initParams.clientId,
);
final VerificationResult result = verify(api.init(captureAny));
final InitParams passedParams = result.captured[0] as InitParams;
expect(passedParams.hostedDomain, initParams.hostedDomain);
expect(passedParams.scopes, initParams.scopes);
expect(passedParams.clientId, initParams.clientId);
// This should use whatever the SignInInitParameters defaults are.
expect(passedParams.serverClientId, initParams.serverClientId);
});
test('initWithParams passes arguments', () async {
const SignInInitParameters initParams = SignInInitParameters(
hostedDomain: 'example.com',
scopes: <String>['two', 'scopes'],
clientId: 'fakeClientId',
serverClientId: 'fakeServerClientId',
forceCodeForRefreshToken: true,
);
await googleSignIn.initWithParams(initParams);
final VerificationResult result = verify(api.init(captureAny));
final InitParams passedParams = result.captured[0] as InitParams;
expect(passedParams.hostedDomain, initParams.hostedDomain);
expect(passedParams.scopes, initParams.scopes);
expect(passedParams.clientId, initParams.clientId);
expect(passedParams.serverClientId, initParams.serverClientId);
});
test('requestScopes passes arguments', () async {
const List<String> scopes = <String>['newScope', 'anotherScope'];
when(api.requestScopes(scopes)).thenAnswer((_) async => true);
final bool response = await googleSignIn.requestScopes(scopes);
expect(response, true);
});
test('signOut calls through', () async {
await googleSignIn.signOut();
verify(api.signOut());
});
test('disconnect calls through', () async {
await googleSignIn.disconnect();
verify(api.disconnect());
});
test('isSignedIn passes true response', () async {
when(api.isSignedIn()).thenAnswer((_) async => true);
expect(await googleSignIn.isSignedIn(), true);
});
test('isSignedIn passes false response', () async {
when(api.isSignedIn()).thenAnswer((_) async => false);
expect(await googleSignIn.isSignedIn(), false);
});
}
| packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart/0 | {'file_path': 'packages/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart', 'repo_id': 'packages', 'token_count': 2272} |
name: google_sign_in_web_integration_tests
publish_to: none
environment:
sdk: ">=3.2.0 <4.0.0"
flutter: ">=3.16.0"
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
google_identity_services_web: ^0.3.0
google_sign_in_platform_interface: ^2.4.0
google_sign_in_web:
path: ../
dev_dependencies:
build_runner: ^2.1.1
flutter_test:
sdk: flutter
http: ">=0.13.0 <2.0.0"
integration_test:
sdk: flutter
mockito: 5.4.4
web: ">=0.3.0 <0.5.0"
flutter:
uses-material-design: true
| packages/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml/0 | {'file_path': 'packages/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 258} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:html' as html;
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker_for_web/image_picker_for_web.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:integration_test/integration_test.dart';
const String expectedStringContents = 'Hello, world!';
const String otherStringContents = 'Hello again, world!';
final Uint8List bytes = const Utf8Encoder().convert(expectedStringContents);
final Uint8List otherBytes = const Utf8Encoder().convert(otherStringContents);
final Map<String, dynamic> options = <String, dynamic>{
'type': 'text/plain',
'lastModified': DateTime.utc(2017, 12, 13).millisecondsSinceEpoch,
};
final html.File textFile = html.File(<Uint8List>[bytes], 'hello.txt', options);
final html.File secondTextFile =
html.File(<Uint8List>[otherBytes], 'secondFile.txt');
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// Under test...
late ImagePickerPlugin plugin;
setUp(() {
plugin = ImagePickerPlugin();
});
testWidgets('getImageFromSource can select a file', (
WidgetTester _,
) async {
final html.FileUploadInputElement mockInput = html.FileUploadInputElement();
final ImagePickerPluginTestOverrides overrides =
ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput = ((_) => <html.File>[textFile]);
final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides);
// Init the pick file dialog...
final Future<XFile?> image = plugin.getImageFromSource(
source: ImageSource.camera,
);
expect(html.querySelector('flt-image-picker-inputs')?.children.isEmpty,
isFalse);
// Mock the browser behavior of selecting a file...
mockInput.dispatchEvent(html.Event('change'));
// Now the file should be available
expect(image, completes);
// And readable
final XFile? file = await image;
expect(file, isNotNull);
expect(file!.readAsBytes(), completion(isNotEmpty));
expect(file.name, textFile.name);
expect(file.length(), completion(textFile.size));
expect(file.mimeType, textFile.type);
expect(
file.lastModified(),
completion(
DateTime.fromMillisecondsSinceEpoch(textFile.lastModified!),
));
expect(html.querySelector('flt-image-picker-inputs')?.children.isEmpty,
isTrue);
});
testWidgets('getMultiImageWithOptions can select multiple files', (
WidgetTester _,
) async {
final html.FileUploadInputElement mockInput = html.FileUploadInputElement();
final ImagePickerPluginTestOverrides overrides =
ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput =
((_) => <html.File>[textFile, secondTextFile]);
final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides);
// Init the pick file dialog...
final Future<List<XFile>> files = plugin.getMultiImageWithOptions();
// Mock the browser behavior of selecting a file...
mockInput.dispatchEvent(html.Event('change'));
// Now the file should be available
expect(files, completes);
// And readable
expect((await files).first.readAsBytes(), completion(isNotEmpty));
// Peek into the second file...
final XFile secondFile = (await files).elementAt(1);
expect(secondFile.readAsBytes(), completion(isNotEmpty));
expect(secondFile.name, secondTextFile.name);
expect(secondFile.length(), completion(secondTextFile.size));
});
testWidgets('getMedia can select multiple files', (WidgetTester _) async {
final html.FileUploadInputElement mockInput = html.FileUploadInputElement();
final ImagePickerPluginTestOverrides overrides =
ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput =
((_) => <html.File>[textFile, secondTextFile]);
final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides);
// Init the pick file dialog...
final Future<List<XFile>> files =
plugin.getMedia(options: const MediaOptions(allowMultiple: true));
// Mock the browser behavior of selecting a file...
mockInput.dispatchEvent(html.Event('change'));
// Now the file should be available
expect(files, completes);
// And readable
expect((await files).first.readAsBytes(), completion(isNotEmpty));
// Peek into the second file...
final XFile secondFile = (await files).elementAt(1);
expect(secondFile.readAsBytes(), completion(isNotEmpty));
expect(secondFile.name, secondTextFile.name);
expect(secondFile.length(), completion(secondTextFile.size));
});
group('cancel event', () {
late html.FileUploadInputElement mockInput;
late ImagePickerPluginTestOverrides overrides;
late ImagePickerPlugin plugin;
setUp(() {
mockInput = html.FileUploadInputElement();
overrides = ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput = ((_) => <html.File>[textFile]);
plugin = ImagePickerPlugin(overrides: overrides);
});
void mockCancel() {
mockInput.dispatchEvent(html.Event('cancel'));
}
testWidgets('getFiles - returns empty list', (WidgetTester _) async {
final Future<List<XFile>> files = plugin.getFiles();
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
testWidgets('getMedia - returns empty list', (WidgetTester _) async {
final Future<List<XFile>?> files = plugin.getMedia(
options: const MediaOptions(
allowMultiple: true,
));
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
testWidgets('getMultiImageWithOptions - returns empty list', (
WidgetTester _,
) async {
final Future<List<XFile>?> files = plugin.getMultiImageWithOptions();
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
testWidgets('getImageFromSource - returns null', (WidgetTester _) async {
final Future<XFile?> file = plugin.getImageFromSource(
source: ImageSource.gallery,
);
mockCancel();
expect(file, completes);
expect(await file, isNull);
});
testWidgets('getVideo - returns null', (WidgetTester _) async {
final Future<XFile?> file = plugin.getVideo(
source: ImageSource.gallery,
);
mockCancel();
expect(file, completes);
expect(await file, isNull);
});
});
testWidgets('computeCaptureAttribute', (WidgetTester tester) async {
expect(
plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.front),
isNull,
);
expect(
plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.rear),
isNull,
);
expect(
plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.front),
'user',
);
expect(
plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.rear),
'environment',
);
});
group('createInputElement', () {
testWidgets('accept: any, capture: null', (WidgetTester tester) async {
final html.Element input = plugin.createInputElement('any', null);
expect(input.attributes, containsPair('accept', 'any'));
expect(input.attributes, isNot(contains('capture')));
expect(input.attributes, isNot(contains('multiple')));
});
testWidgets('accept: any, capture: something', (WidgetTester tester) async {
final html.Element input = plugin.createInputElement('any', 'something');
expect(input.attributes, containsPair('accept', 'any'));
expect(input.attributes, containsPair('capture', 'something'));
expect(input.attributes, isNot(contains('multiple')));
});
testWidgets('accept: any, capture: null, multi: true',
(WidgetTester tester) async {
final html.Element input =
plugin.createInputElement('any', null, multiple: true);
expect(input.attributes, containsPair('accept', 'any'));
expect(input.attributes, isNot(contains('capture')));
expect(input.attributes, contains('multiple'));
});
testWidgets('accept: any, capture: something, multi: true',
(WidgetTester tester) async {
final html.Element input =
plugin.createInputElement('any', 'something', multiple: true);
expect(input.attributes, containsPair('accept', 'any'));
expect(input.attributes, containsPair('capture', 'something'));
expect(input.attributes, contains('multiple'));
});
});
group('Deprecated methods', () {
late html.FileUploadInputElement mockInput;
late ImagePickerPluginTestOverrides overrides;
late ImagePickerPlugin plugin;
setUp(() {
mockInput = html.FileUploadInputElement();
overrides = ImagePickerPluginTestOverrides()
..createInputElement = ((_, __) => mockInput)
..getMultipleFilesFromInput = ((_) => <html.File>[textFile]);
plugin = ImagePickerPlugin(overrides: overrides);
});
void mockCancel() {
mockInput.dispatchEvent(html.Event('cancel'));
}
void mockChange() {
mockInput.dispatchEvent(html.Event('change'));
}
group('getImage', () {
testWidgets('can select a file', (WidgetTester _) async {
// ignore: deprecated_member_use
final Future<XFile?> image = plugin.getImage(
source: ImageSource.camera,
);
// Mock the browser behavior when selecting a file...
mockChange();
// Now the file should be available
expect(image, completes);
// And readable
final XFile? file = await image;
expect(file, isNotNull);
expect(file!.readAsBytes(), completion(isNotEmpty));
expect(file.name, textFile.name);
expect(file.length(), completion(textFile.size));
expect(file.mimeType, textFile.type);
expect(
file.lastModified(),
completion(
DateTime.fromMillisecondsSinceEpoch(textFile.lastModified!),
));
});
testWidgets('returns null when canceled', (WidgetTester _) async {
// ignore: deprecated_member_use
final Future<XFile?> file = plugin.getImage(
source: ImageSource.gallery,
);
mockCancel();
expect(file, completes);
expect(await file, isNull);
});
});
group('getMultiImage', () {
testWidgets('can select multiple files', (WidgetTester _) async {
// Override the returned files...
overrides.getMultipleFilesFromInput =
(_) => <html.File>[textFile, secondTextFile];
// ignore: deprecated_member_use
final Future<List<XFile>> files = plugin.getMultiImage();
// Mock the browser behavior of selecting a file...
mockChange();
// Now the file should be available
expect(files, completes);
// And readable
expect((await files).first.readAsBytes(), completion(isNotEmpty));
// Peek into the second file...
final XFile secondFile = (await files).elementAt(1);
expect(secondFile.readAsBytes(), completion(isNotEmpty));
expect(secondFile.name, secondTextFile.name);
expect(secondFile.length(), completion(secondTextFile.size));
});
testWidgets('returns an empty list when canceled', (
WidgetTester _,
) async {
// ignore: deprecated_member_use
final Future<List<XFile>?> files = plugin.getMultiImage();
mockCancel();
expect(files, completes);
expect(await files, isEmpty);
});
});
});
}
| packages/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart/0 | {'file_path': 'packages/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart', 'repo_id': 'packages', 'token_count': 4438} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http show readBytes;
import './base.dart';
/// A PickedFile that works on web.
///
/// It wraps the bytes of a selected file.
class PickedFile extends PickedFileBase {
/// Construct a PickedFile object from its ObjectUrl.
///
/// Optionally, this can be initialized with `bytes`
/// so no http requests are performed to retrieve files later.
const PickedFile(this.path, {Uint8List? bytes})
: _initBytes = bytes,
super(path);
@override
final String path;
final Uint8List? _initBytes;
Future<Uint8List> get _bytes async {
if (_initBytes != null) {
return Future<Uint8List>.value(UnmodifiableUint8ListView(_initBytes!));
}
return http.readBytes(Uri.parse(path));
}
@override
Future<String> readAsString({Encoding encoding = utf8}) async {
return encoding.decode(await _bytes);
}
@override
Future<Uint8List> readAsBytes() async {
return Future<Uint8List>.value(await _bytes);
}
@override
Stream<Uint8List> openRead([int? start, int? end]) async* {
final Uint8List bytes = await _bytes;
yield bytes.sublist(start ?? 0, end ?? bytes.length);
}
}
| packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart/0 | {'file_path': 'packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart', 'repo_id': 'packages', 'token_count': 472} |
// 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:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../billing_client_wrappers.dart';
import '../in_app_purchase_android.dart';
/// Contains InApp Purchase features that are only available on PlayStore.
class InAppPurchaseAndroidPlatformAddition
extends InAppPurchasePlatformAddition {
/// Creates a [InAppPurchaseAndroidPlatformAddition] which uses the supplied
/// `BillingClientManager` to provide Android specific features.
InAppPurchaseAndroidPlatformAddition(this._billingClientManager);
/// Whether pending purchase is enabled.
///
/// **Deprecation warning:** it is no longer required to call
/// [enablePendingPurchases] when initializing your application. From now on
/// this is handled internally and the [enablePendingPurchase] property will
/// always return `true`.
///
/// See also [enablePendingPurchases] for more on pending purchases.
@Deprecated(
'The requirement to call `enablePendingPurchases()` has become obsolete '
"since Google Play no longer accepts app submissions that don't support "
'pending purchases.')
static bool get enablePendingPurchase => true;
/// Enable the [InAppPurchaseConnection] to handle pending purchases.
///
/// **Deprecation warning:** it is no longer required to call
/// [enablePendingPurchases] when initializing your application.
@Deprecated(
'The requirement to call `enablePendingPurchases()` has become obsolete '
"since Google Play no longer accepts app submissions that don't support "
'pending purchases.')
static void enablePendingPurchases() {
// No-op, until it is time to completely remove this method from the API.
}
final BillingClientManager _billingClientManager;
/// Mark that the user has consumed a product.
///
/// You are responsible for consuming all consumable purchases once they are
/// delivered. The user won't be able to buy the same product again until the
/// purchase of the product is consumed.
Future<BillingResultWrapper> consumePurchase(PurchaseDetails purchase) {
return _billingClientManager.runWithClient(
(BillingClient client) =>
client.consumeAsync(purchase.verificationData.serverVerificationData),
);
}
/// Query all previous purchases.
///
/// The `applicationUserName` should match whatever was sent in the initial
/// `PurchaseParam`, if anything. If no `applicationUserName` was specified in
/// the initial `PurchaseParam`, use `null`.
///
/// This does not return consumed products. If you want to restore unused
/// consumable products, you need to persist consumable product information
/// for your user on your own server.
///
/// See also:
///
/// * [refreshPurchaseVerificationData], for reloading failed
/// [PurchaseDetails.verificationData].
Future<QueryPurchaseDetailsResponse> queryPastPurchases(
{String? applicationUserName}) async {
List<PurchasesResultWrapper> responses;
PlatformException? exception;
try {
responses = await Future.wait(<Future<PurchasesResultWrapper>>[
_billingClientManager.runWithClient(
(BillingClient client) => client.queryPurchases(ProductType.inapp),
),
_billingClientManager.runWithClient(
(BillingClient client) => client.queryPurchases(ProductType.subs),
),
]);
} on PlatformException catch (e) {
exception = e;
responses = <PurchasesResultWrapper>[
PurchasesResultWrapper(
responseCode: BillingResponse.error,
purchasesList: const <PurchaseWrapper>[],
billingResult: BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: e.details.toString(),
),
),
PurchasesResultWrapper(
responseCode: BillingResponse.error,
purchasesList: const <PurchaseWrapper>[],
billingResult: BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: e.details.toString(),
),
)
];
}
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<GooglePlayPurchaseDetails> pastPurchases = responses
.expand((PurchasesResultWrapper response) => response.purchasesList)
.expand((PurchaseWrapper purchaseWrapper) =>
GooglePlayPurchaseDetails.fromPurchase(purchaseWrapper))
.toList();
IAPError? error;
if (exception != null) {
error = IAPError(
source: kIAPSource,
code: exception.code,
message: exception.message ?? '',
details: exception.details);
} else if (errorMessage.isNotEmpty) {
error = IAPError(
source: kIAPSource,
code: kRestoredPurchaseErrorCode,
message: errorMessage);
}
return QueryPurchaseDetailsResponse(
pastPurchases: pastPurchases, error: error);
}
/// Checks if the specified feature or capability is supported by the Play Store.
/// Call this to check if a [BillingClientFeature] is supported by the device.
Future<bool> isFeatureSupported(BillingClientFeature feature) async {
return _billingClientManager.runWithClientNonRetryable(
(BillingClient client) => client.isFeatureSupported(feature),
);
}
}
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart/0 | {'file_path': 'packages/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart', 'repo_id': 'packages', 'token_count': 1933} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'sk_payment_transaction_wrappers.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SKPaymentTransactionWrapper _$SKPaymentTransactionWrapperFromJson(Map json) =>
SKPaymentTransactionWrapper(
payment: SKPaymentWrapper.fromJson(
Map<String, dynamic>.from(json['payment'] as Map)),
transactionState: const SKTransactionStatusConverter()
.fromJson(json['transactionState'] as int?),
originalTransaction: json['originalTransaction'] == null
? null
: SKPaymentTransactionWrapper.fromJson(
Map<String, dynamic>.from(json['originalTransaction'] as Map)),
transactionTimeStamp: (json['transactionTimeStamp'] as num?)?.toDouble(),
transactionIdentifier: json['transactionIdentifier'] as String?,
error: json['error'] == null
? null
: SKError.fromJson(Map<String, dynamic>.from(json['error'] as Map)),
);
Map<String, dynamic> _$SKPaymentTransactionWrapperToJson(
SKPaymentTransactionWrapper instance) =>
<String, dynamic>{
'transactionState': const SKTransactionStatusConverter()
.toJson(instance.transactionState),
'payment': instance.payment,
'originalTransaction': instance.originalTransaction,
'transactionTimeStamp': instance.transactionTimeStamp,
'transactionIdentifier': instance.transactionIdentifier,
'error': instance.error,
};
| packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart/0 | {'file_path': 'packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart', 'repo_id': 'packages', 'token_count': 540} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_storekit/src/channel.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'sk_test_stub_objects.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform();
setUpAll(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform, fakeStoreKitPlatform.onMethodCall);
});
setUp(() {});
tearDown(() {
fakeStoreKitPlatform.testReturnNull = false;
fakeStoreKitPlatform.queueIsActive = null;
fakeStoreKitPlatform.getReceiptFailTest = false;
});
group('sk_request_maker', () {
test('get products method channel', () async {
final SkProductResponseWrapper productResponseWrapper =
await SKRequestMaker().startProductRequest(<String>['xxx']);
expect(
productResponseWrapper.products,
isNotEmpty,
);
expect(
productResponseWrapper.products.first.priceLocale.currencySymbol,
r'$',
);
expect(
productResponseWrapper.products.first.priceLocale.currencySymbol,
isNot('A'),
);
expect(
productResponseWrapper.products.first.priceLocale.currencyCode,
'USD',
);
expect(
productResponseWrapper.products.first.priceLocale.countryCode,
'US',
);
expect(
productResponseWrapper.invalidProductIdentifiers,
isNotEmpty,
);
expect(
fakeStoreKitPlatform.startProductRequestParam,
<String>['xxx'],
);
});
test('get products method channel should throw exception', () async {
fakeStoreKitPlatform.getProductRequestFailTest = true;
expect(
SKRequestMaker().startProductRequest(<String>['xxx']),
throwsException,
);
fakeStoreKitPlatform.getProductRequestFailTest = false;
});
test('refreshed receipt', () async {
final int receiptCountBefore = fakeStoreKitPlatform.refreshReceipt;
await SKRequestMaker().startRefreshReceiptRequest(
receiptProperties: <String, dynamic>{'isExpired': true});
expect(fakeStoreKitPlatform.refreshReceipt, receiptCountBefore + 1);
expect(fakeStoreKitPlatform.refreshReceiptParam,
<String, dynamic>{'isExpired': true});
});
test('should get null receipt if any exceptions are raised', () async {
fakeStoreKitPlatform.getReceiptFailTest = true;
expect(() async => SKReceiptManager.retrieveReceiptData(),
throwsA(const TypeMatcher<PlatformException>()));
});
});
group('sk_receipt_manager', () {
test('should get receipt (faking it by returning a `receipt data` string)',
() async {
final String receiptData = await SKReceiptManager.retrieveReceiptData();
expect(receiptData, 'receipt data');
});
});
group('sk_payment_queue', () {
test('canMakePayment should return true', () async {
expect(await SKPaymentQueueWrapper.canMakePayments(), true);
});
test('canMakePayment returns false if method channel returns null',
() async {
fakeStoreKitPlatform.testReturnNull = true;
expect(await SKPaymentQueueWrapper.canMakePayments(), false);
});
test('storefront returns valid SKStoreFrontWrapper object', () async {
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
expect(
await queue.storefront(),
SKStorefrontWrapper.fromJson(const <String, dynamic>{
'countryCode': 'USA',
'identifier': 'unique_identifier',
}));
});
test('storefront returns null', () async {
fakeStoreKitPlatform.testReturnNull = true;
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
expect(await queue.storefront(), isNull);
});
test('transactions should return a valid list of transactions', () async {
expect(await SKPaymentQueueWrapper().transactions(), isNotEmpty);
});
test(
'throws if observer is not set for payment queue before adding payment',
() async {
expect(SKPaymentQueueWrapper().addPayment(dummyPayment),
throwsAssertionError);
});
test('should add payment to the payment queue', () async {
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
final TestPaymentTransactionObserver observer =
TestPaymentTransactionObserver();
queue.setTransactionObserver(observer);
await queue.addPayment(dummyPayment);
expect(fakeStoreKitPlatform.payments.first, equals(dummyPayment));
});
test('should finish transaction', () async {
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
final TestPaymentTransactionObserver observer =
TestPaymentTransactionObserver();
queue.setTransactionObserver(observer);
await queue.finishTransaction(dummyTransaction);
expect(fakeStoreKitPlatform.transactionsFinished.first,
equals(dummyTransaction.toFinishMap()));
});
test('should restore transaction', () async {
final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper();
final TestPaymentTransactionObserver observer =
TestPaymentTransactionObserver();
queue.setTransactionObserver(observer);
await queue.restoreTransactions(applicationUserName: 'aUserID');
expect(fakeStoreKitPlatform.applicationNameHasTransactionRestored,
'aUserID');
});
test('startObservingTransactionQueue should call methodChannel', () async {
expect(fakeStoreKitPlatform.queueIsActive, isNot(true));
await SKPaymentQueueWrapper().startObservingTransactionQueue();
expect(fakeStoreKitPlatform.queueIsActive, true);
});
test('stopObservingTransactionQueue should call methodChannel', () async {
expect(fakeStoreKitPlatform.queueIsActive, isNot(false));
await SKPaymentQueueWrapper().stopObservingTransactionQueue();
expect(fakeStoreKitPlatform.queueIsActive, false);
});
test('setDelegate should call methodChannel', () async {
expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, false);
await SKPaymentQueueWrapper().setDelegate(TestPaymentQueueDelegate());
expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, true);
await SKPaymentQueueWrapper().setDelegate(null);
expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, false);
});
test('showPriceConsentIfNeeded should call methodChannel', () async {
expect(fakeStoreKitPlatform.showPriceConsentIfNeeded, false);
await SKPaymentQueueWrapper().showPriceConsentIfNeeded();
expect(fakeStoreKitPlatform.showPriceConsentIfNeeded, true);
});
});
group('Code Redemption Sheet', () {
test('presentCodeRedemptionSheet should not throw', () async {
expect(fakeStoreKitPlatform.presentCodeRedemption, false);
await SKPaymentQueueWrapper().presentCodeRedemptionSheet();
expect(fakeStoreKitPlatform.presentCodeRedemption, true);
fakeStoreKitPlatform.presentCodeRedemption = false;
});
});
}
class FakeStoreKitPlatform {
FakeStoreKitPlatform() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, onMethodCall);
}
// get product request
List<dynamic> startProductRequestParam = <dynamic>[];
bool getProductRequestFailTest = false;
bool testReturnNull = false;
// get receipt request
bool getReceiptFailTest = false;
// refresh receipt request
int refreshReceipt = 0;
late Map<String, dynamic> refreshReceiptParam;
// payment queue
List<SKPaymentWrapper> payments = <SKPaymentWrapper>[];
List<Map<String, String>> transactionsFinished = <Map<String, String>>[];
String applicationNameHasTransactionRestored = '';
// present Code Redemption
bool presentCodeRedemption = false;
// show price consent sheet
bool showPriceConsentIfNeeded = false;
// indicate if the payment queue delegate is registered
bool isPaymentQueueDelegateRegistered = false;
// Listen to purchase updates
bool? queueIsActive;
Future<dynamic> onMethodCall(MethodCall call) {
switch (call.method) {
// request makers
case '-[InAppPurchasePlugin startProductRequest:result:]':
startProductRequestParam = call.arguments as List<dynamic>;
if (getProductRequestFailTest) {
return Future<dynamic>.value();
}
return Future<Map<String, dynamic>>.value(
buildProductResponseMap(dummyProductResponseWrapper));
case '-[InAppPurchasePlugin refreshReceipt:result:]':
refreshReceipt++;
refreshReceiptParam = Map.castFrom<dynamic, dynamic, String, dynamic>(
call.arguments as Map<dynamic, dynamic>);
return Future<void>.sync(() {});
// receipt manager
case '-[InAppPurchasePlugin retrieveReceiptData:result:]':
if (getReceiptFailTest) {
throw Exception('some arbitrary error');
}
return Future<String>.value('receipt data');
// payment queue
case '-[SKPaymentQueue canMakePayments:]':
if (testReturnNull) {
return Future<dynamic>.value();
}
return Future<bool>.value(true);
case '-[SKPaymentQueue transactions]':
return Future<List<dynamic>>.value(
<dynamic>[buildTransactionMap(dummyTransaction)]);
case '-[SKPaymentQueue storefront]':
if (testReturnNull) {
return Future<dynamic>.value();
}
return Future<Map<String, dynamic>>.value(const <String, dynamic>{
'countryCode': 'USA',
'identifier': 'unique_identifier',
});
case '-[InAppPurchasePlugin addPayment:result:]':
payments.add(SKPaymentWrapper.fromJson(Map<String, dynamic>.from(
call.arguments as Map<dynamic, dynamic>)));
return Future<void>.sync(() {});
case '-[InAppPurchasePlugin finishTransaction:result:]':
transactionsFinished.add(
Map<String, String>.from(call.arguments as Map<dynamic, dynamic>));
return Future<void>.sync(() {});
case '-[InAppPurchasePlugin restoreTransactions:result:]':
applicationNameHasTransactionRestored = call.arguments as String;
return Future<void>.sync(() {});
case '-[InAppPurchasePlugin presentCodeRedemptionSheet:result:]':
presentCodeRedemption = true;
return Future<void>.sync(() {});
case '-[SKPaymentQueue startObservingTransactionQueue]':
queueIsActive = true;
return Future<void>.sync(() {});
case '-[SKPaymentQueue stopObservingTransactionQueue]':
queueIsActive = false;
return Future<void>.sync(() {});
case '-[SKPaymentQueue registerDelegate]':
isPaymentQueueDelegateRegistered = true;
return Future<void>.sync(() {});
case '-[SKPaymentQueue removeDelegate]':
isPaymentQueueDelegateRegistered = false;
return Future<void>.sync(() {});
case '-[SKPaymentQueue showPriceConsentIfNeeded]':
showPriceConsentIfNeeded = true;
return Future<void>.sync(() {});
}
return Future<dynamic>.error('method not mocked');
}
}
class TestPaymentQueueDelegate extends SKPaymentQueueDelegateWrapper {}
class TestPaymentTransactionObserver extends SKTransactionObserverWrapper {
@override
void updatedTransactions(
{required List<SKPaymentTransactionWrapper> transactions}) {}
@override
void removedTransactions(
{required List<SKPaymentTransactionWrapper> transactions}) {}
@override
void restoreCompletedTransactionsFailed({required SKError error}) {}
@override
void paymentQueueRestoreCompletedTransactionsFinished() {}
@override
bool shouldAddStorePayment(
{required SKPaymentWrapper payment, required SKProductWrapper product}) {
return true;
}
}
| packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart/0 | {'file_path': 'packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart', 'repo_id': 'packages', 'token_count': 4345} |
// 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:intl/intl.dart';
import 'package:local_auth_platform_interface/types/auth_messages.dart';
/// Android side authentication messages.
///
/// Provides default values for all messages.
@immutable
class AndroidAuthMessages extends AuthMessages {
/// Constructs a new instance.
const AndroidAuthMessages({
this.biometricHint,
this.biometricNotRecognized,
this.biometricRequiredTitle,
this.biometricSuccess,
this.cancelButton,
this.deviceCredentialsRequiredTitle,
this.deviceCredentialsSetupDescription,
this.goToSettingsButton,
this.goToSettingsDescription,
this.signInTitle,
});
/// Hint message advising the user how to authenticate with biometrics.
/// Maximum 60 characters.
final String? biometricHint;
/// Message to let the user know that authentication was failed.
/// Maximum 60 characters.
final String? biometricNotRecognized;
/// Message shown as a title in a dialog which indicates the user
/// has not set up biometric authentication on their device.
/// Maximum 60 characters.
final String? biometricRequiredTitle;
/// Message to let the user know that authentication was successful.
/// Maximum 60 characters
final String? biometricSuccess;
/// Message shown on a button that the user can click to leave the
/// current dialog.
/// Maximum 30 characters.
final String? cancelButton;
/// Message shown as a title in a dialog which indicates the user
/// has not set up credentials authentication on their device.
/// Maximum 60 characters.
final String? deviceCredentialsRequiredTitle;
/// Message advising the user to go to the settings and configure
/// device credentials on their device.
final String? deviceCredentialsSetupDescription;
/// Message shown on a button that the user can click to go to settings pages
/// from the current dialog.
/// Maximum 30 characters.
final String? goToSettingsButton;
/// Message advising the user to go to the settings and configure
/// biometric on their device.
final String? goToSettingsDescription;
/// Message shown as a title in a dialog which indicates the user
/// that they need to scan biometric to continue.
/// Maximum 60 characters.
final String? signInTitle;
@override
Map<String, String> get args {
return <String, String>{
'biometricHint': biometricHint ?? androidBiometricHint,
'biometricNotRecognized':
biometricNotRecognized ?? androidBiometricNotRecognized,
'biometricSuccess': biometricSuccess ?? androidBiometricSuccess,
'biometricRequired':
biometricRequiredTitle ?? androidBiometricRequiredTitle,
'cancelButton': cancelButton ?? androidCancelButton,
'deviceCredentialsRequired': deviceCredentialsRequiredTitle ??
androidDeviceCredentialsRequiredTitle,
'deviceCredentialsSetupDescription': deviceCredentialsSetupDescription ??
androidDeviceCredentialsSetupDescription,
'goToSetting': goToSettingsButton ?? goToSettings,
'goToSettingDescription':
goToSettingsDescription ?? androidGoToSettingsDescription,
'signInTitle': signInTitle ?? androidSignInTitle,
};
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AndroidAuthMessages &&
runtimeType == other.runtimeType &&
biometricHint == other.biometricHint &&
biometricNotRecognized == other.biometricNotRecognized &&
biometricRequiredTitle == other.biometricRequiredTitle &&
biometricSuccess == other.biometricSuccess &&
cancelButton == other.cancelButton &&
deviceCredentialsRequiredTitle ==
other.deviceCredentialsRequiredTitle &&
deviceCredentialsSetupDescription ==
other.deviceCredentialsSetupDescription &&
goToSettingsButton == other.goToSettingsButton &&
goToSettingsDescription == other.goToSettingsDescription &&
signInTitle == other.signInTitle;
@override
int get hashCode => Object.hash(
super.hashCode,
biometricHint,
biometricNotRecognized,
biometricRequiredTitle,
biometricSuccess,
cancelButton,
deviceCredentialsRequiredTitle,
deviceCredentialsSetupDescription,
goToSettingsButton,
goToSettingsDescription,
signInTitle);
}
// Default strings for AndroidAuthMessages. Currently supports English.
// Intl.message must be string literals.
/// Message shown on a button that the user can click to go to settings pages
/// from the current dialog.
String get goToSettings => Intl.message('Go to settings',
desc: 'Message shown on a button that the user can click to go to '
'settings pages from the current dialog. Maximum 30 characters.');
/// Hint message advising the user how to authenticate with biometrics.
String get androidBiometricHint => Intl.message('Verify identity',
desc: 'Hint message advising the user how to authenticate with biometrics. '
'Maximum 60 characters.');
/// Message to let the user know that authentication was failed.
String get androidBiometricNotRecognized =>
Intl.message('Not recognized. Try again.',
desc: 'Message to let the user know that authentication was failed. '
'Maximum 60 characters.');
/// Message to let the user know that authentication was successful. It
String get androidBiometricSuccess => Intl.message('Success',
desc: 'Message to let the user know that authentication was successful. '
'Maximum 60 characters.');
/// Message shown on a button that the user can click to leave the
/// current dialog.
String get androidCancelButton => Intl.message('Cancel',
desc: 'Message shown on a button that the user can click to leave the '
'current dialog. Maximum 30 characters.');
/// Message shown as a title in a dialog which indicates the user
/// that they need to scan biometric to continue.
String get androidSignInTitle => Intl.message('Authentication required',
desc: 'Message shown as a title in a dialog which indicates the user '
'that they need to scan biometric to continue. Maximum 60 characters.');
/// Message shown as a title in a dialog which indicates the user
/// has not set up biometric authentication on their device.
String get androidBiometricRequiredTitle => Intl.message('Biometric required',
desc: 'Message shown as a title in a dialog which indicates the user '
'has not set up biometric authentication on their device. '
'Maximum 60 characters.');
/// Message shown as a title in a dialog which indicates the user
/// has not set up credentials authentication on their device.
String get androidDeviceCredentialsRequiredTitle =>
Intl.message('Device credentials required',
desc: 'Message shown as a title in a dialog which indicates the user '
'has not set up credentials authentication on their device. '
'Maximum 60 characters.');
/// Message advising the user to go to the settings and configure
/// device credentials on their device.
String get androidDeviceCredentialsSetupDescription =>
Intl.message('Device credentials required',
desc: 'Message advising the user to go to the settings and configure '
'device credentials on their device.');
/// Message advising the user to go to the settings and configure
/// biometric on their device.
String get androidGoToSettingsDescription => Intl.message(
'Biometric authentication is not set up on your device. Go to '
"'Settings > Security' to add biometric authentication.",
desc: 'Message advising the user to go to the settings and configure '
'biometric on their device.');
| packages/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart/0 | {'file_path': 'packages/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart', 'repo_id': 'packages', 'token_count': 2315} |
// 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 'common.dart';
import 'constants.dart';
import 'skiaperf.dart';
/// Convenient class to capture the benchmarks in the Flutter engine repo.
class FlutterEngineMetricPoint extends MetricPoint {
/// Creates a metric point for the Flutter engine repository.
///
/// The `name`, `value`, and `gitRevision` parameters must not be null.
FlutterEngineMetricPoint(
String name,
double value,
String gitRevision, {
Map<String, String> moreTags = const <String, String>{},
}) : super(
value,
<String, String>{
kNameKey: name,
kGithubRepoKey: kFlutterEngineRepo,
kGitRevisionKey: gitRevision,
}..addAll(moreTags),
);
}
/// All Flutter performance metrics (framework, engine, ...) should be written
/// to this destination.
class FlutterDestination extends MetricDestination {
FlutterDestination._(this._skiaPerfDestination);
/// Creates a [FlutterDestination] from service account JSON.
static Future<FlutterDestination> makeFromCredentialsJson(
Map<String, dynamic> json,
{bool isTesting = false}) async {
final SkiaPerfDestination skiaPerfDestination =
await SkiaPerfDestination.makeFromGcpCredentials(json,
isTesting: isTesting);
return FlutterDestination._(skiaPerfDestination);
}
/// Creates a [FlutterDestination] from an OAuth access token.
static Future<FlutterDestination> makeFromAccessToken(
String accessToken, String projectId,
{bool isTesting = false}) async {
final SkiaPerfDestination skiaPerfDestination =
await SkiaPerfDestination.makeFromAccessToken(accessToken, projectId,
isTesting: isTesting);
return FlutterDestination._(skiaPerfDestination);
}
@override
Future<void> update(
List<MetricPoint> points, DateTime commitTime, String taskName) async {
await _skiaPerfDestination.update(points, commitTime, taskName);
}
final SkiaPerfDestination _skiaPerfDestination;
}
| packages/packages/metrics_center/lib/src/flutter.dart/0 | {'file_path': 'packages/packages/metrics_center/lib/src/flutter.dart', 'repo_id': 'packages', 'token_count': 753} |
// 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.
// Test that the resource record cache works correctly. In particular, make
// sure that it removes all entries for a name before insertingrecords
// of that name.
import 'dart:io';
import 'package:multicast_dns/src/native_protocol_client.dart'
show ResourceRecordCache;
import 'package:multicast_dns/src/resource_record.dart';
import 'package:test/test.dart';
void main() {
testOverwrite();
testTimeout();
}
void testOverwrite() {
test('Cache can overwrite entries', () {
final InternetAddress ip1 = InternetAddress('192.168.1.1');
final InternetAddress ip2 = InternetAddress('192.168.1.2');
final int valid = DateTime.now().millisecondsSinceEpoch + 86400 * 1000;
final ResourceRecordCache cache = ResourceRecordCache();
// Add two different records.
cache.updateRecords(<ResourceRecord>[
IPAddressResourceRecord('hest', valid, address: ip1),
IPAddressResourceRecord('fisk', valid, address: ip2)
]);
expect(cache.entryCount, 2);
// Update these records.
cache.updateRecords(<ResourceRecord>[
IPAddressResourceRecord('hest', valid, address: ip1),
IPAddressResourceRecord('fisk', valid, address: ip2)
]);
expect(cache.entryCount, 2);
// Add two records with the same name (should remove the old one
// with that name only.)
cache.updateRecords(<ResourceRecord>[
IPAddressResourceRecord('hest', valid, address: ip1),
IPAddressResourceRecord('hest', valid, address: ip2)
]);
expect(cache.entryCount, 3);
// Overwrite the two cached entries with one with the same name.
cache.updateRecords(<ResourceRecord>[
IPAddressResourceRecord('hest', valid, address: ip1),
]);
expect(cache.entryCount, 2);
});
}
void testTimeout() {
test('Cache can evict records after timeout', () {
final InternetAddress ip1 = InternetAddress('192.168.1.1');
final int valid = DateTime.now().millisecondsSinceEpoch + 86400 * 1000;
final int notValid = DateTime.now().millisecondsSinceEpoch - 1;
final ResourceRecordCache cache = ResourceRecordCache();
cache.updateRecords(
<ResourceRecord>[IPAddressResourceRecord('hest', valid, address: ip1)]);
expect(cache.entryCount, 1);
cache.updateRecords(<ResourceRecord>[
IPAddressResourceRecord('fisk', notValid, address: ip1)
]);
List<ResourceRecord> results = <ResourceRecord>[];
cache.lookup('hest', ResourceRecordType.addressIPv4, results);
expect(results.isEmpty, isFalse);
results = <ResourceRecord>[];
cache.lookup('fisk', ResourceRecordType.addressIPv4, results);
expect(results.isEmpty, isTrue);
expect(cache.entryCount, 1);
});
}
| packages/packages/multicast_dns/test/resource_record_cache_test.dart/0 | {'file_path': 'packages/packages/multicast_dns/test/resource_record_cache_test.dart', 'repo_id': 'packages', 'token_count': 941} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:path_provider_foundation/path_provider_foundation.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
void main() {
runApp(const MyApp());
}
/// Sample app
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? _tempDirectory = 'Unknown';
String? _downloadsDirectory = 'Unknown';
String? _libraryDirectory = 'Unknown';
String? _appSupportDirectory = 'Unknown';
String? _documentsDirectory = 'Unknown';
String? _containerDirectory = 'Unknown';
String? _cacheDirectory = 'Unknown';
@override
void initState() {
super.initState();
initDirectories();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initDirectories() async {
String? tempDirectory;
String? downloadsDirectory;
String? appSupportDirectory;
String? libraryDirectory;
String? documentsDirectory;
String? containerDirectory;
String? cacheDirectory;
final PathProviderPlatform provider = PathProviderPlatform.instance;
final PathProviderFoundation providerFoundation = PathProviderFoundation();
try {
tempDirectory = await provider.getTemporaryPath();
} catch (exception) {
tempDirectory = 'Failed to get temp directory: $exception';
}
try {
downloadsDirectory = await provider.getDownloadsPath();
} catch (exception) {
downloadsDirectory = 'Failed to get downloads directory: $exception';
}
try {
documentsDirectory = await provider.getApplicationDocumentsPath();
} catch (exception) {
documentsDirectory = 'Failed to get documents directory: $exception';
}
try {
libraryDirectory = await provider.getLibraryPath();
} catch (exception) {
libraryDirectory = 'Failed to get library directory: $exception';
}
try {
appSupportDirectory = await provider.getApplicationSupportPath();
} catch (exception) {
appSupportDirectory = 'Failed to get app support directory: $exception';
}
try {
containerDirectory = await providerFoundation.getContainerPath(
appGroupIdentifier: 'group.flutter.appGroupTest');
} catch (exception) {
containerDirectory =
'Failed to get app group container directory: $exception';
}
try {
cacheDirectory = await provider.getApplicationCachePath();
} catch (exception) {
cacheDirectory = 'Failed to get cache directory: $exception';
}
setState(() {
_tempDirectory = tempDirectory;
_downloadsDirectory = downloadsDirectory;
_libraryDirectory = libraryDirectory;
_appSupportDirectory = appSupportDirectory;
_documentsDirectory = documentsDirectory;
_containerDirectory = containerDirectory;
_cacheDirectory = cacheDirectory;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Path Provider example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Temp Directory: $_tempDirectory\n'),
Text('Documents Directory: $_documentsDirectory\n'),
Text('Downloads Directory: $_downloadsDirectory\n'),
Text('Library Directory: $_libraryDirectory\n'),
Text('Application Support Directory: $_appSupportDirectory\n'),
Text('App Group Container Directory: $_containerDirectory\n'),
Text('Cache Directory: $_cacheDirectory\n'),
],
),
),
),
);
}
}
| packages/packages/path_provider/path_provider_foundation/example/lib/main.dart/0 | {'file_path': 'packages/packages/path_provider/path_provider_foundation/example/lib/main.dart', 'repo_id': 'packages', 'token_count': 1361} |
// 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',
swiftOut: 'macos/Classes/messages.g.swift',
dartOut: 'lib/messages.g.dart',
dartTestOut: 'test/messages_test.g.dart',
copyrightHeader: 'pigeons/copyright.txt',
))
enum DirectoryType {
applicationDocuments,
applicationSupport,
downloads,
library,
temp,
applicationCache,
}
@HostApi(dartHostTestHandler: 'TestPathProviderApi')
abstract class PathProviderApi {
String? getDirectoryPath(DirectoryType type);
String? getContainerPath(String appGroupIdentifier);
}
| packages/packages/path_provider/path_provider_foundation/pigeons/messages.dart/0 | {'file_path': 'packages/packages/path_provider/path_provider_foundation/pigeons/messages.dart', 'repo_id': 'packages', 'token_count': 249} |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/pigeon/example/app/.pluginToolsConfig.yaml/0 | {'file_path': 'packages/packages/pigeon/example/app/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'src/messages.g.dart';
// #docregion main-dart-flutter
class _ExampleFlutterApi implements MessageFlutterApi {
@override
String flutterMethod(String? aString) {
return aString ?? '';
}
}
// #enddocregion main-dart-flutter
void main() {
// #docregion main-dart-flutter
MessageFlutterApi.setup(_ExampleFlutterApi());
// #enddocregion main-dart-flutter
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Pigeon Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Pigeon Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final ExampleHostApi _hostApi = ExampleHostApi();
String? _hostCallResult;
// #docregion main-dart
final ExampleHostApi _api = ExampleHostApi();
/// Calls host method `add` with provided arguments.
Future<int> add(int a, int b) async {
try {
return await _api.add(a, b);
} catch (e) {
// handle error.
return 0;
}
}
/// Sends message through host api using `MessageData` class
/// and api `sendMessage` method.
Future<bool> sendMessage(String messageText) {
final MessageData message = MessageData(
code: Code.one,
data: <String?, String?>{'header': 'this is a header'},
description: 'uri text',
);
try {
return _api.sendMessage(message);
} catch (e) {
// handle error.
return Future<bool>(() => true);
}
}
// #enddocregion main-dart
@override
void initState() {
super.initState();
_hostApi.getHostLanguage().then((String response) {
setState(() {
_hostCallResult = 'Hello from $response!';
});
}).onError<PlatformException>((PlatformException error, StackTrace _) {
setState(() {
_hostCallResult = 'Failed to get host language: ${error.message}';
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_hostCallResult ?? 'Waiting for host language...',
),
if (_hostCallResult == null) const CircularProgressIndicator(),
],
),
),
);
}
}
| packages/packages/pigeon/example/app/lib/main.dart/0 | {'file_path': 'packages/packages/pigeon/example/app/lib/main.dart', 'repo_id': 'packages', 'token_count': 1193} |
// 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';
// #docregion config
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartOptions: DartOptions(),
cppOptions: CppOptions(namespace: 'pigeon_example'),
cppHeaderOut: 'windows/runner/messages.g.h',
cppSourceOut: 'windows/runner/messages.g.cpp',
kotlinOut:
'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt',
kotlinOptions: KotlinOptions(),
javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java',
javaOptions: JavaOptions(),
swiftOut: 'ios/Runner/Messages.g.swift',
swiftOptions: SwiftOptions(),
objcHeaderOut: 'macos/Runner/messages.g.h',
objcSourceOut: 'macos/Runner/messages.g.m',
// Set this to a unique prefix for your plugin or application, per Objective-C naming conventions.
objcOptions: ObjcOptions(prefix: 'PGN'),
copyrightHeader: 'pigeons/copyright.txt',
dartPackageName: 'pigeon_example_package',
))
// #enddocregion config
// This file and ./messages_test.dart must be identical below this line.
// #docregion host-definitions
enum Code { one, two }
class MessageData {
MessageData({required this.code, required this.data});
String? name;
String? description;
Code code;
Map<String?, String?> data;
}
@HostApi()
abstract class ExampleHostApi {
String getHostLanguage();
// These annotations create more idiomatic naming of methods in Objc and Swift.
@ObjCSelector('addNumber:toNumber:')
@SwiftFunction('add(_:to:)')
int add(int a, int b);
@async
bool sendMessage(MessageData message);
}
// #enddocregion host-definitions
// #docregion flutter-definitions
@FlutterApi()
abstract class MessageFlutterApi {
String flutterMethod(String? aString);
}
// #enddocregion flutter-definitions
| packages/packages/pigeon/example/app/pigeons/messages.dart/0 | {'file_path': 'packages/packages/pigeon/example/app/pigeons/messages.dart', 'repo_id': 'packages', 'token_count': 649} |
// 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';
@HostApi()
abstract class PrimitiveHostApi {
int anInt(int value);
bool aBool(bool value);
String aString(String value);
double aDouble(double value);
// ignore: always_specify_types, strict_raw_type
Map aMap(Map value);
// ignore: always_specify_types, strict_raw_type
List aList(List value);
Int32List anInt32List(Int32List value);
List<bool?> aBoolList(List<bool?> value);
Map<String?, int?> aStringIntMap(Map<String?, int?> value);
}
@FlutterApi()
abstract class PrimitiveFlutterApi {
int anInt(int value);
bool aBool(bool value);
String aString(String value);
double aDouble(double value);
// ignore: always_specify_types, strict_raw_type
Map aMap(Map value);
// ignore: always_specify_types, strict_raw_type
List aList(List value);
Int32List anInt32List(Int32List value);
List<bool?> aBoolList(List<bool?> value);
Map<String?, int?> aStringIntMap(Map<String?, int?> value);
}
| packages/packages/pigeon/pigeons/primitive.dart/0 | {'file_path': 'packages/packages/pigeon/pigeons/primitive.dart', 'repo_id': 'packages', 'token_count': 390} |
name: alternate_language_test_plugin_example
description: Pigeon test harness for alternate plugin languages.
publish_to: 'none'
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
alternate_language_test_plugin:
path: ../
flutter:
sdk: flutter
shared_test_plugin_code:
path: ../../shared_test_plugin_code
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml/0 | {'file_path': 'packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 173} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// TODO(louisehsu): given the difficulty of making the same integration tests
// work for both web and ios implementations, please find tests in their respective
// platform implementation packages.
testWidgets('placeholder test', (WidgetTester tester) async {});
}
| packages/packages/pointer_interceptor/pointer_interceptor/example/integration_test/widget_test.dart/0 | {'file_path': 'packages/packages/pointer_interceptor/pointer_interceptor/example/integration_test/widget_test.dart', 'repo_id': 'packages', 'token_count': 181} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test(
'Default implementation of PointerInterceptorPlatform should throw unimplemented error',
() {
final PointerInterceptorPlatform unimplementedPointerInterceptorPlatform =
UnimplementedPointerInterceptorPlatform();
final Container testChild = Container();
expect(
() => unimplementedPointerInterceptorPlatform.buildWidget(
child: testChild),
throwsUnimplementedError);
});
}
class UnimplementedPointerInterceptorPlatform
extends PointerInterceptorPlatform {}
| packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart/0 | {'file_path': 'packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart', 'repo_id': 'packages', 'token_count': 292} |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/shared_preferences/shared_preferences/example/.pluginToolsConfig.yaml/0 | {'file_path': 'packages/packages/shared_preferences/shared_preferences/example/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:shared_preferences_platform_interface/types.dart';
/// Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing
/// a persistent store for simple data.
///
/// Data is persisted to disk asynchronously.
class SharedPreferences {
SharedPreferences._(this._preferenceCache);
static String _prefix = 'flutter.';
static bool _prefixHasBeenChanged = false;
static Set<String>? _allowList;
static Completer<SharedPreferences>? _completer;
static SharedPreferencesStorePlatform get _store =>
SharedPreferencesStorePlatform.instance;
/// Sets the prefix that is attached to all keys for all shared preferences.
///
/// This changes the inputs when adding data to preferences as well as
/// setting the filter that determines what data will be returned
/// from the `getInstance` method.
///
/// By default, the prefix is 'flutter.', which is compatible with the
/// previous behavior of this plugin. To use preferences with no prefix,
/// set [prefix] to ''.
///
/// If [prefix] is set to '', you may encounter preferences that are
/// incompatible with shared_preferences. The optional parameter
/// [allowList] will cause the plugin to only return preferences that
/// are both contained in the list AND match the provided prefix.
///
/// No migration of existing preferences is performed by this method.
/// If you set a different prefix, and have previously stored preferences,
/// you will need to handle any migration yourself.
///
/// This cannot be called after `getInstance`.
static void setPrefix(String prefix, {Set<String>? allowList}) {
if (_completer != null) {
throw StateError('setPrefix cannot be called after getInstance');
}
_prefix = prefix;
_prefixHasBeenChanged = true;
_allowList = allowList;
}
/// Resets class's static values to allow for testing of setPrefix flow.
@visibleForTesting
static void resetStatic() {
_completer = null;
_prefix = 'flutter.';
_prefixHasBeenChanged = false;
_allowList = null;
}
/// Loads and parses the [SharedPreferences] for this app from disk.
///
/// Because this is reading from disk, it shouldn't be awaited in
/// performance-sensitive blocks.
static Future<SharedPreferences> getInstance() async {
if (_completer == null) {
final Completer<SharedPreferences> completer =
Completer<SharedPreferences>();
_completer = completer;
try {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
completer.complete(SharedPreferences._(preferencesMap));
} catch (e) {
// If there's an error, explicitly return the future with an error.
// then set the completer to null so we can retry.
completer.completeError(e);
final Future<SharedPreferences> sharedPrefsFuture = completer.future;
_completer = null;
return sharedPrefsFuture;
}
}
return _completer!.future;
}
/// The cache that holds all preferences.
///
/// It is instantiated to the current state of the SharedPreferences or
/// NSUserDefaults object and then kept in sync via setter methods in this
/// class.
///
/// It is NOT guaranteed that this cache and the device prefs will remain
/// in sync since the setter method might fail for any reason.
final Map<String, Object> _preferenceCache;
/// Returns all keys in the persistent storage.
Set<String> getKeys() => Set<String>.from(_preferenceCache.keys);
/// Reads a value of any type from persistent storage.
Object? get(String key) => _preferenceCache[key];
/// Reads a value from persistent storage, throwing an exception if it's not a
/// bool.
bool? getBool(String key) => _preferenceCache[key] as bool?;
/// Reads a value from persistent storage, throwing an exception if it's not
/// an int.
int? getInt(String key) => _preferenceCache[key] as int?;
/// Reads a value from persistent storage, throwing an exception if it's not a
/// double.
double? getDouble(String key) => _preferenceCache[key] as double?;
/// Reads a value from persistent storage, throwing an exception if it's not a
/// String.
String? getString(String key) => _preferenceCache[key] as String?;
/// Returns true if the persistent storage contains the given [key].
bool containsKey(String key) => _preferenceCache.containsKey(key);
/// Reads a set of string values from persistent storage, throwing an
/// exception if it's not a string set.
List<String>? getStringList(String key) {
List<dynamic>? list = _preferenceCache[key] as List<dynamic>?;
if (list != null && list is! List<String>) {
list = list.cast<String>().toList();
_preferenceCache[key] = list;
}
// Make a copy of the list so that later mutations won't propagate
return list?.toList() as List<String>?;
}
/// Saves a boolean [value] to persistent storage in the background.
Future<bool> setBool(String key, bool value) => _setValue('Bool', key, value);
/// Saves an integer [value] to persistent storage in the background.
Future<bool> setInt(String key, int value) => _setValue('Int', key, value);
/// Saves a double [value] to persistent storage in the background.
///
/// Android doesn't support storing doubles, so it will be stored as a float.
Future<bool> setDouble(String key, double value) =>
_setValue('Double', key, value);
/// Saves a string [value] to persistent storage in the background.
///
/// Note: Due to limitations in Android's SharedPreferences,
/// values cannot start with any one of the following:
///
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu'
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy'
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu'
Future<bool> setString(String key, String value) =>
_setValue('String', key, value);
/// Saves a list of strings [value] to persistent storage in the background.
Future<bool> setStringList(String key, List<String> value) =>
_setValue('StringList', key, value);
/// Removes an entry from persistent storage.
Future<bool> remove(String key) {
final String prefixedKey = '$_prefix$key';
_preferenceCache.remove(key);
return _store.remove(prefixedKey);
}
Future<bool> _setValue(String valueType, String key, Object value) {
ArgumentError.checkNotNull(value, 'value');
final String prefixedKey = '$_prefix$key';
if (value is List<String>) {
// Make a copy of the list so that later mutations won't propagate
_preferenceCache[key] = value.toList();
} else {
_preferenceCache[key] = value;
}
return _store.setValue(valueType, prefixedKey, value);
}
/// Always returns true.
/// On iOS, synchronize is marked deprecated. On Android, we commit every set.
@Deprecated('This method is now a no-op, and should no longer be called.')
Future<bool> commit() async => true;
/// Completes with true once the user preferences for the app has been cleared.
Future<bool> clear() {
_preferenceCache.clear();
if (_prefixHasBeenChanged) {
try {
return _store.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(
prefix: _prefix,
allowList: _allowList,
),
),
);
} catch (e) {
// Catching and clarifying UnimplementedError to provide a more robust message.
if (e is UnimplementedError) {
throw UnimplementedError('''
This implementation of Shared Preferences doesn't yet support the setPrefix method.
Either update the implementation to support setPrefix, or do not call setPrefix.
''');
} else {
rethrow;
}
}
}
return _store.clear();
}
/// Fetches the latest values from the host platform.
///
/// Use this method to observe modifications that were made in native code
/// (without using the plugin) while the app is running.
Future<void> reload() async {
final Map<String, Object> preferences =
await SharedPreferences._getSharedPreferencesMap();
_preferenceCache.clear();
_preferenceCache.addAll(preferences);
}
static Future<Map<String, Object>> _getSharedPreferencesMap() async {
final Map<String, Object> fromSystem = <String, Object>{};
if (_prefixHasBeenChanged) {
try {
fromSystem.addAll(
await _store.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(
prefix: _prefix,
allowList: _allowList,
),
),
),
);
} catch (e) {
// Catching and clarifying UnimplementedError to provide a more robust message.
if (e is UnimplementedError) {
throw UnimplementedError('''
This implementation of Shared Preferences doesn't yet support the setPrefix method.
Either update the implementation to support setPrefix, or do not call setPrefix.
''');
} else {
rethrow;
}
}
} else {
fromSystem.addAll(await _store.getAll());
}
if (_prefix.isEmpty) {
return fromSystem;
}
// Strip the prefix from the returned preferences.
final Map<String, Object> preferencesMap = <String, Object>{};
for (final String key in fromSystem.keys) {
assert(key.startsWith(_prefix));
preferencesMap[key.substring(_prefix.length)] = fromSystem[key]!;
}
return preferencesMap;
}
/// Initializes the shared preferences with mock values for testing.
///
/// If the singleton instance has been initialized already, it is nullified.
@visibleForTesting
static void setMockInitialValues(Map<String, Object> values) {
final Map<String, Object> newValues =
values.map<String, Object>((String key, Object value) {
String newKey = key;
if (!key.startsWith(_prefix)) {
newKey = '$_prefix$key';
}
return MapEntry<String, Object>(newKey, value);
});
SharedPreferencesStorePlatform.instance =
InMemorySharedPreferencesStore.withData(newValues);
_completer = null;
}
}
| packages/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart/0 | {'file_path': 'packages/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart', 'repo_id': 'packages', 'token_count': 3532} |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/shared_preferences/shared_preferences_android/example/.pluginToolsConfig.yaml/0 | {'file_path': 'packages/packages/shared_preferences/shared_preferences_android/example/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:shared_preferences_linux/shared_preferences_linux.dart';
import 'package:shared_preferences_platform_interface/types.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('SharedPreferencesLinux', () {
late SharedPreferencesLinux preferences;
const Map<String, Object> flutterTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.Bool': true,
'flutter.Int': 42,
'flutter.Double': 3.14159,
'flutter.StringList': <String>['foo', 'bar'],
};
const Map<String, Object> prefixTestValues = <String, Object>{
'prefix.String': 'hello world',
'prefix.Bool': true,
'prefix.Int': 42,
'prefix.Double': 3.14159,
'prefix.StringList': <String>['foo', 'bar'],
};
const Map<String, Object> nonPrefixTestValues = <String, Object>{
'String': 'hello world',
'Bool': true,
'Int': 42,
'Double': 3.14159,
'StringList': <String>['foo', 'bar'],
};
final Map<String, Object> allTestValues = <String, Object>{};
allTestValues.addAll(flutterTestValues);
allTestValues.addAll(prefixTestValues);
allTestValues.addAll(nonPrefixTestValues);
Future<void> addData() async {
await preferences.setValue('String', 'String', allTestValues['String']!);
await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!);
await preferences.setValue('Int', 'Int', allTestValues['Int']!);
await preferences.setValue('Double', 'Double', allTestValues['Double']!);
await preferences.setValue(
'StringList', 'StringList', allTestValues['StringList']!);
await preferences.setValue(
'String', 'prefix.String', allTestValues['prefix.String']!);
await preferences.setValue(
'Bool', 'prefix.Bool', allTestValues['prefix.Bool']!);
await preferences.setValue(
'Int', 'prefix.Int', allTestValues['prefix.Int']!);
await preferences.setValue(
'Double', 'prefix.Double', allTestValues['prefix.Double']!);
await preferences.setValue('StringList', 'prefix.StringList',
allTestValues['prefix.StringList']!);
await preferences.setValue(
'String', 'flutter.String', allTestValues['flutter.String']!);
await preferences.setValue(
'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!);
await preferences.setValue(
'Int', 'flutter.Int', allTestValues['flutter.Int']!);
await preferences.setValue(
'Double', 'flutter.Double', allTestValues['flutter.Double']!);
await preferences.setValue('StringList', 'flutter.StringList',
allTestValues['flutter.StringList']!);
}
setUp(() async {
preferences = SharedPreferencesLinux();
await addData();
});
tearDown(() async {
await preferences.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(prefix: ''),
),
);
});
testWidgets('getAll', (WidgetTester _) async {
final Map<String, Object> values = await preferences.getAll();
expect(values['flutter.String'], allTestValues['flutter.String']);
expect(values['flutter.Bool'], allTestValues['flutter.Bool']);
expect(values['flutter.Int'], allTestValues['flutter.Int']);
expect(values['flutter.Double'], allTestValues['flutter.Double']);
expect(values['flutter.StringList'], allTestValues['flutter.StringList']);
});
group('withPrefix', () {
testWidgets('remove', (WidgetTester _) async {
const String key = 'flutter.String';
await preferences.remove(key);
final Map<String, Object> values =
await preferences.getAllWithPrefix('');
expect(values[key], isNull);
});
testWidgets('clear', (WidgetTester _) async {
await preferences.clear();
final Map<String, Object> values = await preferences.getAll();
expect(values['flutter.String'], null);
expect(values['flutter.Bool'], null);
expect(values['flutter.Int'], null);
expect(values['flutter.Double'], null);
expect(values['flutter.StringList'], null);
});
testWidgets('get all with prefix', (WidgetTester _) async {
final Map<String, Object> values =
await preferences.getAllWithPrefix('prefix.');
expect(values['prefix.String'], allTestValues['prefix.String']);
expect(values['prefix.Bool'], allTestValues['prefix.Bool']);
expect(values['prefix.Int'], allTestValues['prefix.Int']);
expect(values['prefix.Double'], allTestValues['prefix.Double']);
expect(values['prefix.StringList'], allTestValues['prefix.StringList']);
});
testWidgets('getAllWithNoPrefix', (WidgetTester _) async {
final Map<String, Object> values =
await preferences.getAllWithPrefix('');
expect(values['String'], allTestValues['String']);
expect(values['Bool'], allTestValues['Bool']);
expect(values['Int'], allTestValues['Int']);
expect(values['Double'], allTestValues['Double']);
expect(values['StringList'], allTestValues['StringList']);
expect(values['flutter.String'], allTestValues['flutter.String']);
expect(values['flutter.Bool'], allTestValues['flutter.Bool']);
expect(values['flutter.Int'], allTestValues['flutter.Int']);
expect(values['flutter.Double'], allTestValues['flutter.Double']);
expect(
values['flutter.StringList'], allTestValues['flutter.StringList']);
});
testWidgets('clearWithPrefix', (WidgetTester _) async {
await preferences.clearWithPrefix('prefix.');
Map<String, Object> values =
await preferences.getAllWithPrefix('prefix.');
expect(values['prefix.String'], null);
expect(values['prefix.Bool'], null);
expect(values['prefix.Int'], null);
expect(values['prefix.Double'], null);
expect(values['prefix.StringList'], null);
values = await preferences.getAllWithPrefix('flutter.');
expect(values['flutter.String'], allTestValues['flutter.String']);
expect(values['flutter.Bool'], allTestValues['flutter.Bool']);
expect(values['flutter.Int'], allTestValues['flutter.Int']);
expect(values['flutter.Double'], allTestValues['flutter.Double']);
expect(
values['flutter.StringList'], allTestValues['flutter.StringList']);
});
testWidgets('clearWithNoPrefix', (WidgetTester _) async {
await preferences.clearWithPrefix('');
final Map<String, Object> values =
await preferences.getAllWithPrefix('');
expect(values['String'], null);
expect(values['Bool'], null);
expect(values['Int'], null);
expect(values['Double'], null);
expect(values['StringList'], null);
expect(values['flutter.String'], null);
expect(values['flutter.Bool'], null);
expect(values['flutter.Int'], null);
expect(values['flutter.Double'], null);
expect(values['flutter.StringList'], null);
});
});
group('withParameters', () {
testWidgets('remove', (WidgetTester _) async {
const String key = 'flutter.String';
await preferences.remove(key);
final Map<String, Object> values =
await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: ''),
),
);
expect(values[key], isNull);
});
testWidgets('clear', (WidgetTester _) async {
await preferences.clear();
final Map<String, Object> values = await preferences.getAll();
expect(values['flutter.String'], null);
expect(values['flutter.Bool'], null);
expect(values['flutter.Int'], null);
expect(values['flutter.Double'], null);
expect(values['flutter.StringList'], null);
});
testWidgets('get all with prefix', (WidgetTester _) async {
final Map<String, Object> values =
await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(values['prefix.String'], allTestValues['prefix.String']);
expect(values['prefix.Bool'], allTestValues['prefix.Bool']);
expect(values['prefix.Int'], allTestValues['prefix.Int']);
expect(values['prefix.Double'], allTestValues['prefix.Double']);
expect(values['prefix.StringList'], allTestValues['prefix.StringList']);
});
testWidgets('get all with allow list', (WidgetTester _) async {
final Map<String, Object> values =
await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(
prefix: 'prefix.',
allowList: <String>{'prefix.String'},
),
),
);
expect(values['prefix.String'], allTestValues['prefix.String']);
expect(values['prefix.Bool'], null);
expect(values['prefix.Int'], null);
expect(values['prefix.Double'], null);
expect(values['prefix.StringList'], null);
});
testWidgets('getAllWithNoPrefix', (WidgetTester _) async {
final Map<String, Object> values =
await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: ''),
),
);
expect(values['String'], allTestValues['String']);
expect(values['Bool'], allTestValues['Bool']);
expect(values['Int'], allTestValues['Int']);
expect(values['Double'], allTestValues['Double']);
expect(values['StringList'], allTestValues['StringList']);
expect(values['flutter.String'], allTestValues['flutter.String']);
expect(values['flutter.Bool'], allTestValues['flutter.Bool']);
expect(values['flutter.Int'], allTestValues['flutter.Int']);
expect(values['flutter.Double'], allTestValues['flutter.Double']);
expect(
values['flutter.StringList'], allTestValues['flutter.StringList']);
});
testWidgets('clearWithParameters', (WidgetTester _) async {
await preferences.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
Map<String, Object> values = await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(values['prefix.String'], null);
expect(values['prefix.Bool'], null);
expect(values['prefix.Int'], null);
expect(values['prefix.Double'], null);
expect(values['prefix.StringList'], null);
values = await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'flutter.'),
),
);
expect(values['flutter.String'], allTestValues['flutter.String']);
expect(values['flutter.Bool'], allTestValues['flutter.Bool']);
expect(values['flutter.Int'], allTestValues['flutter.Int']);
expect(values['flutter.Double'], allTestValues['flutter.Double']);
expect(
values['flutter.StringList'], allTestValues['flutter.StringList']);
});
testWidgets('clearWithParameters with allow list',
(WidgetTester _) async {
await addData();
await preferences.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(
prefix: 'prefix.',
allowList: <String>{'prefix.StringList'},
),
),
);
Map<String, Object> values = await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'prefix.'),
),
);
expect(values['prefix.String'], allTestValues['prefix.String']);
expect(values['prefix.Bool'], allTestValues['prefix.Bool']);
expect(values['prefix.Int'], allTestValues['prefix.Int']);
expect(values['prefix.Double'], allTestValues['prefix.Double']);
expect(values['prefix.StringList'], null);
values = await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: 'flutter.'),
),
);
expect(values['flutter.String'], allTestValues['flutter.String']);
expect(values['flutter.Bool'], allTestValues['flutter.Bool']);
expect(values['flutter.Int'], allTestValues['flutter.Int']);
expect(values['flutter.Double'], allTestValues['flutter.Double']);
expect(
values['flutter.StringList'], allTestValues['flutter.StringList']);
});
testWidgets('clearWithNoPrefix', (WidgetTester _) async {
await preferences.clearWithParameters(
ClearParameters(
filter: PreferencesFilter(prefix: ''),
),
);
final Map<String, Object> values =
await preferences.getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: ''),
),
);
expect(values['String'], null);
expect(values['Bool'], null);
expect(values['Int'], null);
expect(values['Double'], null);
expect(values['StringList'], null);
expect(values['flutter.String'], null);
expect(values['flutter.Bool'], null);
expect(values['flutter.Int'], null);
expect(values['flutter.Double'], null);
expect(values['flutter.StringList'], null);
});
});
});
}
| packages/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart/0 | {'file_path': 'packages/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart', 'repo_id': 'packages', 'token_count': 5724} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file exists solely to host compiled excerpts for README.md, and is not
// intended for use as an actual example application.
// ignore_for_file: avoid_print
import 'dart:typed_data';
import 'package:standard_message_codec/standard_message_codec.dart';
// #docregion Encoding
void main() {
final ByteData? data =
const StandardMessageCodec().encodeMessage(<Object, Object>{
'foo': true,
3: 'fizz',
});
print('The encoded message is $data');
}
// #enddocregion Encoding
| packages/packages/standard_message_codec/example/lib/readme_excerpts.dart/0 | {'file_path': 'packages/packages/standard_message_codec/example/lib/readme_excerpts.dart', 'repo_id': 'packages', 'token_count': 204} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/services.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'src/messages.g.dart';
/// An implementation of [UrlLauncherPlatform] for Android.
class UrlLauncherAndroid extends UrlLauncherPlatform {
/// Creates a new plugin implementation instance.
UrlLauncherAndroid({
@visibleForTesting UrlLauncherApi? api,
}) : _hostApi = api ?? UrlLauncherApi();
final UrlLauncherApi _hostApi;
/// Registers this class as the default instance of [UrlLauncherPlatform].
static void registerWith() {
UrlLauncherPlatform.instance = UrlLauncherAndroid();
}
@override
final LinkDelegate? linkDelegate = null;
@override
Future<bool> canLaunch(String url) async {
final bool canLaunchSpecificUrl = await _hostApi.canLaunchUrl(url);
if (!canLaunchSpecificUrl) {
final String scheme = _getUrlScheme(url);
// canLaunch can return false when a custom application is registered to
// handle a web URL, but the caller doesn't have permission to see what
// that handler is. If that happens, try a web URL (with the same scheme
// variant, to be safe) that should not have a custom handler. If that
// returns true, then there is a browser, which means that there is
// at least one handler for the original URL.
if (scheme == 'http' || scheme == 'https') {
return _hostApi.canLaunchUrl('$scheme://flutter.dev');
}
}
return canLaunchSpecificUrl;
}
@override
Future<void> closeWebView() {
return _hostApi.closeWebView();
}
@override
Future<bool> launch(
String url, {
required bool useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
String? webOnlyWindowName,
}) async {
return launchUrl(
url,
LaunchOptions(
mode: useWebView
? PreferredLaunchMode.inAppWebView
: PreferredLaunchMode.externalApplication,
webViewConfiguration: InAppWebViewConfiguration(
enableDomStorage: enableDomStorage,
enableJavaScript: enableJavaScript,
headers: headers)));
}
@override
Future<bool> launchUrl(String url, LaunchOptions options) async {
final bool inApp;
switch (options.mode) {
case PreferredLaunchMode.inAppWebView:
case PreferredLaunchMode.inAppBrowserView:
inApp = true;
case PreferredLaunchMode.externalApplication:
case PreferredLaunchMode.externalNonBrowserApplication:
// TODO(stuartmorgan): Add full support for
// externalNonBrowsingApplication; see
// https://github.com/flutter/flutter/issues/66721.
// Currently it's treated the same as externalApplication.
inApp = false;
case PreferredLaunchMode.platformDefault:
// Intentionally treat any new values as platformDefault; see comment in
// supportsMode.
// ignore: no_default_cases
default:
// By default, open web URLs in the application.
inApp = url.startsWith('http:') || url.startsWith('https:');
break;
}
final bool succeeded;
if (inApp) {
succeeded = await _hostApi.openUrlInApp(
url,
// Prefer custom tabs unless a webview was specifically requested.
options.mode != PreferredLaunchMode.inAppWebView,
WebViewOptions(
enableJavaScript: options.webViewConfiguration.enableJavaScript,
enableDomStorage: options.webViewConfiguration.enableDomStorage,
headers: options.webViewConfiguration.headers));
} else {
succeeded =
await _hostApi.launchUrl(url, options.webViewConfiguration.headers);
}
// TODO(stuartmorgan): Remove this special handling as part of a
// breaking change to rework failure handling across all platform. The
// current behavior is backwards compatible with the previous Java error.
if (!succeeded) {
throw PlatformException(
code: 'ACTIVITY_NOT_FOUND',
message: 'No Activity found to handle intent { $url }');
}
return succeeded;
}
@override
Future<bool> supportsMode(PreferredLaunchMode mode) async {
switch (mode) {
case PreferredLaunchMode.platformDefault:
case PreferredLaunchMode.inAppWebView:
case PreferredLaunchMode.externalApplication:
return true;
case PreferredLaunchMode.inAppBrowserView:
return _hostApi.supportsCustomTabs();
// Default is a desired behavior here since support for new modes is
// always opt-in, and the enum lives in a different package, so silently
// adding "false" for new values is the correct behavior.
// ignore: no_default_cases
default:
return false;
}
}
@override
Future<bool> supportsCloseForMode(PreferredLaunchMode mode) async {
return mode == PreferredLaunchMode.inAppWebView;
}
// Returns the part of [url] up to the first ':', or an empty string if there
// is no ':'. This deliberately does not use [Uri] to extract the scheme
// so that it works on strings that aren't actually valid URLs, since Android
// is very lenient about what it accepts for launching.
String _getUrlScheme(String url) {
final int schemeEnd = url.indexOf(':');
if (schemeEnd == -1) {
return '';
}
return url.substring(0, schemeEnd);
}
}
| packages/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart/0 | {'file_path': 'packages/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart', 'repo_id': 'packages', 'token_count': 2028} |
name: url_launcher_example
description: Demonstrates how to use the url_launcher plugin.
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
dependencies:
flutter:
sdk: flutter
url_launcher_linux:
# When depending on this package from a real application you should use:
# url_launcher_linux: ^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: ../
url_launcher_platform_interface: ^2.2.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/url_launcher/url_launcher_linux/example/pubspec.yaml/0 | {'file_path': 'packages/packages/url_launcher/url_launcher_linux/example/pubspec.yaml', 'repo_id': 'packages', 'token_count': 274} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'URL Launcher',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'URL Launcher'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<void>? _launched;
Future<void> _launchInBrowser(String url) async {
if (await UrlLauncherPlatform.instance.canLaunch(url)) {
await UrlLauncherPlatform.instance.launch(
url,
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: <String, String>{},
);
} else {
throw Exception('Could not launch $url');
}
}
Widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return const Text('');
}
}
@override
Widget build(BuildContext context) {
const String toLaunch = 'https://www.cylog.org/headers/';
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.all(16.0),
child: Text(toLaunch),
),
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchInBrowser(toLaunch);
}),
child: const Text('Launch in browser'),
),
const Padding(padding: EdgeInsets.all(16.0)),
FutureBuilder<void>(future: _launched, builder: _launchStatus),
],
),
],
),
);
}
}
| packages/packages/url_launcher/url_launcher_macos/example/lib/main.dart/0 | {'file_path': 'packages/packages/url_launcher/url_launcher_macos/example/lib/main.dart', 'repo_id': 'packages', 'token_count': 1087} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:video_player/src/closed_caption_file.dart';
void main() {
group('ClosedCaptionFile', () {
test('toString()', () {
const Caption caption = Caption(
number: 1,
start: Duration(seconds: 1),
end: Duration(seconds: 2),
text: 'caption',
);
expect(
caption.toString(),
'Caption('
'number: 1, '
'start: 0:00:01.000000, '
'end: 0:00:02.000000, '
'text: caption)');
});
});
}
| packages/packages/video_player/video_player/test/closed_caption_file_test.dart/0 | {'file_path': 'packages/packages/video_player/video_player/test/closed_caption_file_test.dart', 'repo_id': 'packages', 'token_count': 311} |
// 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:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import 'package:video_player_web/video_player_web.dart';
import 'utils.dart';
// Use WebM to allow CI to run tests in Chromium.
const String _videoAssetKey = 'assets/Butterfly-209.webm';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('VideoPlayerWeb plugin (hits network)', () {
late Future<int> textureId;
setUp(() {
VideoPlayerPlatform.instance = VideoPlayerPlugin();
textureId = VideoPlayerPlatform.instance
.create(
DataSource(
sourceType: DataSourceType.network,
uri: getUrlForAssetAsNetworkSource(_videoAssetKey),
),
)
.then((int? textureId) => textureId!);
});
testWidgets('can init', (WidgetTester tester) async {
expect(VideoPlayerPlatform.instance.init(), completes);
});
testWidgets('can create from network', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.create(
DataSource(
sourceType: DataSourceType.network,
uri: getUrlForAssetAsNetworkSource(_videoAssetKey),
),
),
completion(isNonZero));
});
testWidgets('can create from asset', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.create(
DataSource(
sourceType: DataSourceType.asset,
asset: 'videos/bee.mp4',
package: 'bee_vids',
),
),
completion(isNonZero));
});
testWidgets('cannot create from file', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.create(
DataSource(
sourceType: DataSourceType.file,
uri: '/videos/bee.mp4',
),
),
throwsUnimplementedError);
});
testWidgets('cannot create from content URI', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.create(
DataSource(
sourceType: DataSourceType.contentUri,
uri: 'content://video',
),
),
throwsUnimplementedError);
});
testWidgets('can dispose', (WidgetTester tester) async {
expect(VideoPlayerPlatform.instance.dispose(await textureId), completes);
});
testWidgets('can set looping', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.setLooping(await textureId, true),
completes,
);
});
testWidgets('can play', (WidgetTester tester) async {
// Mute video to allow autoplay (See https://goo.gl/xX8pDD)
await VideoPlayerPlatform.instance.setVolume(await textureId, 0);
expect(VideoPlayerPlatform.instance.play(await textureId), completes);
});
testWidgets('throws PlatformException when playing bad media',
(WidgetTester tester) async {
final int videoPlayerId = (await VideoPlayerPlatform.instance.create(
DataSource(
sourceType: DataSourceType.network,
uri: getUrlForAssetAsNetworkSource('assets/__non_existent.webm'),
),
))!;
final Stream<VideoEvent> eventStream =
VideoPlayerPlatform.instance.videoEventsFor(videoPlayerId);
// Mute video to allow autoplay (See https://goo.gl/xX8pDD)
await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0);
await VideoPlayerPlatform.instance.play(videoPlayerId);
expect(() async {
await eventStream.timeout(const Duration(seconds: 5)).last;
}, throwsA(isA<PlatformException>()));
});
testWidgets('can pause', (WidgetTester tester) async {
expect(VideoPlayerPlatform.instance.pause(await textureId), completes);
});
testWidgets('can set volume', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.setVolume(await textureId, 0.8),
completes,
);
});
testWidgets('can set playback speed', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.setPlaybackSpeed(await textureId, 2.0),
completes,
);
});
testWidgets('can seek to position', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.seekTo(
await textureId,
const Duration(seconds: 1),
),
completes,
);
});
testWidgets('can get position', (WidgetTester tester) async {
expect(VideoPlayerPlatform.instance.getPosition(await textureId),
completion(isInstanceOf<Duration>()));
});
testWidgets('can get video event stream', (WidgetTester tester) async {
expect(VideoPlayerPlatform.instance.videoEventsFor(await textureId),
isInstanceOf<Stream<VideoEvent>>());
});
testWidgets('can build view', (WidgetTester tester) async {
expect(VideoPlayerPlatform.instance.buildView(await textureId),
isInstanceOf<Widget>());
});
testWidgets('ignores setting mixWithOthers', (WidgetTester tester) async {
expect(VideoPlayerPlatform.instance.setMixWithOthers(true), completes);
expect(VideoPlayerPlatform.instance.setMixWithOthers(false), completes);
});
testWidgets(
'double call to play will emit a single isPlayingStateUpdate event',
(WidgetTester tester) async {
final int videoPlayerId = await textureId;
final Stream<VideoEvent> eventStream =
VideoPlayerPlatform.instance.videoEventsFor(videoPlayerId);
final Future<List<VideoEvent>> stream = eventStream.timeout(
const Duration(seconds: 2),
onTimeout: (EventSink<VideoEvent> sink) {
sink.close();
},
).toList();
await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0);
await VideoPlayerPlatform.instance.play(videoPlayerId);
await VideoPlayerPlatform.instance.play(videoPlayerId);
// Let the video play, until we stop seeing events for two seconds
final List<VideoEvent> events = await stream;
await VideoPlayerPlatform.instance.pause(videoPlayerId);
expect(
events.where((VideoEvent e) =>
e.eventType == VideoEventType.isPlayingStateUpdate),
equals(<VideoEvent>[
VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: true,
)
]));
});
testWidgets('video playback lifecycle', (WidgetTester tester) async {
final int videoPlayerId = await textureId;
final Stream<VideoEvent> eventStream =
VideoPlayerPlatform.instance.videoEventsFor(videoPlayerId);
final Future<List<VideoEvent>> stream = eventStream.timeout(
const Duration(seconds: 2),
onTimeout: (EventSink<VideoEvent> sink) {
sink.close();
},
).toList();
await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0);
await VideoPlayerPlatform.instance.play(videoPlayerId);
// Let the video play, until we stop seeing events for two seconds
final List<VideoEvent> events = await stream;
await VideoPlayerPlatform.instance.pause(videoPlayerId);
// The expected list of event types should look like this:
// 1. isPlayingStateUpdate (videoElement.onPlaying)
// 2. bufferingStart,
// 3. bufferingUpdate (videoElement.onWaiting),
// 4. initialized (videoElement.onCanPlay),
// 5. bufferingEnd (videoElement.onCanPlayThrough),
expect(
events.map((VideoEvent e) => e.eventType),
equals(<VideoEventType>[
VideoEventType.isPlayingStateUpdate,
VideoEventType.bufferingStart,
VideoEventType.bufferingUpdate,
VideoEventType.initialized,
VideoEventType.bufferingEnd,
]));
});
testWidgets('can set web options', (WidgetTester tester) async {
expect(
VideoPlayerPlatform.instance.setWebOptions(
await textureId,
const VideoPlayerWebOptions(),
),
completes,
);
});
});
}
| packages/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart/0 | {'file_path': 'packages/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart', 'repo_id': 'packages', 'token_count': 3386} |
// 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:collection/collection.dart';
import 'server.dart';
export 'src/benchmark_result.dart';
/// Returns the average of the benchmark results in [results].
///
/// Each element in [results] is expected to have identical benchmark names and
/// metrics; otherwise, an [Exception] will be thrown.
BenchmarkResults computeAverage(List<BenchmarkResults> results) {
if (results.isEmpty) {
throw ArgumentError('Cannot take average of empty list.');
}
final BenchmarkResults totalSum = results.reduce(
(BenchmarkResults sum, BenchmarkResults next) => sum._sumWith(next),
);
final BenchmarkResults average = totalSum;
for (final String benchmark in totalSum.scores.keys) {
final List<BenchmarkScore> scoresForBenchmark = totalSum.scores[benchmark]!;
for (int i = 0; i < scoresForBenchmark.length; i++) {
final BenchmarkScore score = scoresForBenchmark[i];
final double averageValue = score.value / results.length;
average.scores[benchmark]![i] =
BenchmarkScore(metric: score.metric, value: averageValue);
}
}
return average;
}
/// Computes the delta for each matching metric in [test] and [baseline], and
/// returns a new [BenchmarkResults] object where each [BenchmarkScore] contains
/// a [delta] value.
BenchmarkResults computeDelta(
BenchmarkResults baseline,
BenchmarkResults test,
) {
final Map<String, List<BenchmarkScore>> delta =
<String, List<BenchmarkScore>>{};
for (final String benchmarkName in test.scores.keys) {
final List<BenchmarkScore> testScores = test.scores[benchmarkName]!;
final List<BenchmarkScore>? baselineScores = baseline.scores[benchmarkName];
delta[benchmarkName] = testScores.map<BenchmarkScore>(
(BenchmarkScore testScore) {
final BenchmarkScore? baselineScore = baselineScores?.firstWhereOrNull(
(BenchmarkScore s) => s.metric == testScore.metric);
return testScore._copyWith(
delta: baselineScore == null
? null
: (testScore.value - baselineScore.value).toDouble(),
);
},
).toList();
}
return BenchmarkResults(delta);
}
extension _AnalysisExtension on BenchmarkResults {
/// Sums this [BenchmarkResults] instance with [other] by adding the values
/// of each matching benchmark score.
///
/// Returns a [BenchmarkResults] object with the summed values.
///
/// When [throwExceptionOnMismatch] is true (default), the set of benchmark
/// names and metric names in [other] are expected to be identical to those in
/// [scores], or else an [Exception] will be thrown.
BenchmarkResults _sumWith(
BenchmarkResults other, {
bool throwExceptionOnMismatch = true,
}) {
final Map<String, List<BenchmarkScore>> sum =
<String, List<BenchmarkScore>>{};
for (final String benchmark in scores.keys) {
// Look up this benchmark in [other].
final List<BenchmarkScore>? matchingBenchmark = other.scores[benchmark];
if (matchingBenchmark == null) {
if (throwExceptionOnMismatch) {
throw Exception(
'Cannot sum benchmarks because [other] is missing an entry for '
'benchmark "$benchmark".',
);
}
continue;
}
final List<BenchmarkScore> scoresForBenchmark = scores[benchmark]!;
sum[benchmark] =
scoresForBenchmark.map<BenchmarkScore>((BenchmarkScore score) {
// Look up this score in the [matchingBenchmark] from [other].
final BenchmarkScore? matchingScore = matchingBenchmark
.firstWhereOrNull((BenchmarkScore s) => s.metric == score.metric);
if (matchingScore == null && throwExceptionOnMismatch) {
throw Exception(
'Cannot sum benchmarks because benchmark "$benchmark" is missing '
'a score for metric ${score.metric}.',
);
}
return score._copyWith(
value: matchingScore == null
? score.value
: score.value + matchingScore.value,
);
}).toList();
}
return BenchmarkResults(sum);
}
}
extension _CopyExtension on BenchmarkScore {
BenchmarkScore _copyWith({String? metric, num? value, num? delta}) =>
BenchmarkScore(
metric: metric ?? this.metric,
value: value ?? this.value,
delta: delta ?? this.delta,
);
}
| packages/packages/web_benchmarks/lib/analysis.dart/0 | {'file_path': 'packages/packages/web_benchmarks/lib/analysis.dart', 'repo_id': 'packages', 'token_count': 1613} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show JsonEncoder;
import 'dart:io';
import 'package:test/test.dart';
import 'package:web_benchmarks/server.dart';
import 'package:web_benchmarks/src/common.dart';
Future<void> main() async {
test('Can run a web benchmark', () async {
await _runBenchmarks(
benchmarkNames: <String>['scroll', 'page', 'tap'],
entryPoint: 'lib/benchmarks/runner.dart',
);
}, timeout: Timeout.none);
test('Can run a web benchmark with an alternate initial page', () async {
await _runBenchmarks(
benchmarkNames: <String>['simple'],
entryPoint: 'lib/benchmarks/runner_simple.dart',
initialPage: 'index.html#about',
);
}, timeout: Timeout.none);
test('Can run a web benchmark with wasm', () async {
await _runBenchmarks(
benchmarkNames: <String>['simple'],
entryPoint: 'lib/benchmarks/runner_simple.dart',
compilationOptions: const CompilationOptions(useWasm: true),
);
}, timeout: Timeout.none);
}
Future<void> _runBenchmarks({
required List<String> benchmarkNames,
required String entryPoint,
String initialPage = defaultInitialPage,
CompilationOptions compilationOptions = const CompilationOptions(),
}) async {
final BenchmarkResults taskResult = await serveWebBenchmark(
benchmarkAppDirectory: Directory('testing/test_app'),
entryPoint: entryPoint,
treeShakeIcons: false,
initialPage: initialPage,
compilationOptions: compilationOptions,
);
for (final String benchmarkName in benchmarkNames) {
for (final String metricName in <String>[
'preroll_frame',
'apply_frame',
'drawFrameDuration',
]) {
for (final String valueName in <String>[
'average',
'outlierAverage',
'outlierRatio',
'noise',
]) {
expect(
taskResult.scores[benchmarkName]!.where((BenchmarkScore score) =>
score.metric == '$metricName.$valueName'),
hasLength(1),
);
}
}
expect(
taskResult.scores[benchmarkName]!.where(
(BenchmarkScore score) => score.metric == 'totalUiFrame.average'),
hasLength(1),
);
}
expect(
const JsonEncoder.withIndent(' ').convert(taskResult.toJson()),
isA<String>(),
);
}
| packages/packages/web_benchmarks/testing/web_benchmarks_test.dart/0 | {'file_path': 'packages/packages/web_benchmarks/testing/web_benchmarks_test.dart', 'repo_id': 'packages', 'token_count': 895} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:webview_flutter/webview_flutter.dart' as main_file;
void main() {
group('webview_flutter', () {
test('ensure webview_flutter.dart exports classes from platform interface',
() {
// ignore: unnecessary_statements
main_file.JavaScriptConsoleMessage;
// ignore: unnecessary_statements
main_file.JavaScriptLogLevel;
// ignore: unnecessary_statements
main_file.JavaScriptMessage;
// ignore: unnecessary_statements
main_file.JavaScriptMode;
// ignore: unnecessary_statements
main_file.LoadRequestMethod;
// ignore: unnecessary_statements
main_file.NavigationDecision;
// ignore: unnecessary_statements
main_file.NavigationRequest;
// ignore: unnecessary_statements
main_file.NavigationRequestCallback;
// ignore: unnecessary_statements
main_file.PageEventCallback;
// ignore: unnecessary_statements
main_file.PlatformNavigationDelegateCreationParams;
// ignore: unnecessary_statements
main_file.PlatformWebViewControllerCreationParams;
// ignore: unnecessary_statements
main_file.PlatformWebViewCookieManagerCreationParams;
// ignore: unnecessary_statements
main_file.PlatformWebViewPermissionRequest;
// ignore: unnecessary_statements
main_file.PlatformWebViewWidgetCreationParams;
// ignore: unnecessary_statements
main_file.ProgressCallback;
// ignore: unnecessary_statements
main_file.WebViewPermissionResourceType;
// ignore: unnecessary_statements
main_file.WebResourceError;
// ignore: unnecessary_statements
main_file.WebResourceErrorCallback;
// ignore: unnecessary_statements
main_file.WebViewCookie;
// ignore: unnecessary_statements
main_file.WebResourceErrorType;
// ignore: unnecessary_statements
main_file.UrlChange;
});
});
}
| packages/packages/webview_flutter/webview_flutter/test/webview_flutter_test.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter/test/webview_flutter_test.dart', 'repo_id': 'packages', 'token_count': 746} |
// 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 'webview_credential.dart';
/// Defines the parameters of a pending HTTP authentication request received by
/// the webview through a [HttpAuthRequestCallback].
///
/// Platform specific implementations can add additional fields by extending
/// this class and providing a factory method that takes the [HttpAuthRequest]
/// as a parameter.
///
/// This example demonstrates how to extend the [HttpAuthRequest] to provide
/// additional platform specific parameters.
///
/// When extending [HttpAuthRequest], additional parameters should always accept
/// `null` or have a default value to prevent breaking changes.
///
/// ```dart
/// @immutable
/// class WKWebViewHttpAuthRequest extends HttpAuthRequest {
/// WKWebViewHttpAuthRequest._(
/// HttpAuthRequest authRequest,
/// this.extraData,
/// ) : super(
/// onProceed: authRequest.onProceed,
/// onCancel: authRequest.onCancel,
/// host: authRequest.host,
/// realm: authRequest.realm,
/// );
///
/// factory WKWebViewHttpAuthRequest.fromHttpAuthRequest(
/// HttpAuthRequest authRequest, {
/// String? extraData,
/// }) {
/// return WKWebViewHttpAuthRequest._(
/// authRequest,
/// extraData: extraData,
/// );
/// }
///
/// final String? extraData;
/// }
/// ```
@immutable
class HttpAuthRequest {
/// Creates a [HttpAuthRequest].
const HttpAuthRequest({
required this.onProceed,
required this.onCancel,
required this.host,
this.realm,
});
/// The callback to authenticate.
final void Function(WebViewCredential credential) onProceed;
/// The callback to cancel authentication.
final void Function() onCancel;
/// The host requiring authentication.
final String host;
/// The realm requiring authentication.
final String? realm;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_auth_request.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_auth_request.dart', 'repo_id': 'packages', 'token_count': 604} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export 'http_auth_request.dart';
export 'http_response_error.dart';
export 'javascript_console_message.dart';
export 'javascript_dialog_request.dart';
export 'javascript_log_level.dart';
export 'javascript_message.dart';
export 'javascript_mode.dart';
export 'load_request_params.dart';
export 'navigation_decision.dart';
export 'navigation_request.dart';
export 'platform_navigation_delegate_creation_params.dart';
export 'platform_webview_controller_creation_params.dart';
export 'platform_webview_cookie_manager_creation_params.dart';
export 'platform_webview_permission_request.dart';
export 'platform_webview_widget_creation_params.dart';
export 'scroll_position_change.dart';
export 'url_change.dart';
export 'web_resource_error.dart';
export 'web_resource_request.dart';
export 'web_resource_response.dart';
export 'webview_cookie.dart';
export 'webview_credential.dart';
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/types.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/types.dart', 'repo_id': 'packages', 'token_count': 327} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'webview_platform_test.mocks.dart';
void main() {
setUp(() {
WebViewPlatform.instance = MockWebViewPlatformWithMixin();
});
test('Cannot be implemented with `implements`', () {
const PlatformNavigationDelegateCreationParams params =
PlatformNavigationDelegateCreationParams();
when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params))
.thenReturn(ImplementsPlatformNavigationDelegate());
expect(() {
PlatformNavigationDelegate(params);
// In versions of `package:plugin_platform_interface` prior to fixing
// https://github.com/flutter/flutter/issues/109339, an attempt to
// implement a platform interface using `implements` would sometimes throw
// a `NoSuchMethodError` and other times throw an `AssertionError`. After
// the issue is fixed, an `AssertionError` will always be thrown. For the
// purpose of this test, we don't really care what exception is thrown, so
// just allow any exception.
}, throwsA(anything));
});
test('Can be extended', () {
const PlatformNavigationDelegateCreationParams params =
PlatformNavigationDelegateCreationParams();
when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params))
.thenReturn(ExtendsPlatformNavigationDelegate(params));
expect(PlatformNavigationDelegate(params), isNotNull);
});
test('Can be mocked with `implements`', () {
const PlatformNavigationDelegateCreationParams params =
PlatformNavigationDelegateCreationParams();
when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params))
.thenReturn(MockNavigationDelegate());
expect(PlatformNavigationDelegate(params), isNotNull);
});
test(
'Default implementation of setOnNavigationRequest should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnNavigationRequest(
(NavigationRequest navigationRequest) => NavigationDecision.navigate),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnPageStarted should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnPageStarted((String url) {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnPageFinished should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnPageFinished((String url) {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnHttpError should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnHttpError((HttpResponseError error) {}),
throwsUnimplementedError,
);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of setOnProgress should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnProgress((int progress) {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnWebResourceError should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnWebResourceError((WebResourceError error) {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnUrlChange should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnUrlChange((UrlChange change) {}),
throwsUnimplementedError,
);
});
test(
'Default implementation of setOnHttpAuthRequest should throw unimplemented error',
() {
final PlatformNavigationDelegate callbackDelegate =
ExtendsPlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams());
expect(
() => callbackDelegate.setOnHttpAuthRequest((HttpAuthRequest request) {}),
throwsUnimplementedError,
);
});
}
class MockWebViewPlatformWithMixin extends MockWebViewPlatform
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin {}
class ImplementsPlatformNavigationDelegate
implements PlatformNavigationDelegate {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class MockNavigationDelegate extends Mock
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin
implements
PlatformNavigationDelegate {}
class ExtendsPlatformNavigationDelegate extends PlatformNavigationDelegate {
ExtendsPlatformNavigationDelegate(super.params) : super.implementation();
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart/0 | {'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart', 'repo_id': 'packages', 'token_count': 2017} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
/// Returns a [File] created by appending all but the last item in [components]
/// to [base] as subdirectories, then appending the last as a file.
///
/// Example:
/// childFileWithSubcomponents(rootDir, ['foo', 'bar', 'baz.txt'])
/// creates a File representing /rootDir/foo/bar/baz.txt.
File childFileWithSubcomponents(Directory base, List<String> components) {
final String basename = components.removeLast();
return childDirectoryWithSubcomponents(base, components).childFile(basename);
}
/// Returns a [Directory] created by appending everything in [components]
/// to [base] as subdirectories.
///
/// Example:
/// childFileWithSubcomponents(rootDir, ['foo', 'bar'])
/// creates a File representing /rootDir/foo/bar/.
Directory childDirectoryWithSubcomponents(
Directory base, List<String> components) {
Directory dir = base;
for (final String directoryName in components) {
dir = dir.childDirectory(directoryName);
}
return dir;
}
| packages/script/tool/lib/src/common/file_utils.dart/0 | {'file_path': 'packages/script/tool/lib/src/common/file_utils.dart', 'repo_id': 'packages', 'token_count': 337} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:yaml/yaml.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/repository_package.dart';
/// A command to verify Dependabot configuration coverage of packages.
class DependabotCheckCommand extends PackageLoopingCommand {
/// Creates Dependabot check command instance.
DependabotCheckCommand(super.packagesDir, {super.gitDir}) {
argParser.addOption(_configPathFlag,
help: 'Path to the Dependabot configuration file',
defaultsTo: '.github/dependabot.yml');
}
static const String _configPathFlag = 'config';
late Directory _repoRoot;
// The set of directories covered by "gradle" entries in the config.
Set<String> _gradleDirs = const <String>{};
@override
final String name = 'dependabot-check';
@override
List<String> get aliases => <String>['check-dependabot'];
@override
final String description =
'Checks that all packages have Dependabot coverage.';
@override
final PackageLoopingType packageLoopingType =
PackageLoopingType.includeAllSubpackages;
@override
final bool hasLongOutput = false;
@override
Future<void> initializeRun() async {
_repoRoot = packagesDir.fileSystem.directory((await gitDir).path);
final YamlMap config = loadYaml(_repoRoot
.childFile(getStringArg(_configPathFlag))
.readAsStringSync()) as YamlMap;
final dynamic entries = config['updates'];
if (entries is! YamlList) {
return;
}
const String typeKey = 'package-ecosystem';
const String dirKey = 'directory';
_gradleDirs = entries
.cast<YamlMap>()
.where((YamlMap entry) => entry[typeKey] == 'gradle')
.map((YamlMap entry) => entry[dirKey] as String)
.toSet();
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
bool skipped = true;
final List<String> errors = <String>[];
final RunState gradleState = _validateDependabotGradleCoverage(package);
skipped = skipped && gradleState == RunState.skipped;
if (gradleState == RunState.failed) {
printError('${indentation}Missing Gradle coverage.');
errors.add('Missing Gradle coverage');
}
// TODO(stuartmorgan): Add other ecosystem checks here as more are enabled.
if (skipped) {
return PackageResult.skip('No supported package ecosystems');
}
return errors.isEmpty
? PackageResult.success()
: PackageResult.fail(errors);
}
/// Returns the state for the Dependabot coverage of the Gradle ecosystem for
/// [package]:
/// - succeeded if it includes gradle and is covered.
/// - failed if it includes gradle and is not covered.
/// - skipped if it doesn't include gradle.
RunState _validateDependabotGradleCoverage(RepositoryPackage package) {
final Directory androidDir =
package.platformDirectory(FlutterPlatform.android);
final Directory appDir = androidDir.childDirectory('app');
if (appDir.existsSync()) {
// It's an app, so only check for the app directory to be covered.
final String dependabotPath =
'/${getRelativePosixPath(appDir, from: _repoRoot)}';
return _gradleDirs.contains(dependabotPath)
? RunState.succeeded
: RunState.failed;
} else if (androidDir.existsSync()) {
// It's a library, so only check for the android directory to be covered.
final String dependabotPath =
'/${getRelativePosixPath(androidDir, from: _repoRoot)}';
return _gradleDirs.contains(dependabotPath)
? RunState.succeeded
: RunState.failed;
}
return RunState.skipped;
}
}
| packages/script/tool/lib/src/dependabot_check_command.dart/0 | {'file_path': 'packages/script/tool/lib/src/dependabot_check_command.dart', 'repo_id': 'packages', 'token_count': 1336} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/gradle.dart';
import 'package:test/test.dart';
import '../mocks.dart';
import '../util.dart';
void main() {
late FileSystem fileSystem;
late RecordingProcessRunner processRunner;
setUp(() {
fileSystem = MemoryFileSystem();
processRunner = RecordingProcessRunner();
});
group('isConfigured', () {
test('reports true when configured on Windows', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/gradlew.bat']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isWindows: true),
);
expect(project.isConfigured(), true);
});
test('reports true when configured on non-Windows', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/gradlew']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isMacOS: true),
);
expect(project.isConfigured(), true);
});
test('reports false when not configured on Windows', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/foo']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isWindows: true),
);
expect(project.isConfigured(), false);
});
test('reports true when configured on non-Windows', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/foo']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isMacOS: true),
);
expect(project.isConfigured(), false);
});
});
group('runCommand', () {
test('runs without arguments', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/gradlew']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isMacOS: true),
);
final int exitCode = await project.runCommand('foo');
expect(exitCode, 0);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
plugin
.platformDirectory(FlutterPlatform.android)
.childFile('gradlew')
.path,
const <String>[
'foo',
],
plugin.platformDirectory(FlutterPlatform.android).path),
]));
});
test('runs with arguments', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/gradlew']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isMacOS: true),
);
final int exitCode = await project.runCommand(
'foo',
arguments: <String>['--bar', '--baz'],
);
expect(exitCode, 0);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
plugin
.platformDirectory(FlutterPlatform.android)
.childFile('gradlew')
.path,
const <String>[
'foo',
'--bar',
'--baz',
],
plugin.platformDirectory(FlutterPlatform.android).path),
]));
});
test('runs with the correct wrapper on Windows', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/gradlew.bat']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isWindows: true),
);
final int exitCode = await project.runCommand('foo');
expect(exitCode, 0);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
plugin
.platformDirectory(FlutterPlatform.android)
.childFile('gradlew.bat')
.path,
const <String>[
'foo',
],
plugin.platformDirectory(FlutterPlatform.android).path),
]));
});
test('returns error codes', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin', fileSystem.directory('/'),
extraFiles: <String>['android/gradlew.bat']);
final GradleProject project = GradleProject(
plugin,
processRunner: processRunner,
platform: MockPlatform(isWindows: true),
);
processRunner.mockProcessesForExecutable[project.gradleWrapper.path] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1)),
];
final int exitCode = await project.runCommand('foo');
expect(exitCode, 1);
});
});
}
| packages/script/tool/test/common/gradle_test.dart/0 | {'file_path': 'packages/script/tool/test/common/gradle_test.dart', 'repo_id': 'packages', 'token_count': 2487} |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/common/plugin_utils.dart';
import 'package:flutter_plugin_tools/src/readme_check_command.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
late CommandRunner<void> runner;
late RecordingProcessRunner processRunner;
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = fileSystem.currentDirectory.childDirectory('packages');
createPackagesDirectory(parentDir: packagesDir.parent);
processRunner = RecordingProcessRunner();
final ReadmeCheckCommand command = ReadmeCheckCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner = CommandRunner<void>(
'readme_check_command', 'Test for readme_check_command');
runner.addCommand(command);
});
test('prints paths of checked READMEs', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
examples: <String>['example1', 'example2']);
for (final RepositoryPackage example in package.getExamples()) {
example.readmeFile.writeAsStringSync('A readme');
}
getExampleDir(package).childFile('README.md').writeAsStringSync('A readme');
final List<String> output =
await runCapturingPrint(runner, <String>['readme-check']);
expect(
output,
containsAll(<Matcher>[
contains(' Checking README.md...'),
contains(' Checking example/README.md...'),
contains(' Checking example/example1/README.md...'),
contains(' Checking example/example2/README.md...'),
]),
);
});
test('fails when package README is missing', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.deleteSync();
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Missing README.md'),
]),
);
});
test('passes when example README is missing', () async {
createFakePackage('a_package', packagesDir);
final List<String> output =
await runCapturingPrint(runner, <String>['readme-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No README for example'),
]),
);
});
test('does not inculde non-example subpackages', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
const String subpackageName = 'special_test';
final RepositoryPackage miscSubpackage =
createFakePackage(subpackageName, package.directory);
miscSubpackage.readmeFile.deleteSync();
final List<String> output =
await runCapturingPrint(runner, <String>['readme-check']);
expect(output, isNot(contains(subpackageName)));
});
test('fails when README still has plugin template boilerplate', () async {
final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir);
package.readmeFile.writeAsStringSync('''
## Getting Started
This project is a starting point for a Flutter
[plug-in package](https://flutter.dev/developing-packages/),
a specialized package that includes platform-specific implementation code for
Android and/or iOS.
For help getting started with Flutter development, view the
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The boilerplate section about getting started with Flutter '
'should not be left in.'),
contains('Contains template boilerplate'),
]),
);
});
test('fails when example README still has application template boilerplate',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.getExamples().first.readmeFile.writeAsStringSync('''
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The boilerplate section about getting started with Flutter '
'should not be left in.'),
contains('Contains template boilerplate'),
]),
);
});
test(
'fails when a plugin implementation package example README has the '
'template boilerplate', () async {
final RepositoryPackage package = createFakePlugin(
'a_plugin_ios', packagesDir.childDirectory('a_plugin'));
package.getExamples().first.readmeFile.writeAsStringSync('''
# a_plugin_ios_example
Demonstrates how to use the a_plugin_ios plugin.
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The boilerplate should not be left in for a federated plugin '
"implementation package's example."),
contains('Contains template boilerplate'),
]),
);
});
test(
'allows the template boilerplate in the example README for packages '
'other than plugin implementation packages', () async {
final RepositoryPackage package = createFakePlugin(
'a_plugin',
packagesDir.childDirectory('a_plugin'),
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
},
);
// Write a README with an OS support table so that the main README check
// passes.
package.readmeFile.writeAsStringSync('''
# a_plugin
| | Android |
|----------------|---------|
| **Support** | SDK 19+ |
A great plugin.
''');
package.getExamples().first.readmeFile.writeAsStringSync('''
# a_plugin_example
Demonstrates how to use the a_plugin plugin.
''');
final List<String> output =
await runCapturingPrint(runner, <String>['readme-check']);
expect(
output,
containsAll(<Matcher>[
contains(' Checking README.md...'),
contains(' Checking example/README.md...'),
]),
);
});
test(
'fails when a plugin implementation package example README does not have '
'the repo-standard message', () async {
final RepositoryPackage package = createFakePlugin(
'a_plugin_ios', packagesDir.childDirectory('a_plugin'));
package.getExamples().first.readmeFile.writeAsStringSync('''
# a_plugin_ios_example
Some random description.
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The example README for a platform implementation package '
'should warn readers about its intended use. Please copy the '
'example README from another implementation package in this '
'repository.'),
contains('Missing implementation package example warning'),
]),
);
});
test('passes for a plugin implementation package with the expected content',
() async {
final RepositoryPackage package = createFakePlugin(
'a_plugin',
packagesDir.childDirectory('a_plugin'),
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
},
);
// Write a README with an OS support table so that the main README check
// passes.
package.readmeFile.writeAsStringSync('''
# a_plugin
| | Android |
|----------------|---------|
| **Support** | SDK 19+ |
A great plugin.
''');
package.getExamples().first.readmeFile.writeAsStringSync('''
# Platform Implementation Test App
This is a test app for manual testing and automated integration testing
of this platform implementation. It is not intended to demonstrate actual use of
this package, since the intent is that plugin clients use the app-facing
package.
Unless you are making changes to this implementation package, this example is
very unlikely to be relevant.
''');
final List<String> output =
await runCapturingPrint(runner, <String>['readme-check']);
expect(
output,
containsAll(<Matcher>[
contains(' Checking README.md...'),
contains(' Checking example/README.md...'),
]),
);
});
test(
'fails when multi-example top-level example directory README still has '
'application template boilerplate', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
examples: <String>['example1', 'example2']);
package.directory
.childDirectory('example')
.childFile('README.md')
.writeAsStringSync('''
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The boilerplate section about getting started with Flutter '
'should not be left in.'),
contains('Contains template boilerplate'),
]),
);
});
group('plugin OS support', () {
test(
'does not check support table for anything other than app-facing plugin packages',
() async {
const String federatedPluginName = 'a_federated_plugin';
final Directory federatedDir =
packagesDir.childDirectory(federatedPluginName);
// A non-plugin package.
createFakePackage('a_package', packagesDir);
// Non-app-facing parts of a federated plugin.
createFakePlugin(
'${federatedPluginName}_platform_interface', federatedDir);
createFakePlugin('${federatedPluginName}_android', federatedDir);
final List<String> output = await runCapturingPrint(runner, <String>[
'readme-check',
]);
expect(
output,
containsAll(<Matcher>[
contains('Running for a_package...'),
contains('Running for a_federated_plugin_platform_interface...'),
contains('Running for a_federated_plugin_android...'),
contains('No issues found!'),
]),
);
});
test('fails when non-federated plugin is missing an OS support table',
() async {
createFakePlugin('a_plugin', packagesDir);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No OS support table found'),
]),
);
});
test(
'fails when app-facing part of a federated plugin is missing an OS support table',
() async {
createFakePlugin('a_plugin', packagesDir.childDirectory('a_plugin'));
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No OS support table found'),
]),
);
});
test('fails the OS support table is missing the header', () async {
final RepositoryPackage plugin =
createFakePlugin('a_plugin', packagesDir);
plugin.readmeFile.writeAsStringSync('''
A very useful plugin.
| **Support** | SDK 21+ | iOS 10+* | [See `camera_web `][1] |
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('OS support table does not have the expected header format'),
]),
);
});
test('fails if the OS support table is missing a supported OS', () async {
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
plugin.readmeFile.writeAsStringSync('''
A very useful plugin.
| | Android | iOS |
|----------------|---------|----------|
| **Support** | SDK 21+ | iOS 10+* |
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(' OS support table does not match supported platforms:\n'
' Actual: android, ios, web\n'
' Documented: android, ios'),
contains('Incorrect OS support table'),
]),
);
});
test('fails if the OS support table lists an extra OS', () async {
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
},
);
plugin.readmeFile.writeAsStringSync('''
A very useful plugin.
| | Android | iOS | Web |
|----------------|---------|----------|------------------------|
| **Support** | SDK 21+ | iOS 10+* | [See `camera_web `][1] |
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(' OS support table does not match supported platforms:\n'
' Actual: android, ios\n'
' Documented: android, ios, web'),
contains('Incorrect OS support table'),
]),
);
});
test('fails if the OS support table has unexpected OS formatting',
() async {
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
platformMacOS: const PlatformDetails(PlatformSupport.inline),
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
plugin.readmeFile.writeAsStringSync('''
A very useful plugin.
| | android | ios | MacOS | web |
|----------------|---------|----------|-------|------------------------|
| **Support** | SDK 21+ | iOS 10+* | 10.11 | [See `camera_web `][1] |
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(' Incorrect OS capitalization: android, ios, MacOS, web\n'
' Please use standard capitalizations: Android, iOS, macOS, Web\n'),
contains('Incorrect OS support formatting'),
]),
);
});
});
group('code blocks', () {
test('fails on missing info string', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
Example:
```
void main() {
// ...
}
```
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Code block at line 3 is missing a language identifier.'),
contains('Missing language identifier for code block'),
]),
);
});
test('allows unknown info strings', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
Example:
```someunknowninfotag
A B C
```
''');
final List<String> output = await runCapturingPrint(runner, <String>[
'readme-check',
]);
expect(
output,
containsAll(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('allows space around info strings', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
Example:
``` dart
A B C
```
''');
final List<String> output = await runCapturingPrint(runner, <String>[
'readme-check',
]);
expect(
output,
containsAll(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('passes when excerpt requirement is met', () async {
final RepositoryPackage package = createFakePackage(
'a_package',
packagesDir,
);
package.readmeFile.writeAsStringSync('''
Example:
<?code-excerpt "main.dart (SomeSection)"?>
```dart
A B C
```
''');
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check', '--require-excerpts']);
expect(
output,
containsAll(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('fails on missing excerpt tag when requested', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
Example:
```dart
A B C
```
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['readme-check', '--require-excerpts'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Dart code block at line 3 is not managed by code-excerpt.'),
// Ensure that the failure message links to instructions.
contains(
'https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages'),
contains('Missing code-excerpt management for code block'),
]),
);
});
});
}
| packages/script/tool/test/readme_check_command_test.dart/0 | {'file_path': 'packages/script/tool/test/readme_check_command_test.dart', 'repo_id': 'packages', 'token_count': 8065} |
import 'dart:io';
import 'package:args/args.dart';
import 'package:pana/src/license_detection/license_detector.dart';
/// A command line program to use access the license detector.
///
/// The program take two parameters `--path` and `--threshold`.
/// If threshold is not provided it defaults to `0.9`.
void main(List<String> arguments) async {
final parser = ArgParser();
parser.addOption('path');
parser.addOption('threshold');
var argResults = parser.parse(arguments);
var threshold = argResults['threshold'] ?? 0.9;
var path = argResults['path'];
if (path == null) {
print('Path not specified');
return;
}
final file = File(path as String);
var content = await file.readAsString();
final detectionResult = await detectLicense(content, threshold as double);
if (detectionResult.matches.isEmpty) {
print('No license found in the given file');
} else {
var i = 1;
print(
'unclaimedTokenPercentage: ${detectionResult.unclaimedTokenPercentage}');
print(
'longestUnclaimedTokenCount: ${detectionResult.longestUnclaimedTokenCount}');
for (var match in detectionResult.matches) {
print('\nDetection result $i: ');
print('Spdx identifier: ${match.identifier}');
print('Confidence: ${match.confidence}');
print('Start Offset: ${match.start} End offset: ${match.end}');
}
}
}
| pana/bin/license_detector_bin.dart/0 | {'file_path': 'pana/bin/license_detector_bin.dart', 'repo_id': 'pana', 'token_count': 456} |
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
import 'package:pub_semver/pub_semver.dart';
class VersionConverter implements JsonConverter<Version?, String?> {
const VersionConverter();
@override
Version? fromJson(String? json) => json == null ? null : Version.parse(json);
@override
String? toJson(Version? object) => object?.toString();
}
| pana/lib/src/json_converters.dart/0 | {'file_path': 'pana/lib/src/json_converters.dart', 'repo_id': 'pana', 'token_count': 175} |
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as path;
import 'download_utils.dart';
import 'internal_model.dart';
import 'license.dart';
import 'logging.dart';
import 'maintenance.dart';
import 'messages.dart';
import 'model.dart';
import 'package_context.dart';
import 'pubspec.dart';
import 'report/create_report.dart';
import 'sdk_env.dart';
import 'tag/tagger.dart';
import 'utils.dart';
class InspectOptions {
final String? pubHostedUrl;
final String? dartdocOutputDir;
final int dartdocRetry;
final Duration? dartdocTimeout;
final bool isInternal;
final int? lineLength;
/// The analysis options (in yaml format) to use for the analysis.
final String? analysisOptionsYaml;
InspectOptions({
this.pubHostedUrl,
this.dartdocOutputDir,
this.dartdocRetry = 0,
this.dartdocTimeout,
this.isInternal = false,
this.lineLength,
this.analysisOptionsYaml,
});
}
class PackageAnalyzer {
final ToolEnvironment _toolEnv;
final UrlChecker _urlChecker;
PackageAnalyzer(this._toolEnv, {UrlChecker? urlChecker})
: _urlChecker = urlChecker ?? UrlChecker();
static Future<PackageAnalyzer> create({
String? sdkDir,
String? flutterDir,
String? pubCacheDir,
String? pubHostedUrl,
}) async {
return PackageAnalyzer(await ToolEnvironment.create(
dartSdkDir: sdkDir,
flutterSdkDir: flutterDir,
pubCacheDir: pubCacheDir,
environment: <String, String>{
if (pubHostedUrl != null) 'PUB_HOSTED_URL': pubHostedUrl,
}));
}
Future<Summary> inspectPackage(
String package, {
String? version,
InspectOptions? options,
Logger? logger,
}) async {
options ??= InspectOptions();
return withLogger(() async {
return withTempDir((tempDir) async {
await downloadPackage(package, version,
destination: tempDir, pubHostedUrl: options!.pubHostedUrl);
return await _inspect(tempDir, options);
});
}, logger: logger);
}
Future<Summary> inspectDir(String packageDir, {InspectOptions? options}) {
options ??= InspectOptions();
return withTempDir((tempDir) async {
final rootDir = await _detectGitRoot(packageDir) ?? packageDir;
await _copy(rootDir, tempDir);
final relativeDir = path.relative(packageDir, from: rootDir);
return await _inspect(path.join(tempDir, relativeDir), options!);
});
}
Future<Summary> _inspect(String pkgDir, InspectOptions options) async {
final context = PackageContext(
toolEnvironment: _toolEnv,
packageDir: pkgDir,
options: options,
urlChecker: _urlChecker,
);
final dartFiles = <String>[];
final fileList = listFiles(pkgDir, deleteBadExtracted: true);
await for (final file in fileList) {
final isInBin = path.isWithin('bin', file);
final isInLib = path.isWithin('lib', file);
final isDart = file.endsWith('.dart');
if (isDart && (isInLib || isInBin)) {
dartFiles.add(file);
}
}
Pubspec? pubspec;
try {
pubspec = context.pubspec;
} catch (e, st) {
log.info('Unable to read pubspec.yaml', e, st);
return Summary(
runtimeInfo: _toolEnv.runtimeInfo,
packageName: null,
packageVersion: null,
pubspec: pubspec,
allDependencies: null,
licenseFile: null,
tags: null,
report: null,
errorMessage: pubspecParseError(e),
);
}
if (pubspec.hasUnknownSdks) {
context.errors.add('The following unknown SDKs are in `pubspec.yaml`:\n'
' `${pubspec.unknownSdks}`.\n\n'
'`pana` doesn’t recognize them; please remove the `sdk` entry or '
'[report the issue](https://github.com/dart-lang/pana/issues).');
}
final pkgResolution = await context.resolveDependencies();
if (pkgResolution != null && options.dartdocOutputDir != null) {
for (var i = 0; i <= options.dartdocRetry; i++) {
try {
final r = await _toolEnv.dartdoc(
pkgDir,
options.dartdocOutputDir!,
validateLinks: i == 0,
timeout: options.dartdocTimeout,
);
if (!r.wasTimeout) {
break;
}
} catch (e, st) {
log.severe('Could not run dartdoc.', e, st);
}
}
}
final tags = <String>[];
if (pkgResolution != null) {
List<CodeProblem>? analyzerItems;
if (dartFiles.isNotEmpty) {
try {
analyzerItems = await context.staticAnalysis();
} on ToolException catch (e) {
context.errors
.add(runningDartanalyzerFailed(context.usesFlutter, e.message));
}
} else {
analyzerItems = <CodeProblem>[];
}
if (analyzerItems != null && !analyzerItems.any((item) => item.isError)) {
final tagger = Tagger(pkgDir);
final explanations = <Explanation>[];
tagger.sdkTags(tags, explanations);
tagger.platformTags(tags, explanations);
tagger.runtimeTags(tags, explanations);
tagger.flutterPluginTags(tags, explanations);
tagger.nullSafetyTags(tags, explanations);
}
}
final licenseFile = await detectLicenseInDir(pkgDir);
final errorMessage = context.errors.isEmpty
? null
: context.errors.map((e) => e.trim()).join('\n\n');
return Summary(
runtimeInfo: _toolEnv.runtimeInfo,
packageName: pubspec.name,
packageVersion: pubspec.version,
pubspec: pubspec,
allDependencies:
pkgResolution?.dependencies.map((d) => d.package).toList(),
licenseFile: licenseFile,
tags: tags,
report: await createReport(context),
urlProblems: context.urlProblems.entries
.map((e) => UrlProblem(url: e.key, problem: e.value))
.toList()
..sort((a, b) => a.url.compareTo(b.url)),
errorMessage: errorMessage,
);
}
}
Future<String?> _detectGitRoot(String packageDir) async {
final pr = await runProc(
['git', 'rev-parse', '--show-toplevel'],
workingDirectory: packageDir,
);
if (pr.exitCode == 0) {
return pr.stdout.toString().trim();
}
return null;
}
Future<void> _copy(String from, String to) async {
await for (final fse in Directory(from).list(recursive: true)) {
if (fse is File) {
final relativePath = path.relative(fse.path, from: from);
final newFile = File(path.join(to, relativePath));
await newFile.parent.create(recursive: true);
await fse.copy(newFile.path);
} else if (fse is Link) {
final relativePath = path.relative(fse.path, from: from);
final linkTarget = await fse.target();
final newLink = Link(path.join(to, relativePath));
await newLink.parent.create(recursive: true);
await newLink.create(linkTarget);
}
}
}
| pana/lib/src/package_analyzer.dart/0 | {'file_path': 'pana/lib/src/package_analyzer.dart', 'repo_id': 'pana', 'token_count': 2913} |
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:path/path.dart' as path;
import '../logging.dart';
import '../pubspec.dart';
import '../pubspec_io.dart' show pubspecFromDir;
import '_common.dart';
abstract class DirectedGraph<T> {
Set<T> directSuccessors(T t);
}
/// Remembers parsed pubspecs.
///
/// Maps between library Uri's and package directories.
class PubspecCache {
final AnalysisSession _analysisSession;
final _pubspecs = <String, Pubspec>{};
PubspecCache(this._analysisSession);
String _packageDir(String packageName) {
final packageUri = Uri.parse('package:$packageName/');
final filePath = _analysisSession.uriConverter.uriToPath(packageUri);
// Could not resolve uri.
// Probably a missing/broken dependency.
if (filePath == null) {
throw TagException('Could not find package dir of $packageName');
}
return path.dirname(filePath);
}
String packageName(Uri uri) {
if (uri.scheme != 'package') {
// We only resolve package: uris.
throw ArgumentError('Trying to get the package name of $uri');
}
return uri.pathSegments.first;
}
Pubspec pubspecOfLibrary(Uri uri) {
return pubspecOfPackage(packageName(uri));
}
Pubspec pubspecOfPackage(String packageName) {
return _pubspecs.putIfAbsent(packageName, () {
try {
return pubspecFromDir(_packageDir(packageName));
} on Exception catch (e) {
throw TagException(e.toString());
}
});
}
}
/// A graph of import/export dependencies for libraries under some configuration
/// of declared variables.
class LibraryGraph implements DirectedGraph<Uri> {
final AnalysisSession _analysisSession;
final Map<String, String> _declaredVariables;
final Map<Uri, Set<Uri>> _cache = <Uri, Set<Uri>>{};
final bool Function(Uri) _isLeaf;
LibraryGraph(
this._analysisSession,
this._declaredVariables, {
bool Function(Uri) isLeaf = _constantFalse,
}) : _isLeaf = isLeaf;
/// The direct successors of the library [uri] are the libraries imported or
/// exported by that library.
///
/// Part files have no successors.
///
/// For the purposes of our analysis `dart:` and `dart-ext:` libraries have no
/// successors.
///
/// For the purposes of our analysis any library in package:flutter has
/// `dart:ui` as their only successor.
@override
Set<Uri> directSuccessors(Uri uri) {
try {
return _cache.putIfAbsent(uri, () {
final uriString = uri.toString();
if (uriString.startsWith('dart:') ||
uriString.startsWith('dart-ext:') ||
_isLeaf(uri)) {
return <Uri>{};
}
// HACK: package:flutter comes from the SDK, we do not want to look at its
// import graph.
//
// We need this because package:flutter imports dart:io, even though it is
// allowed on web.
if (uriString.startsWith('package:flutter/')) {
return <Uri>{Uri.parse('dart:ui')};
}
final path = _analysisSession.uriConverter.uriToPath(uri);
if (path == null) {
// Could not resolve uri.
// Probably a missing/broken dependency.
throw TagException('Could not resolve import: $uri');
}
final unit = parsedUnitFromUri(_analysisSession, uri);
if (unit == null) {
// Part files cannot contain import/export directives.
return <Uri>{};
}
final dependencies = <Uri>{};
for (final node in unit.sortedDirectivesAndDeclarations) {
if (node is! ImportDirective && node is! ExportDirective) {
continue;
}
// The syntax for an import:
//
// directive ::=
// 'import' stringLiteral (configuration)*
// | 'export' stringLiteral (configuration)*
//
// configuration ::= 'if' '(' test ')' uri
//
// test ::= dottedName ('==' stringLiteral)?
//
// We have dependency upon `directive.uri` resolved relative to this
// library `uri`. Unless there is a `configuration` for which the `test`
// evaluates to true.
final directive = node as NamespaceDirective;
var dependency = uri.resolve(directive.uri.stringValue!);
for (final configuration in directive.configurations) {
final dottedName =
configuration.name.components.map((i) => i.name).join('.');
final testValue = configuration.value?.stringValue ?? 'true';
final actualValue = _declaredVariables[dottedName] ?? '';
if (actualValue == testValue) {
dependency = uri.resolve(configuration.uri.stringValue!);
break; // Aways pick the first satisfied configuration.
}
}
dependencies.add(dependency);
}
return dependencies;
});
} catch (e) {
log.info('Unable to parse "$uri".\n$e');
throw TagException(
'Unable to parse uri: "$uri": `${e.toString().split('\n').first}`.');
}
}
static String formatPath(List<Uri> path) {
assert(path.isNotEmpty);
return path.map((p) => '* `$p`').join(' that imports:\n');
}
static bool _constantFalse(Uri _) => false;
}
/// The dependency graph of a package.
///
/// A node is a package name as a String.
///
/// Only considers non-dev-dependencies.
class PackageGraph implements DirectedGraph<String> {
final PubspecCache _pubspecCache;
PackageGraph(this._pubspecCache);
@override
Set<String> directSuccessors(String packageName) {
final pubspec = _pubspecCache.pubspecOfPackage(packageName);
return pubspec.dependencies.keys.toSet();
}
static String formatPath(List<String> path) {
assert(path.isNotEmpty);
return path.map((p) => '* `$p`').join(' that depends on:\n');
}
}
class PathFinder<T> {
final DirectedGraph<T> graph;
final Predicate<T> predicate;
final Map<T, PathResult<T>> _cache = <T, PathResult<T>>{};
PathFinder(this.graph, this.predicate);
/// Searches [graph] for nodes reachable from [root] to a node full-filling
/// [predicate].
///
/// Uses depth-first search.
PathResult<T> findPath(T root) {
final pathToCurrent = <T>[];
final todo = <List<T>>[
[root]
];
final visited = <T>{};
while (todo.isNotEmpty) {
final x = todo.last;
if (x.isEmpty) {
todo.removeLast();
if (todo.isNotEmpty) pathToCurrent.removeLast();
continue;
}
final current = x.removeLast();
if (!visited.add(current)) continue;
if (_cache.containsKey(current)) {
return _cache[root] = _cache[current]!.prefix(pathToCurrent);
}
pathToCurrent.add(current);
final explainer = predicate(current);
if (explainer == null) {
todo.add(graph.directSuccessors(current).toList());
} else {
return PathResult<T>.path(pathToCurrent, explainer);
}
}
return PathResult<T>.noPath();
}
/// Finds a path from [root] to a node violating of [predicate] and returns a
/// Explanation indicating the issue.
///
/// Returns `null` if no issue was found
Explanation? findViolation(T root) => findPath(root).explain();
}
/// The result of a path-finding.
///
/// Either there is no path or there is a path represented as the nodes on the
/// path including the starting node and the final node.
class PathResult<T> {
bool get hasPath => path != null;
final List<T>? path;
final Explainer<T>? explainer;
PathResult.noPath()
: path = null,
explainer = null;
PathResult.path(this.path, this.explainer)
: assert(path != null),
assert(explainer != null);
PathResult<T> prefix(List<T> prefix) {
return hasPath
? PathResult.path([...prefix, ...path!], explainer)
: PathResult<T>.noPath();
}
Explanation? explain() => hasPath ? explainer!(path!) : null;
}
| pana/lib/src/tag/_graphs.dart/0 | {'file_path': 'pana/lib/src/tag/_graphs.dart', 'repo_id': 'pana', 'token_count': 3199} |
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:pana/src/model.dart';
import 'package:test/test.dart';
void main() {
group('Report', () {
test('join section with no match', () {
final report = Report(sections: [
ReportSection(
id: 'a',
title: 'a',
grantedPoints: 5,
maxPoints: 5,
summary: 'something',
status: ReportStatus.partial,
),
]);
final nr = report.joinSection(ReportSection(
id: 'b',
title: 'b',
grantedPoints: 10,
maxPoints: 10,
summary: 'other',
status: ReportStatus.passed,
));
expect(nr.toJson(), {
'sections': [
{
'id': 'a',
'title': 'a',
'grantedPoints': 5,
'maxPoints': 5,
'summary': 'something',
'status': 'partial'
},
{
'id': 'b',
'title': 'b',
'grantedPoints': 10,
'maxPoints': 10,
'summary': 'other',
'status': 'passed',
},
]
});
});
test('join with match', () {
final report = Report(sections: [
ReportSection(
id: 'a',
title: 'a',
grantedPoints: 5,
maxPoints: 5,
summary: 'something\n',
status: ReportStatus.partial,
),
ReportSection(
id: 'b',
title: 'b',
grantedPoints: 6,
maxPoints: 10,
summary: 'other',
status: ReportStatus.passed,
),
]);
final nr = report.joinSection(ReportSection(
id: 'a',
title: 'a',
grantedPoints: 3,
maxPoints: 7,
summary: '\nanother thing\n',
status: ReportStatus.failed,
));
expect(
nr.toJson(),
{
'sections': [
{
'id': 'a',
'title': 'a',
'grantedPoints': 8,
'maxPoints': 12,
'summary': 'something\n\nanother thing',
'status': 'failed'
},
{
'id': 'b',
'title': 'b',
'grantedPoints': 6,
'maxPoints': 10,
'summary': 'other',
'status': 'passed',
},
]
},
);
});
});
group('PanaRuntimeInfo', () {
test('no Flutter SDK', () {
final info = PanaRuntimeInfo(panaVersion: '1.0.0', sdkVersion: '2.0.0');
expect(info.hasFlutter, isFalse);
expect(info.flutterVersion, isNull);
expect(info.flutterInternalDartSdkVersion, isNull);
});
test('no build', () {
final info = PanaRuntimeInfo(
panaVersion: '1.0.0',
sdkVersion: '2.0.0',
flutterVersions: {
'frameworkVersion': '2.1.0-13.0.pre.292',
'channel': 'master',
'repositoryUrl': 'https://github.com/flutter/flutter',
'frameworkRevision': 'b60c855af5150b695638b2195f500d3c003b71ab',
'frameworkCommitDate': '2021-03-26 22:14:01 -0700',
'engineRevision': 'b5e15d055d135c5b82feb3263f47f9f9a038343e',
'dartSdkVersion': '2.13.0',
'flutterRoot': '/bin/flutter',
});
expect(info.hasFlutter, isTrue);
expect(info.flutterVersion, '2.1.0-13.0.pre.292');
expect(info.flutterInternalDartSdkVersion, '2.13.0');
});
test('full build', () {
final info = PanaRuntimeInfo(
panaVersion: '1.0.0',
sdkVersion: '2.0.0',
flutterVersions: {
'frameworkVersion': '2.1.0-13.0.pre.292',
'channel': 'master',
'repositoryUrl': 'https://github.com/flutter/flutter',
'frameworkRevision': 'b60c855af5150b695638b2195f500d3c003b71ab',
'frameworkCommitDate': '2021-03-26 22:14:01 -0700',
'engineRevision': 'b5e15d055d135c5b82feb3263f47f9f9a038343e',
'dartSdkVersion': '2.13.0 (build 2.13.0-162.0.dev)',
'flutterRoot': '/bin/flutter',
});
expect(info.hasFlutter, isTrue);
expect(info.flutterVersion, '2.1.0-13.0.pre.292');
expect(info.flutterInternalDartSdkVersion, '2.13.0-162.0.dev');
});
});
}
| pana/test/model_test.dart/0 | {'file_path': 'pana/test/model_test.dart', 'repo_id': 'pana', 'token_count': 2403} |
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'package:http/http.dart';
import 'package:pana/src/tag/_specs.dart';
import 'package:test/test.dart';
void main() {
group('Dart SDK library definitions', () {
Map<String, dynamic>? libraries;
Set<String> allVmLibs;
late Set<String> publicVmLibs;
Set<String> allDart2jsLibs;
late Set<String> publicDart2jsLibs;
Set<String> extractLibraries(Map<String, dynamic> map) {
return map.entries
.where(
(e) => e.value is Map && (e.value as Map)['supported'] != false)
.map((e) => e.key)
.toSet();
}
setUpAll(() async {
// Download and parse https://github.com/dart-lang/sdk/blob/master/sdk/lib/libraries.json
final librariesContent = await get(Uri.parse(
'https://raw.githubusercontent.com/dart-lang/sdk/master/sdk/lib/libraries.json'));
libraries = json.decode(librariesContent.body) as Map<String, dynamic>?;
allVmLibs = extractLibraries(
libraries!['vm']['libraries'] as Map<String, dynamic>);
publicVmLibs = allVmLibs.where((s) => !s.startsWith('_')).toSet();
allDart2jsLibs = extractLibraries(
libraries!['dart2js']['libraries'] as Map<String, dynamic>);
publicDart2jsLibs =
allDart2jsLibs.where((s) => !s.startsWith('_')).toSet();
});
test('VM libraries', () {
for (final lib in publicVmLibs) {
if (lib == 'wasm' || lib == 'vmservice_io') {
continue; // ignore for now
}
expect(Runtime.nativeJit.enabledLibs, contains(lib));
}
});
test('dart2js libraries', () {
for (final lib in publicDart2jsLibs) {
expect(Runtime.web.enabledLibs, contains(lib));
}
});
});
}
| pana/test/tag/tag_external_test.dart/0 | {'file_path': 'pana/test/tag/tag_external_test.dart', 'repo_id': 'pana', 'token_count': 833} |
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
class CommonExampleRouteWrapper extends StatelessWidget {
const CommonExampleRouteWrapper({
this.imageProvider,
this.loadingBuilder,
this.backgroundDecoration,
this.minScale,
this.maxScale,
this.initialScale,
this.basePosition = Alignment.center,
this.filterQuality = FilterQuality.none,
this.disableGestures,
this.errorBuilder,
});
final ImageProvider? imageProvider;
final LoadingBuilder? loadingBuilder;
final BoxDecoration? backgroundDecoration;
final dynamic minScale;
final dynamic maxScale;
final dynamic initialScale;
final Alignment basePosition;
final FilterQuality filterQuality;
final bool? disableGestures;
final ImageErrorWidgetBuilder? errorBuilder;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
constraints: BoxConstraints.expand(
height: MediaQuery.of(context).size.height,
),
child: PhotoView(
imageProvider: imageProvider,
loadingBuilder: loadingBuilder,
backgroundDecoration: backgroundDecoration,
minScale: minScale,
maxScale: maxScale,
initialScale: initialScale,
basePosition: basePosition,
filterQuality: filterQuality,
disableGestures: disableGestures,
errorBuilder: errorBuilder,
),
),
);
}
}
| photo_view/example/lib/screens/common/common_example_wrapper.dart/0 | {'file_path': 'photo_view/example/lib/screens/common/common_example_wrapper.dart', 'repo_id': 'photo_view', 'token_count': 534} |
import 'package:photo_view/photo_view.dart';
import 'package:test/test.dart';
void main() {
late PhotoViewScaleStateController controller;
setUp(() {
controller = PhotoViewScaleStateController();
});
test('controller constructor', () {
expect(controller.prevScaleState, PhotoViewScaleState.initial);
expect(controller.scaleState, PhotoViewScaleState.initial);
});
test('controller change values', () {
controller.scaleState = PhotoViewScaleState.covering;
expect(controller.prevScaleState, PhotoViewScaleState.initial);
expect(controller.scaleState, PhotoViewScaleState.covering);
controller.scaleState = PhotoViewScaleState.originalSize;
expect(controller.prevScaleState, PhotoViewScaleState.covering);
expect(controller.scaleState, PhotoViewScaleState.originalSize);
controller.setInvisibly(PhotoViewScaleState.zoomedOut);
expect(controller.prevScaleState, PhotoViewScaleState.originalSize);
expect(controller.scaleState, PhotoViewScaleState.zoomedOut);
});
test('controller reset', () {
controller.scaleState = PhotoViewScaleState.covering;
controller.reset();
expect(controller.prevScaleState, PhotoViewScaleState.covering);
expect(controller.scaleState, PhotoViewScaleState.initial);
});
test('controller stream mutation', () {
const PhotoViewScaleState value1 = PhotoViewScaleState.covering;
const PhotoViewScaleState value2 = PhotoViewScaleState.originalSize;
const PhotoViewScaleState value3 = PhotoViewScaleState.initial;
const PhotoViewScaleState value4 = PhotoViewScaleState.zoomedOut;
expect(controller.outputScaleStateStream,
emitsInOrder([value1, value2, value3, value4]));
controller.scaleState = PhotoViewScaleState.covering;
controller.scaleState = PhotoViewScaleState.originalSize;
controller.reset();
controller.scaleState = PhotoViewScaleState.initial;
controller.setInvisibly(PhotoViewScaleState.zoomedOut);
});
test('controller invisible update', () {
int count = 0;
final void Function() callback = () {
count++;
};
controller.addIgnorableListener(callback);
expect(count, 0);
controller.scaleState = PhotoViewScaleState.zoomedOut;
expect(count, 1);
controller.setInvisibly(PhotoViewScaleState.zoomedOut);
expect(count, 1);
controller.reset();
expect(count, 2);
});
}
| photo_view/test/scale_state_controller_test.dart/0 | {'file_path': 'photo_view/test/scale_state_controller_test.dart', 'repo_id': 'photo_view', 'token_count': 737} |
blank_issues_enabled: false | photobooth/.github/ISSUE_TEMPLATE/config.yml/0 | {'file_path': 'photobooth/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'photobooth', 'token_count': 7} |
name: firebase_functions
on:
pull_request:
paths:
- "functions/**"
- ".github/workflows/firebase_functions.yaml"
jobs:
build:
defaults:
run:
working-directory: ./functions
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: "14"
- run: npm install
- run: npm run lint
- run: npm run build
- run: npm run test:coverage
| photobooth/.github/workflows/firebase_functions.yaml/0 | {'file_path': 'photobooth/.github/workflows/firebase_functions.yaml', 'repo_id': 'photobooth', 'token_count': 224} |
// GENERATED CODE - DO NOT MODIFY BY HAND
import 'package:flutter/widgets.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class Assets {
static const android = Asset(
name: 'android',
path: 'assets/images/android.png',
size: Size(450, 658),
);
static const dash = Asset(
name: 'dash',
path: 'assets/images/dash.png',
size: Size(650, 587),
);
static const dino = Asset(
name: 'dino',
path: 'assets/images/dino.png',
size: Size(648, 757),
);
static const sparky = Asset(
name: 'sparky',
path: 'assets/images/sparky.png',
size: Size(730, 588),
);
static const googleProps = {
Asset(
name: '01_google_v1',
path: 'assets/props/google/01_google_v1.png',
size: Size(847, 697),
),
Asset(
name: '02_google_v1',
path: 'assets/props/google/02_google_v1.png',
size: Size(349, 682),
),
Asset(
name: '03_google_V1',
path: 'assets/props/google/03_google_V1.png',
size: Size(640, 595),
),
Asset(
name: '04_google_v1',
path: 'assets/props/google/04_google_v1.png',
size: Size(631, 365),
),
Asset(
name: '05_google_v1',
path: 'assets/props/google/05_google_v1.png',
size: Size(968, 187),
),
Asset(
name: '06_google_v1',
path: 'assets/props/google/06_google_v1.png',
size: Size(1008, 465),
),
Asset(
name: '07_google_v1',
path: 'assets/props/google/07_google_v1.png',
size: Size(1009, 469),
),
Asset(
name: '08_google_v1',
path: 'assets/props/google/08_google_v1.png',
size: Size(793, 616),
),
Asset(
name: '09_google_v1',
path: 'assets/props/google/09_google_v1.png',
size: Size(603, 810),
),
Asset(
name: '10_google_v1',
path: 'assets/props/google/10_google_v1.png',
size: Size(971, 764),
),
Asset(
name: '11_google_v1',
path: 'assets/props/google/11_google_v1.png',
size: Size(839, 840),
),
Asset(
name: '12_google_v1',
path: 'assets/props/google/12_google_v1.png',
size: Size(995, 181),
),
Asset(
name: '13_google_v1',
path: 'assets/props/google/13_google_v1.png',
size: Size(884, 589),
),
Asset(
name: '14_google_v1',
path: 'assets/props/google/14_google_v1.png',
size: Size(726, 591),
),
Asset(
name: '15_google_v1',
path: 'assets/props/google/15_google_v1.png',
size: Size(450, 722),
),
Asset(
name: '16_google_v1',
path: 'assets/props/google/16_google_v1.png',
size: Size(690, 772),
),
Asset(
name: '17_google_v1',
path: 'assets/props/google/17_google_v1.png',
size: Size(671, 641),
),
Asset(
name: '18_google_v1',
path: 'assets/props/google/18_google_v1.png',
size: Size(437, 452),
),
Asset(
name: '19_google_v1',
path: 'assets/props/google/19_google_v1.png',
size: Size(620, 619),
),
Asset(
name: '20_google_v1',
path: 'assets/props/google/20_google_v1.png',
size: Size(320, 903),
),
Asset(
name: '21_google_v1',
path: 'assets/props/google/21_google_v1.png',
size: Size(301, 795),
),
Asset(
name: '22_google_v1',
path: 'assets/props/google/22_google_v1.png',
size: Size(901, 870),
),
Asset(
name: '23_google_v1',
path: 'assets/props/google/23_google_v1.png',
size: Size(541, 715),
),
Asset(
name: '24_google_v1',
path: 'assets/props/google/24_google_v1.png',
size: Size(784, 807),
),
Asset(
name: '25_google_v1',
path: 'assets/props/google/25_google_v1.png',
size: Size(1086, 898),
),
Asset(
name: '26_google_v1',
path: 'assets/props/google/26_google_v1.png',
size: Size(419, 820),
),
Asset(
name: '27_google_v1',
path: 'assets/props/google/27_google_v1.png',
size: Size(921, 613),
),
Asset(
name: '28_google_v1',
path: 'assets/props/google/28_google_v1.png',
size: Size(403, 741),
),
Asset(
name: '29_google_v1',
path: 'assets/props/google/29_google_v1.png',
size: Size(570, 556),
),
Asset(
name: '30_google_v1',
path: 'assets/props/google/30_google_v1.png',
size: Size(890, 747),
),
Asset(
name: '31_google_v1',
path: 'assets/props/google/31_google_v1.png',
size: Size(891, 639),
),
Asset(
name: '32_google_v1',
path: 'assets/props/google/32_google_v1.png',
size: Size(599, 468),
),
Asset(
name: '33_google_v1',
path: 'assets/props/google/33_google_v1.png',
size: Size(639, 657),
),
Asset(
name: '34_google_v1',
path: 'assets/props/google/34_google_v1.png',
size: Size(570, 556),
),
Asset(
name: '35_google_v1',
path: 'assets/props/google/35_google_v1.png',
size: Size(662, 591),
),
};
static const hatProps = {
Asset(
name: '01_hats_v1',
path: 'assets/props/hats/01_hats_v1.png',
size: Size(571, 296),
),
Asset(
name: '02_hats_v1',
path: 'assets/props/hats/02_hats_v1.png',
size: Size(348, 594),
),
Asset(
name: '03_hats_v1',
path: 'assets/props/hats/03_hats_v1.png',
size: Size(833, 490),
),
Asset(
name: '04_hats_v1',
path: 'assets/props/hats/04_hats_v1.png',
size: Size(1051, 616),
),
Asset(
name: '05_hats_v1',
path: 'assets/props/hats/05_hats_v1.png',
size: Size(555, 298),
),
Asset(
name: '06_hats_v1',
path: 'assets/props/hats/06_hats_v1.png',
size: Size(1048, 656),
),
Asset(
name: '07_hats_v1',
path: 'assets/props/hats/07_hats_v1.png',
size: Size(925, 673),
),
Asset(
name: '08_hats_v1',
path: 'assets/props/hats/08_hats_v1.png',
size: Size(693, 361),
),
Asset(
name: '09_hats_v1',
path: 'assets/props/hats/09_hats_v1.png',
size: Size(558, 296),
),
Asset(
name: '10_hats_v1',
path: 'assets/props/hats/10_hats_v1.png',
size: Size(185, 676),
),
Asset(
name: '11_hats_v1',
path: 'assets/props/hats/11_hats_v1.png',
size: Size(677, 464),
),
Asset(
name: '12_hats_v1',
path: 'assets/props/hats/12_hats_v1.png',
size: Size(578, 762),
),
Asset(
name: '13_hats_v1',
path: 'assets/props/hats/13_hats_v1.png',
size: Size(590, 255),
),
Asset(
name: '14_hats_v1',
path: 'assets/props/hats/14_hats_v1.png',
size: Size(673, 555),
),
Asset(
name: '15_hats_v1',
path: 'assets/props/hats/15_hats_v1.png',
size: Size(860, 535),
),
Asset(
name: '16_hats_v1',
path: 'assets/props/hats/16_hats_v1.png',
size: Size(560, 611),
),
Asset(
name: '17_hats_v1',
path: 'assets/props/hats/17_hats_v1.png',
size: Size(1044, 618),
),
Asset(
name: '18_hats_v1',
path: 'assets/props/hats/18_hats_v1.png',
size: Size(849, 299),
),
Asset(
name: '19_hats_v1',
path: 'assets/props/hats/19_hats_v1.png',
size: Size(701, 483),
),
Asset(
name: '20_hats_v1',
path: 'assets/props/hats/20_hats_v1.png',
size: Size(644, 433),
),
Asset(
name: '21_hats_v1',
path: 'assets/props/hats/21_hats_v1.png',
size: Size(530, 612),
),
Asset(
name: '22_hats_v1',
path: 'assets/props/hats/22_hats_v1.png',
size: Size(664, 146),
),
Asset(
name: '23_hats_v1',
path: 'assets/props/hats/23_hats_v1.png',
size: Size(969, 336),
),
Asset(
name: '24_hats_v1',
path: 'assets/props/hats/24_hats_v1.png',
size: Size(812, 622),
),
Asset(
name: '25_hats_v1',
path: 'assets/props/hats/25_hats_v1.png',
size: Size(608, 316),
),
Asset(
name: '26_hats_v1',
path: 'assets/props/hats/26_hats_v1.png',
size: Size(693, 360),
),
Asset(
name: '27_hats_v1',
path: 'assets/props/hats/27_hats_v1.png',
size: Size(469, 608),
),
};
static const eyewearProps = {
Asset(
name: '01_eyewear_v1',
path: 'assets/props/eyewear/01_eyewear_v1.png',
size: Size(479, 330),
),
Asset(
name: '02_eyewear_v1',
path: 'assets/props/eyewear/02_eyewear_v1.png',
size: Size(512, 133),
),
Asset(
name: '03_eyewear_v1',
path: 'assets/props/eyewear/03_eyewear_v1.png',
size: Size(1212, 522),
),
Asset(
name: '04_eyewear_v1',
path: 'assets/props/eyewear/04_eyewear_v1.png',
size: Size(723, 343),
),
Asset(
name: '05_eyewear_v1',
path: 'assets/props/eyewear/05_eyewear_v1.png',
size: Size(1173, 436),
),
Asset(
name: '06_eyewear_v1',
path: 'assets/props/eyewear/06_eyewear_v1.png',
size: Size(973, 411),
),
Asset(
name: '07_eyewear_v1',
path: 'assets/props/eyewear/07_eyewear_v1.png',
size: Size(1195, 451),
),
Asset(
name: '08_eyewear_v1',
path: 'assets/props/eyewear/08_eyewear_v1.png',
size: Size(985, 250),
),
Asset(
name: '09_eyewear_v1',
path: 'assets/props/eyewear/09_eyewear_v1.png',
size: Size(479, 330),
),
Asset(
name: '10_eyewear_v1',
path: 'assets/props/eyewear/10_eyewear_v1.png',
size: Size(1405, 589),
),
Asset(
name: '11_eyewear_v1',
path: 'assets/props/eyewear/11_eyewear_v1.png',
size: Size(1151, 495),
),
Asset(
name: '12_eyewear_v1',
path: 'assets/props/eyewear/12_eyewear_v1.png',
size: Size(1267, 388),
),
Asset(
name: '13_eyewear_v1',
path: 'assets/props/eyewear/13_eyewear_v1.png',
size: Size(957, 334),
),
Asset(
name: '14_eyewear_v1',
path: 'assets/props/eyewear/14_eyewear_v1.png',
size: Size(989, 601),
),
Asset(
name: '15_eyewear_v1',
path: 'assets/props/eyewear/15_eyewear_v1.png',
size: Size(1200, 482),
),
Asset(
name: '16_eyewear_v1',
path: 'assets/props/eyewear/16_eyewear_v1.png',
size: Size(1028, 360),
),
};
static const foodProps = {
Asset(
name: '01_food_v1',
path: 'assets/props/food/01_food_v1.png',
size: Size(587, 678),
),
Asset(
name: '02_food_v1',
path: 'assets/props/food/02_food_v1.png',
size: Size(325, 591),
),
Asset(
name: '03_food_v1',
path: 'assets/props/food/03_food_v1.png',
size: Size(685, 686),
),
Asset(
name: '04_food_v1',
path: 'assets/props/food/04_food_v1.png',
size: Size(496, 422),
),
Asset(
name: '05_food_v1',
path: 'assets/props/food/05_food_v1.png',
size: Size(373, 431),
),
Asset(
name: '06_food_v1',
path: 'assets/props/food/06_food_v1.png',
size: Size(635, 587),
),
Asset(
name: '07_food_v1',
path: 'assets/props/food/07_food_v1.png',
size: Size(847, 720),
),
Asset(
name: '08_food_v1',
path: 'assets/props/food/08_food_v1.png',
size: Size(799, 610),
),
Asset(
name: '09_food_v1',
path: 'assets/props/food/09_food_v1.png',
size: Size(771, 489),
),
Asset(
name: '10_food_v1',
path: 'assets/props/food/10_food_v1.png',
size: Size(651, 634),
),
Asset(
name: '11_food_v1',
path: 'assets/props/food/11_food_v1.png',
size: Size(391, 710),
),
Asset(
name: '12_food_v1',
path: 'assets/props/food/12_food_v1.png',
size: Size(530, 856),
),
Asset(
name: '13_food_v1',
path: 'assets/props/food/13_food_v1.png',
size: Size(451, 638),
),
Asset(
name: '14_food_v1',
path: 'assets/props/food/14_food_v1.png',
size: Size(721, 507),
),
Asset(
name: '15_food_v1',
path: 'assets/props/food/15_food_v1.png',
size: Size(353, 640),
),
Asset(
name: '16_food_v1',
path: 'assets/props/food/16_food_v1.png',
size: Size(353, 640),
),
Asset(
name: '17_food_v1',
path: 'assets/props/food/17_food_v1.png',
size: Size(524, 649),
),
Asset(
name: '18_food_v1',
path: 'assets/props/food/18_food_v1.png',
size: Size(437, 503),
),
Asset(
name: '19_food_v1',
path: 'assets/props/food/19_food_v1.png',
size: Size(327, 770),
),
Asset(
name: '20_food_v1',
path: 'assets/props/food/20_food_v1.png',
size: Size(391, 786),
),
Asset(
name: '21_food_v1',
path: 'assets/props/food/21_food_v1.png',
size: Size(315, 754),
),
Asset(
name: '22_food_v1',
path: 'assets/props/food/22_food_v1.png',
size: Size(532, 610),
),
Asset(
name: '23_food_v1',
path: 'assets/props/food/23_food_v1.png',
size: Size(761, 664),
),
Asset(
name: '24_food_v1',
path: 'assets/props/food/24_food_v1.png',
size: Size(829, 630),
),
Asset(
name: '25_food_v1',
path: 'assets/props/food/25_food_v1.png',
size: Size(668, 819),
),
};
static const shapeProps = {
Asset(
name: '01_shapes_v1',
path: 'assets/props/shapes/01_shapes_v1.png',
size: Size(519, 391),
),
Asset(
name: '02_shapes_v1',
path: 'assets/props/shapes/02_shapes_v1.png',
size: Size(486, 522),
),
Asset(
name: '03_shapes_v1',
path: 'assets/props/shapes/03_shapes_v1.png',
size: Size(404, 522),
),
Asset(
name: '04_shapes_v1',
path: 'assets/props/shapes/04_shapes_v1.png',
size: Size(636, 697),
),
Asset(
name: '05_shapes_v1',
path: 'assets/props/shapes/05_shapes_v1.png',
size: Size(463, 458),
),
Asset(
name: '06_shapes_v1',
path: 'assets/props/shapes/06_shapes_v1.png',
size: Size(447, 442),
),
Asset(
name: '07_shapes_v1',
path: 'assets/props/shapes/07_shapes_v1.png',
size: Size(793, 402),
),
Asset(
name: '08_shapes_v1',
path: 'assets/props/shapes/08_shapes_v1.png',
size: Size(442, 405),
),
Asset(
name: '09_shapes_v1',
path: 'assets/props/shapes/09_shapes_v1.png',
size: Size(973, 684),
),
Asset(
name: '10_shapes_v1',
path: 'assets/props/shapes/10_shapes_v1.png',
size: Size(586, 560),
),
Asset(
name: '11_shapes_v1',
path: 'assets/props/shapes/11_shapes_v1.png',
size: Size(760, 650),
),
Asset(
name: '12_shapes_v1',
path: 'assets/props/shapes/12_shapes_v1.png',
size: Size(696, 408),
),
Asset(
name: '13_shapes_v1',
path: 'assets/props/shapes/13_shapes_v1.png',
size: Size(423, 410),
),
Asset(
name: '14_shapes_v1',
path: 'assets/props/shapes/14_shapes_v1.png',
size: Size(319, 552),
),
Asset(
name: '15_shapes_v1',
path: 'assets/props/shapes/15_shapes_v1.png',
size: Size(779, 687),
),
Asset(
name: '16_shapes_v1',
path: 'assets/props/shapes/16_shapes_v1.png',
size: Size(651, 616),
),
Asset(
name: '17_shapes_v1',
path: 'assets/props/shapes/17_shapes_v1.png',
size: Size(704, 761),
),
Asset(
name: '18_shapes_v1',
path: 'assets/props/shapes/18_shapes_v1.png',
size: Size(936, 809),
),
Asset(
name: '19_shapes_v1',
path: 'assets/props/shapes/19_shapes_v1.png',
size: Size(848, 850),
),
Asset(
name: '20_shapes_v1',
path: 'assets/props/shapes/20_shapes_v1.png',
size: Size(377, 825),
),
Asset(
name: '21_shapes_v1',
path: 'assets/props/shapes/21_shapes_v1.png',
size: Size(365, 814),
),
Asset(
name: '22_shapes_v1',
path: 'assets/props/shapes/22_shapes_v1.png',
size: Size(297, 799),
),
Asset(
name: '23_shapes_v1',
path: 'assets/props/shapes/23_shapes_v1.png',
size: Size(363, 822),
),
Asset(
name: '24_shapes_v1',
path: 'assets/props/shapes/24_shapes_v1.png',
size: Size(363, 821),
),
Asset(
name: '25_shapes_v1',
path: 'assets/props/shapes/25_shapes_v1.png',
size: Size(363, 821),
),
};
static const props = {
...googleProps,
...eyewearProps,
...hatProps,
...foodProps,
...shapeProps
};
}
| photobooth/lib/assets.g.dart/0 | {'file_path': 'photobooth/lib/assets.g.dart', 'repo_id': 'photobooth', 'token_count': 9191} |
export 'bloc/photobooth_bloc.dart';
export 'view/photobooth_page.dart';
export 'widgets/widgets.dart';
| photobooth/lib/photobooth/photobooth.dart/0 | {'file_path': 'photobooth/lib/photobooth/photobooth.dart', 'repo_id': 'photobooth', 'token_count': 42} |
export 'animated_characters/animated_characters.dart';
export 'character_icon_button.dart';
export 'characters_caption.dart';
export 'characters_layer.dart';
export 'photobooth_background.dart';
export 'photobooth_error.dart';
export 'photobooth_photo.dart';
export 'photobooth_preview.dart';
export 'shutter_button.dart';
export 'stickers_layer.dart';
| photobooth/lib/photobooth/widgets/widgets.dart/0 | {'file_path': 'photobooth/lib/photobooth/widgets/widgets.dart', 'repo_id': 'photobooth', 'token_count': 124} |
import 'dart:typed_data';
import 'package:analytics/analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:platform_helper/platform_helper.dart';
class ShareButton extends StatelessWidget {
ShareButton({
required this.image,
PlatformHelper? platformHelper,
super.key,
}) : platformHelper = platformHelper ?? PlatformHelper();
/// Composited image
final Uint8List image;
/// Optional [PlatformHelper] instance.
final PlatformHelper platformHelper;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return ElevatedButton(
key: const Key('sharePage_share_elevatedButton'),
onPressed: () {
trackEvent(
category: 'button',
action: 'click-share-photo',
label: 'share-photo',
);
showAppModal<void>(
context: context,
platformHelper: platformHelper,
landscapeChild: MultiBlocProvider(
providers: [
BlocProvider.value(value: context.read<PhotoboothBloc>()),
BlocProvider.value(value: context.read<ShareBloc>()),
],
child: ShareDialog(image: image),
),
portraitChild: MultiBlocProvider(
providers: [
BlocProvider.value(value: context.read<PhotoboothBloc>()),
BlocProvider.value(value: context.read<ShareBloc>()),
],
child: ShareBottomSheet(image: image),
),
);
},
child: Text(l10n.sharePageShareButtonText),
);
}
}
| photobooth/lib/share/widgets/share_button.dart/0 | {'file_path': 'photobooth/lib/share/widgets/share_button.dart', 'repo_id': 'photobooth', 'token_count': 772} |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/footer/footer.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const _initialStickerScale = 0.25;
const _minStickerScale = 0.05;
class StickersPage extends StatelessWidget {
const StickersPage({
super.key,
});
static Route<void> route() {
return AppPageRoute(builder: (_) => const StickersPage());
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => StickersBloc(),
child: const StickersView(),
);
}
}
class StickersView extends StatelessWidget {
const StickersView({super.key});
@override
Widget build(BuildContext context) {
final state = context.watch<PhotoboothBloc>().state;
final image = state.image;
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
const PhotoboothBackground(),
Center(
child: AspectRatio(
aspectRatio: state.aspectRatio,
child: Stack(
fit: StackFit.expand,
children: [
const Positioned.fill(
child: ColoredBox(color: PhotoboothColors.black),
),
if (image != null) PreviewImage(data: image.data),
const Align(
alignment: Alignment.bottomLeft,
child: Padding(
padding: EdgeInsets.only(left: 16, bottom: 24),
child: MadeWithIconLinks(),
),
),
const CharactersLayer(),
const _DraggableStickers(),
const Positioned(
left: 15,
top: 15,
child: Row(
children: [
_RetakeButton(),
ClearStickersButtonLayer(),
],
),
),
Positioned(
right: 15,
top: 15,
child: OpenStickersButton(
onPressed: () {
context
.read<StickersBloc>()
.add(const StickersDrawerToggled());
},
),
),
const Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.only(bottom: 30),
child: _NextButton(),
),
),
const Align(
alignment: Alignment.bottomCenter,
child: _StickerReminderText(),
)
],
),
),
),
const StickersDrawerLayer(),
],
),
);
}
}
class _StickerReminderText extends StatelessWidget {
const _StickerReminderText();
@override
Widget build(BuildContext context) {
final shouldDisplayPropsReminder = context.select(
(StickersBloc bloc) => bloc.state.shouldDisplayPropsReminder,
);
if (!shouldDisplayPropsReminder) return const SizedBox();
return Container(
margin: const EdgeInsets.only(bottom: 125),
child: AppTooltip.custom(
key: const Key('stickersPage_propsReminder_appTooltip'),
visible: true,
message: context.l10n.propsReminderText,
),
);
}
}
class _DraggableStickers extends StatelessWidget {
const _DraggableStickers();
@override
Widget build(BuildContext context) {
final state = context.watch<PhotoboothBloc>().state;
if (state.stickers.isEmpty) return const SizedBox();
return Stack(
fit: StackFit.expand,
children: [
Positioned.fill(
child: GestureDetector(
key: const Key('stickersView_background_gestureDetector'),
onTap: () {
context.read<PhotoboothBloc>().add(const PhotoTapped());
},
),
),
for (final sticker in state.stickers)
DraggableResizable(
key: Key('stickerPage_${sticker.id}_draggableResizable_asset'),
canTransform: sticker.id == state.selectedAssetId,
onUpdate: (update) => context
.read<PhotoboothBloc>()
.add(PhotoStickerDragged(sticker: sticker, update: update)),
onDelete: () => context
.read<PhotoboothBloc>()
.add(const PhotoDeleteSelectedStickerTapped()),
size: sticker.asset.size * _initialStickerScale,
constraints: sticker.getImageConstraints(),
child: SizedBox.expand(
child: Image.asset(
sticker.asset.path,
fit: BoxFit.fill,
gaplessPlayback: true,
),
),
),
],
);
}
}
class _RetakeButton extends StatelessWidget {
const _RetakeButton();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Semantics(
focusable: true,
button: true,
label: l10n.retakePhotoButtonLabelText,
child: AppTooltipButton(
key: const Key('stickersPage_retake_appTooltipButton'),
onPressed: () async {
final photoboothBloc = context.read<PhotoboothBloc>();
final navigator = Navigator.of(context);
final confirmed = await showAppModal<bool>(
context: context,
landscapeChild: const _RetakeConfirmationDialogContent(),
portraitChild: const _RetakeConfirmationBottomSheet(),
);
if (confirmed ?? false) {
photoboothBloc.add(const PhotoClearAllTapped());
unawaited(
navigator.pushReplacement(PhotoboothPage.route()),
);
}
},
verticalOffset: 50,
message: l10n.retakeButtonTooltip,
child: Image.asset('assets/icons/retake_button_icon.png', height: 100),
),
);
}
}
class _NextButton extends StatelessWidget {
const _NextButton();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Semantics(
focusable: true,
button: true,
label: l10n.stickersNextButtonLabelText,
child: Material(
clipBehavior: Clip.hardEdge,
shape: const CircleBorder(),
color: PhotoboothColors.transparent,
child: InkWell(
key: const Key('stickersPage_next_inkWell'),
onTap: () async {
final navigator = Navigator.of(context);
final confirmed = await showAppModal<bool>(
context: context,
landscapeChild: const _NextConfirmationDialogContent(),
portraitChild: const _NextConfirmationBottomSheet(),
);
if (confirmed ?? false) {
unawaited(navigator.pushReplacement(SharePage.route()));
}
},
child: Image.asset(
'assets/icons/go_next_button_icon.png',
height: 100,
),
),
),
);
}
}
class _RetakeConfirmationDialogContent extends StatelessWidget {
const _RetakeConfirmationDialogContent();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(60),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.stickersRetakeConfirmationHeading,
textAlign: TextAlign.center,
style: theme.textTheme.displayLarge,
),
const SizedBox(height: 24),
Text(
l10n.stickersRetakeConfirmationSubheading,
textAlign: TextAlign.center,
style: theme.textTheme.displaySmall,
),
const SizedBox(height: 24),
Wrap(
alignment: WrapAlignment.center,
spacing: 24,
runSpacing: 24,
children: [
OutlinedButton(
style: OutlinedButton.styleFrom(
side: const BorderSide(color: PhotoboothColors.black),
),
onPressed: () => Navigator.of(context).pop(false),
child: Text(
l10n.stickersRetakeConfirmationCancelButtonText,
style: theme.textTheme.labelLarge?.copyWith(
color: PhotoboothColors.black,
),
),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text(
l10n.stickersRetakeConfirmationConfirmButtonText,
),
)
],
),
],
),
),
),
);
}
}
class _RetakeConfirmationBottomSheet extends StatelessWidget {
const _RetakeConfirmationBottomSheet();
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 30),
decoration: const BoxDecoration(
color: PhotoboothColors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
child: Stack(
children: [
const _RetakeConfirmationDialogContent(),
Positioned(
right: 24,
top: 24,
child: IconButton(
icon: const Icon(Icons.clear, color: PhotoboothColors.black54),
onPressed: () => Navigator.of(context).pop(false),
),
),
],
),
);
}
}
class _NextConfirmationDialogContent extends StatelessWidget {
const _NextConfirmationDialogContent();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(60),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.stickersNextConfirmationHeading,
textAlign: TextAlign.center,
style: theme.textTheme.displayLarge,
),
const SizedBox(height: 24),
Text(
l10n.stickersNextConfirmationSubheading,
textAlign: TextAlign.center,
style: theme.textTheme.displaySmall,
),
const SizedBox(height: 24),
Wrap(
alignment: WrapAlignment.center,
spacing: 24,
runSpacing: 24,
children: [
OutlinedButton(
style: OutlinedButton.styleFrom(
side: const BorderSide(color: PhotoboothColors.black),
),
onPressed: () => Navigator.of(context).pop(false),
child: Text(
l10n.stickersNextConfirmationCancelButtonText,
style: theme.textTheme.labelLarge?.copyWith(
color: PhotoboothColors.black,
),
),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text(
l10n.stickersNextConfirmationConfirmButtonText,
),
)
],
),
],
),
),
),
);
}
}
class _NextConfirmationBottomSheet extends StatelessWidget {
const _NextConfirmationBottomSheet();
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 30),
decoration: const BoxDecoration(
color: PhotoboothColors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
child: Stack(
children: [
const _NextConfirmationDialogContent(),
Positioned(
right: 24,
top: 24,
child: IconButton(
icon: const Icon(Icons.clear, color: PhotoboothColors.black54),
onPressed: () => Navigator.of(context).pop(false),
),
),
],
),
);
}
}
extension on PhotoAsset {
BoxConstraints getImageConstraints() {
return BoxConstraints(
minWidth: asset.size.width * _minStickerScale,
minHeight: asset.size.height * _minStickerScale,
);
}
}
class OpenStickersButton extends StatefulWidget {
const OpenStickersButton({
required this.onPressed,
super.key,
});
final VoidCallback onPressed;
@override
State<OpenStickersButton> createState() => _OpenStickersButtonState();
}
class _OpenStickersButtonState extends State<OpenStickersButton> {
bool _isAnimating = true;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final child = Semantics(
focusable: true,
button: true,
label: l10n.addStickersButtonLabelText,
child: AppTooltipButton(
key: const Key('stickersView_openStickersButton_appTooltipButton'),
onPressed: () {
widget.onPressed();
if (_isAnimating) setState(() => _isAnimating = false);
},
message: l10n.openStickersTooltip,
verticalOffset: 50,
child: Image.asset(
'assets/icons/stickers_button_icon.png',
height: 100,
),
),
);
return _isAnimating ? AnimatedPulse(child: child) : child;
}
}
| photobooth/lib/stickers/view/stickers_page.dart/0 | {'file_path': 'photobooth/lib/stickers/view/stickers_page.dart', 'repo_id': 'photobooth', 'token_count': 7274} |
import 'dart:js';
import 'package:flutter/foundation.dart';
/// Exposed [JsObject] for testing purposes.
@visibleForTesting
JsObject? testContext;
/// Method which tracks an event for the provided
/// [category], [action], and [label].
void trackEvent({
required String category,
required String action,
required String label,
}) {
try {
(testContext ?? context).callMethod(
'ga',
<dynamic>['send', 'event', category, action, label],
);
} catch (_) {}
}
| photobooth/packages/analytics/lib/src/analytics_web.dart/0 | {'file_path': 'photobooth/packages/analytics/lib/src/analytics_web.dart', 'repo_id': 'photobooth', 'token_count': 158} |
name: example
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
flutter: ">=2.0.0"
dependencies:
camera:
path: ../
flutter:
sdk: flutter
dev_dependencies:
very_good_analysis: ^4.0.0+1
flutter:
uses-material-design: true
| photobooth/packages/camera/camera/example/pubspec.yaml/0 | {'file_path': 'photobooth/packages/camera/camera/example/pubspec.yaml', 'repo_id': 'photobooth', 'token_count': 117} |
class CameraImage {
const CameraImage({
required this.data,
required this.width,
required this.height,
});
/// A data URI containing a representation of the image ('image/png').
final String data;
/// Is an unsigned long representing the actual height,
/// in pixels, of the image data.
final int width;
/// Is an unsigned long representing the actual width,
/// in pixels, of the image data.
final int height;
}
| photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_image.dart/0 | {'file_path': 'photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_image.dart', 'repo_id': 'photobooth', 'token_count': 124} |
/// Unsupported Implementation of [ImageCompositor]
class ImageCompositor {
/// Throws [UnsupportedError].
Future<List<int>> composite({
required String data,
required int width,
required int height,
required List<dynamic> layers,
required double aspectRatio,
}) {
throw UnsupportedError(
'composite is not supported for the current host platform',
);
}
}
| photobooth/packages/image_compositor/lib/src/unsupported.dart/0 | {'file_path': 'photobooth/packages/image_compositor/lib/src/unsupported.dart', 'repo_id': 'photobooth', 'token_count': 127} |
import 'package:flutter/widgets.dart';
/// Defines the color palette for the Photobooth UI.
abstract class PhotoboothColors {
/// Black
static const Color black = Color(0xFF202124);
/// Black 54% opacity
static const Color black54 = Color(0x8A000000);
/// Black 25% opacity
static const Color black25 = Color(0x40202124);
/// Gray
static const Color gray = Color(0xFFCFCFCF);
/// White
static const Color white = Color(0xFFFFFFFF);
/// WhiteBackground
static const Color whiteBackground = Color(0xFFE8EAED);
/// Transparent
static const Color transparent = Color(0x00000000);
/// Blue
static const Color blue = Color(0xFF428EFF);
/// Red
static const Color red = Color(0xFFFB5246);
/// Green
static const Color green = Color(0xFF3fBC5C);
/// Orange
static const Color orange = Color(0xFFFFBB00);
/// Charcoal
static const Color charcoal = Color(0xBF202124);
}
| photobooth/packages/photobooth_ui/lib/src/colors.dart/0 | {'file_path': 'photobooth/packages/photobooth_ui/lib/src/colors.dart', 'repo_id': 'photobooth', 'token_count': 286} |
export 'font_weights.dart';
export 'text_styles.dart';
| photobooth/packages/photobooth_ui/lib/src/typography/typography.dart/0 | {'file_path': 'photobooth/packages/photobooth_ui/lib/src/typography/typography.dart', 'repo_id': 'photobooth', 'token_count': 20} |
name: photobooth_ui
description: UI Toolkit for the Photobooth Flutter Application
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
equatable: ^2.0.5
flame: ^1.6.0
flutter:
sdk: flutter
platform_helper:
path: ../platform_helper
url_launcher: ^6.1.8
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
plugin_platform_interface: ^2.1.3
url_launcher_platform_interface: ^2.1.1
very_good_analysis: ^4.0.0+1
flutter:
fonts:
- family: GoogleSans
fonts:
- asset: assets/fonts/GoogleSans-Bold.ttf
weight: 700
- asset: assets/fonts/GoogleSans-BoldItalic.ttf
weight: 700
style: italic
- asset: assets/fonts/GoogleSans-Medium.ttf
weight: 500
- asset: assets/fonts/GoogleSans-MediumItalic.ttf
weight: 500
style: italic
- asset: assets/fonts/GoogleSans-Regular.ttf
weight: 400
- asset: assets/fonts/GoogleSans-Italic.ttf
weight: 400
style: italic
| photobooth/packages/photobooth_ui/pubspec.yaml/0 | {'file_path': 'photobooth/packages/photobooth_ui/pubspec.yaml', 'repo_id': 'photobooth', 'token_count': 517} |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('showAppDialog', () {
testWidgets('should show dialog', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => TextButton(
onPressed: () => showAppDialog<void>(
context: context,
child: const Text('dialog'),
),
child: const Text('open dialog'),
),
),
),
);
await tester.tap(find.text('open dialog'));
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/app_dialog_test.dart/0 | {'file_path': 'photobooth/packages/photobooth_ui/test/src/widgets/app_dialog_test.dart', 'repo_id': 'photobooth', 'token_count': 358} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/external_links/external_links.dart';
import 'package:io_photobooth/footer/footer.dart';
import 'package:mocktail/mocktail.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../../helpers/helpers.dart';
class MockUrlLauncher extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
void main() {
setUpAll(() {
registerFallbackValue(LaunchOptions());
});
group('IconLink', () {
testWidgets('opens link when tapped', (tester) async {
final originalUrlLauncher = UrlLauncherPlatform.instance;
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await tester.pumpApp(
IconLink(
link: 'https://example.com',
icon: Icon(Icons.image),
),
);
await tester.tap(find.byType(IconLink));
await tester.pumpAndSettle();
verify(() => mock.launchUrl('https://example.com', any())).called(1);
UrlLauncherPlatform.instance = originalUrlLauncher;
});
});
group('FlutterIconLink', () {
testWidgets('renders IconLink widget with a proper link', (tester) async {
await tester.pumpApp(FlutterIconLink());
final widget = tester.widget<IconLink>(find.byType(IconLink));
expect(widget.link, equals(flutterDevExternalLink));
});
});
group('FirebaseIconLink', () {
testWidgets('renders IconLink widget with a proper link', (tester) async {
await tester.pumpApp(FirebaseIconLink());
final widget = tester.widget<IconLink>(find.byType(IconLink));
expect(widget.link, equals(firebaseExternalLink));
});
});
}
| photobooth/test/app/widgets/icon_link_test.dart/0 | {'file_path': 'photobooth/test/app/widgets/icon_link_test.dart', 'repo_id': 'photobooth', 'token_count': 746} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.