code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
import 'package:flutter/material.dart';
import '../../../constants/constants.dart';
class SingletonExampleCard extends StatelessWidget {
final String text;
const SingletonExampleCard({
required this.text,
});
@override
Widget build(BuildContext context) {
return Card(
child: Container(
height: 64.0,
padding: const EdgeInsets.all(LayoutConstants.paddingL),
child: Center(
child: Text(
text,
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
),
),
);
}
}
| flutter-design-patterns/lib/widgets/design_patterns/singleton/singleton_example_card.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/design_patterns/singleton/singleton_example_card.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 263} |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class ImageView extends StatefulWidget {
const ImageView({
required this.uri,
super.key,
});
final Uri uri;
@override
State<ImageView> createState() => _ImageViewState();
}
class _ImageViewState extends State<ImageView>
with SingleTickerProviderStateMixin {
late TransformationController _controller;
late Animation<Matrix4>? _animationReset;
late AnimationController _controllerReset;
var _tapPosition = Offset.zero;
@override
void initState() {
super.initState();
_controllerReset = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 100),
);
_controller = TransformationController();
}
@override
void dispose() {
_controller.dispose();
_controllerReset.dispose();
super.dispose();
}
// little hack as there is no way to get onTapDown triggered
// when onDoubleTap is registered
// track issue: (https://github.com/flutter/flutter/issues/10048)
void _onTapDown(TapDownDetails details) {
if (_tapPosition == Offset.zero &&
!(details.globalPosition.dx - _tapPosition.dx < 20 &&
details.globalPosition.dy - _tapPosition.dy < 20)) {
_tapPosition = details.globalPosition;
}
Timer(const Duration(milliseconds: 500), () => _tapPosition = Offset.zero);
}
void _onDoubleTap() => _controller.value == Matrix4.identity()
? _animateScaleIn()
: _animateScaleOut();
void _animateScaleIn() {
final size = MediaQuery.of(context).size;
final offset = Offset(-size.width / 4, -size.height / 4);
_animateResetInitialize(
_controller.value.clone()
..scale(2.5)
..translate(offset.dx, offset.dy),
);
}
void _animateScaleOut() => _animateResetInitialize(Matrix4.identity());
void _animateResetInitialize(Matrix4 end) {
_controllerReset.reset();
_animationReset = Matrix4Tween(
begin: _controller.value,
end: end,
).animate(_controllerReset);
_animationReset?.addListener(_onAnimateReset);
_controllerReset.forward();
}
void _resetAndRemoveListener() {
_animationReset?.removeListener(_onAnimateReset);
_animationReset = null;
_controllerReset.reset();
}
void _onAnimateReset() {
_controller.value = _animationReset!.value;
if (_controllerReset.isAnimating) return;
_resetAndRemoveListener();
}
/// If the user tries to cause a transformation while the reset animation is
/// running, cancel the reset animation.
void _onInteractionStart(ScaleStartDetails details) {
if (_controllerReset.status != AnimationStatus.forward) return;
_animateResetStop();
}
void _animateResetStop() {
_controllerReset.stop();
_resetAndRemoveListener();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Theme.of(context).colorScheme.background,
leading: const CloseButton(color: Colors.black),
),
body: GestureDetector(
onTap: context.pop,
child: InteractiveViewer(
onInteractionStart: _onInteractionStart,
transformationController: _controller,
minScale: 0.7,
maxScale: 3,
child: Center(
child: GestureDetector(
onTapDown: _onTapDown,
onDoubleTap: _onDoubleTap,
child: Hero(
tag: widget.uri,
child: Image.asset(widget.uri.path),
),
),
),
),
),
);
}
}
| flutter-design-patterns/lib/widgets/image_view.dart/0 | {'file_path': 'flutter-design-patterns/lib/widgets/image_view.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 1415} |
# Copyright 2017 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Root analysis options shared among all Dart code in the respository. Based
# on the Fuchsia standard analysis options, with some changes.
linter:
# Full list available at http://dart-lang.github.io/linter/lints/options/options.html.
rules:
- always_declare_return_types
- always_put_control_body_on_new_line
- always_put_required_named_parameters_first
- always_require_non_null_named_parameters
- annotate_overrides
- avoid_as
- avoid_bool_literals_in_conditional_expressions
- avoid_catches_without_on_clauses
- avoid_catching_errors
- avoid_classes_with_only_static_members
- avoid_empty_else
# Not compatible with VS Code yet.
# - avoid_field_initializers_in_const_classes
- avoid_function_literals_in_foreach_calls
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_positional_boolean_parameters
- avoid_private_typedef_functions
# TODO: Change relative imports for package imports
# - avoid_relative_lib_imports
# This puts an unnecessary burden on API clients.
# - avoid_renaming_method_parameters
- avoid_return_types_on_setters
- avoid_returning_null
- avoid_returning_this
- avoid_single_cascade_in_expression_statements
- avoid_setters_without_getters
- avoid_slow_async_io
- avoid_types_as_parameter_names
- avoid_types_on_closure_parameters
- avoid_unused_constructor_parameters
- await_only_futures
- camel_case_types
- cancel_subscriptions
- cascade_invocations
- close_sinks
- comment_references
- constant_identifier_names
- control_flow_in_finally
- directives_ordering
- empty_catches
- empty_constructor_bodies
- empty_statements
- hash_and_equals
- implementation_imports
- invariant_booleans
- iterable_contains_unrelated_type
- join_return_with_assignment
- library_names
- library_prefixes
- list_remove_unrelated_type
- literal_only_boolean_expressions
- no_adjacent_strings_in_list
- no_duplicate_case_values
- non_constant_identifier_names
- omit_local_variable_types
- one_member_abstracts
- only_throw_errors
- overridden_fields
- package_api_docs
- package_names
- package_prefixed_library_names
- parameter_assignments
- prefer_adjacent_string_concatenation
- prefer_asserts_in_initializer_lists
- prefer_collection_literals
- prefer_conditional_assignment
# Disabled until bug is fixed
# https://github.com/dart-lang/linter/issues/995
# - prefer_const_constructors
- prefer_const_constructors_in_immutables
- prefer_const_declarations
- prefer_const_literals_to_create_immutables
- prefer_constructors_over_static_methods
- prefer_contains
- prefer_equal_for_default_values
# Add this when 'short' is better defined.
# - prefer_expression_function_bodies
- prefer_final_fields
- prefer_final_locals
# Seems to have false positive with await for.
# - prefer_foreach
- prefer_function_declarations_over_variables
- prefer_generic_function_type_aliases
- prefer_initializing_formals
- prefer_interpolation_to_compose_strings
- prefer_is_empty
- prefer_is_not_empty
- prefer_iterable_whereType
- prefer_single_quotes
- prefer_typing_uninitialized_variables
- public_member_api_docs
- recursive_getters
- slash_for_doc_comments
- sort_constructors_first
- sort_unnamed_constructors_first
- test_types_in_equals
- throw_in_finally
- type_annotate_public_apis
- type_init_formals
- unawaited_futures
- unnecessary_brace_in_string_interps
- unnecessary_getters_setters
- unnecessary_lambdas
- unnecessary_null_aware_assignments
- unnecessary_null_in_if_null_operators
- unnecessary_overrides
- unnecessary_parenthesis
- unnecessary_statements
- unnecessary_this
- unrelated_type_equality_checks
- use_rethrow_when_possible
- use_setters_to_change_properties
- use_string_buffers
- use_to_and_as_if_applicable
- valid_regexps
# Not compatible with VS Code yet.
# - void_checks
| flutter-desktop-embedding/analysis_options.yaml/0 | {'file_path': 'flutter-desktop-embedding/analysis_options.yaml', 'repo_id': 'flutter-desktop-embedding', 'token_count': 1613} |
include: ../../analysis_options.yaml
| flutter-desktop-embedding/plugins/color_panel/analysis_options.yaml/0 | {'file_path': 'flutter-desktop-embedding/plugins/color_panel/analysis_options.yaml', 'repo_id': 'flutter-desktop-embedding', 'token_count': 12} |
import 'dart:async';
import 'package:flutter/services.dart';
class ExamplePlugin {
static const MethodChannel _channel =
const MethodChannel('example_plugin');
static Future<String> get platformVersion async {
final String version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
}
| flutter-desktop-embedding/plugins/example_plugin/lib/example_plugin.dart/0 | {'file_path': 'flutter-desktop-embedding/plugins/example_plugin/lib/example_plugin.dart', 'repo_id': 'flutter-desktop-embedding', 'token_count': 95} |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:async';
import 'dart:ui';
import 'package:flutter/services.dart';
import 'platform_window.dart';
import 'screen.dart';
/// The name of the plugin's platform channel.
const String _windowSizeChannelName = 'flutter/windowsize';
/// The method name to request information about the available screens.
///
/// Returns a list of screen info maps; see keys below.
const String _getScreenListMethod = 'getScreenList';
/// The method name to request information about the window containing the
/// Flutter instance.
///
/// Returns a list of window info maps; see keys below.
const String _getWindowInfoMethod = 'getWindowInfo';
/// The method name to set the frame of a window.
///
/// Takes a frame array, as documented for the value of _frameKey.
const String _setWindowFrameMethod = 'setWindowFrame';
// Keys for screen and window maps returned by _getScreenListMethod.
/// The frame of a screen or window. The value is a list of four doubles:
/// [left, top, width, height]
const String _frameKey = 'frame';
/// The frame of a screen available for use by applications. The value format
/// is the same as _frameKey's.
///
/// Only used for screens.
const String _visibleFrameKey = 'visibleFrame';
/// The scale factor for a screen or window, as a double.
///
/// This is the number of pixels per screen coordinate, and thus the ratio
/// between sizes as seen by Flutter and sizes in native screen coordinates.
const String _scaleFactorKey = 'scaleFactor';
/// The screen containing this window, if any. The value is a screen map, or
/// null if the window is not visible on a screen.
///
/// Only used for windows.
///
/// If a window is on multiple screens, it is up to the platform to decide which
/// screen to report.
const String _screenKey = 'screen';
/// A singleton object that handles the interaction with the platform channel.
class WindowSizeChannel {
/// Private constructor.
WindowSizeChannel._();
final MethodChannel _platformChannel =
const MethodChannel(_windowSizeChannelName);
/// The static instance of the menu channel.
static final WindowSizeChannel instance = new WindowSizeChannel._();
/// Returns a list of screens.
Future<List<Screen>> getScreenList() async {
try {
final screenList = <Screen>[];
final response =
await _platformChannel.invokeMethod(_getScreenListMethod);
for (final screenInfo in response) {
screenList.add(_screenFromInfoMap(screenInfo));
}
return screenList;
} on PlatformException catch (e) {
print('Platform exception getting screen list: ${e.message}');
}
return <Screen>[];
}
/// Returns information about the window containing this Flutter instance.
Future<PlatformWindow> getWindowInfo() async {
try {
final response =
await _platformChannel.invokeMethod(_getWindowInfoMethod);
return PlatformWindow(
_rectFromLTWHList(response[_frameKey].cast<double>()),
response[_scaleFactorKey],
_screenFromInfoMap(response[_screenKey]));
} on PlatformException catch (e) {
print('Platform exception getting window info: ${e.message}');
}
return null;
}
/// Sets the frame of the window containing this Flutter instance, in
/// screen coordinates.
///
/// The platform may adjust the frame as necessary if the provided frame would
/// cause significant usability issues (e.g., a window with no visible portion
/// that can be used to move the window).
void setWindowFrame(Rect frame) async {
assert(!frame.isEmpty, 'Cannot set window frame to an empty rect.');
assert(frame.isFinite, 'Cannot set window frame to a non-finite rect.');
try {
await _platformChannel.invokeMethod(_setWindowFrameMethod,
[frame.left, frame.top, frame.width, frame.height]);
} on PlatformException catch (e) {
print('Platform exception setting window frame: ${e.message}');
}
}
/// Given an array of the form [left, top, width, height], return the
/// corresponding [Rect].
///
/// Used for frame deserialization in the platform channel.
Rect _rectFromLTWHList(List<double> ltwh) {
return Rect.fromLTWH(ltwh[0], ltwh[1], ltwh[2], ltwh[3]);
}
/// Given a map of information about a screen, return the corresponding
/// [Screen] object, or null.
///
/// Used for screen deserialization in the platform channel.
Screen _screenFromInfoMap(Map<dynamic, dynamic> map) {
if (map == null) {
return null;
}
return Screen(
_rectFromLTWHList(map[_frameKey].cast<double>()),
_rectFromLTWHList(map[_visibleFrameKey].cast<double>()),
map[_scaleFactorKey]);
}
}
| flutter-desktop-embedding/plugins/window_size/lib/src/window_size_channel.dart/0 | {'file_path': 'flutter-desktop-embedding/plugins/window_size/lib/src/window_size_channel.dart', 'repo_id': 'flutter-desktop-embedding', 'token_count': 1562} |
import 'package:flutter/material.dart';
import 'package:flutter_festival/i18n/translations.dart';
import 'package:flutter_festival/ui/explicit_animations/widgets/animated_builder_example.dart';
import 'package:flutter_festival/ui/explicit_animations/widgets/animated_widget_example.dart';
import 'package:flutter_festival/ui/styles/app_text_styles.dart';
class CustomExplicitAnimationsPage extends StatelessWidget {
const CustomExplicitAnimationsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Custom Explicit Animations'),
),
body: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 20),
child: Text(Translations.of(context)!
.get('custom_explicit_animations_description')),
),
const Text(
'AnimatedBuilder',
style: AppTextStyles.h1,
),
const SizedBox(height: 10),
const AnimatedBuilderExample(),
const SizedBox(height: 100),
const Text(
'AnimatedWidget',
style: AppTextStyles.h1,
),
const SizedBox(height: 10),
const AnimatedWidgetExample(),
],
),
),
);
}
}
| flutter-festival-session/lib/ui/explicit_animations/pages/custom_explicit_animations_page.dart/0 | {'file_path': 'flutter-festival-session/lib/ui/explicit_animations/pages/custom_explicit_animations_page.dart', 'repo_id': 'flutter-festival-session', 'token_count': 652} |
import 'package:flutter/material.dart';
class AppColors {
static const Color primary = Colors.deepPurple;
static const Color primaryAccent = Colors.deepPurpleAccent;
}
| flutter-festival-session/lib/ui/styles/app_colors.dart/0 | {'file_path': 'flutter-festival-session/lib/ui/styles/app_colors.dart', 'repo_id': 'flutter-festival-session', 'token_count': 52} |
include: package:lints/recommended.yaml
analyzer:
exclude:
- 'out/**'
- 'tool/icon_generator/**'
language:
strict-casts: true
linter:
rules:
- directives_ordering
- unawaited_futures
| flutter-intellij/analysis_options.yaml/0 | {'file_path': 'flutter-intellij/analysis_options.yaml', 'repo_id': 'flutter-intellij', 'token_count': 86} |
import 'package:flutter/material.dart';
class NotesApp extends StatelessWidget {
const NotesApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Scaffold(),
);
}
}
| flutter-notes-app/lib/notes_app.dart/0 | {'file_path': 'flutter-notes-app/lib/notes_app.dart', 'repo_id': 'flutter-notes-app', 'token_count': 134} |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_theme_switcher/presentation/providers/theme_provider.dart';
import 'package:flutter_theme_switcher/presentation/settings/pages/settings_page.dart';
import 'package:flutter_theme_switcher/presentation/styles/app_themes.dart';
import 'package:flutter_theme_switcher/services/service_locator.dart';
import 'package:flutter_theme_switcher/services/storage/storage_service.dart';
import 'package:provider/provider.dart';
void main() {
runZonedGuarded<Future<void>>(() async {
setUpServiceLocator();
final StorageService storageService = getIt<StorageService>();
await storageService.init();
runApp(App(
storageService: storageService,
));
}, (e, _) => throw e);
}
class App extends StatelessWidget {
final StorageService storageService;
const App({
Key? key,
required this.storageService,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => ThemeProvider(storageService),
),
],
child: Consumer<ThemeProvider>(
child: const SettingsPage(),
builder: (c, themeProvider, home) => MaterialApp(
title: 'Flutter Theme And Primary Color Switcher',
debugShowCheckedModeBanner: false,
theme: AppThemes.main(
primaryColor: themeProvider.selectedPrimaryColor,
),
darkTheme: AppThemes.main(
isDark: true,
primaryColor: themeProvider.selectedPrimaryColor,
),
themeMode: themeProvider.selectedThemeMode,
home: home,
),
),
);
}
}
| flutter-theme-switcher/lib/main.dart/0 | {'file_path': 'flutter-theme-switcher/lib/main.dart', 'repo_id': 'flutter-theme-switcher', 'token_count': 667} |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_theme_switcher/presentation/settings/widgets/primary_color_option.dart';
import 'package:flutter_theme_switcher/presentation/styles/app_colors.dart';
import 'package:flutter_theme_switcher/presentation/styles/app_themes.dart';
import '../../pump_app.dart';
void main() {
testWidgets(
'Has transparent Border if not selected',
(WidgetTester tester) async {
await tester.pumpRawApp(
const PrimaryColorOption(
color: AppColors.primary,
isSelected: false,
),
);
await tester.pumpAndSettle();
final finder = find.byKey(
Key('__${AppColors.primary.value}_color_option__'),
);
expect(finder, findsOneWidget);
final container = tester.widget<AnimatedContainer>(finder);
final BoxDecoration decoration = container.decoration as BoxDecoration;
expect(decoration.border!.top.color, equals(Colors.transparent));
},
);
testWidgets('Has gray Border if selected', (WidgetTester tester) async {
await tester.pumpRawApp(
const PrimaryColorOption(
color: AppColors.primary,
isSelected: true,
),
);
await tester.pumpAndSettle();
final finder = find.byKey(
Key('__${AppColors.primary.value}_color_option__'),
);
expect(finder, findsOneWidget);
final container = tester.widget<AnimatedContainer>(finder);
final BoxDecoration decoration = container.decoration as BoxDecoration;
expect(
decoration.border!.top.color,
equals(AppThemes.main().dividerColor),
);
});
}
| flutter-theme-switcher/test/settings/widgets/primary_color_option_test.dart/0 | {'file_path': 'flutter-theme-switcher/test/settings/widgets/primary_color_option_test.dart', 'repo_id': 'flutter-theme-switcher', 'token_count': 636} |
import 'package:flutter/material.dart';
class AvatarImage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(color: Colors.grey, width: 2),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image.asset(
'assets/images/avatar.png',
fit: BoxFit.cover,
height: 400,
width: double.infinity,
alignment: Alignment.topCenter,
),
),
);
}
}
| flutter-tutorials/lib/animated-cross-fade/widgets/avatar_image.dart/0 | {'file_path': 'flutter-tutorials/lib/animated-cross-fade/widgets/avatar_image.dart', 'repo_id': 'flutter-tutorials', 'token_count': 270} |
class Tutorial {
String title;
String description;
String? tutorialLink;
String? tutorialPageRoute;
Tutorial({
required this.title,
required this.description,
this.tutorialLink,
this.tutorialPageRoute,
});
}
| flutter-tutorials/lib/data/models/tutorial.dart/0 | {'file_path': 'flutter-tutorials/lib/data/models/tutorial.dart', 'repo_id': 'flutter-tutorials', 'token_count': 77} |
import 'package:flutter/material.dart';
import 'package:interactive_gallery/pages/image_gallery_item_page.dart';
import 'package:interactive_gallery/utils/images.dart';
import 'package:interactive_gallery/utils/routes.dart';
import 'package:interactive_gallery/widgets/distorted_interactive_grid.dart';
import 'package:interactive_gallery/widgets/image_gallery_item.dart';
class ImageGalleryPage extends StatelessWidget {
const ImageGalleryPage({super.key});
static List<String> items = gifs;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
extendBody: true,
body: DistortedInteractiveGrid(
maxItemsPerViewport: 10,
children: List.generate(
items.length,
(index) => GestureDetector(
onTap: () {
Navigator.of(context).push(
createFadeInRoute(
routePageBuilder: (
BuildContext context,
Animation<double> animation,
_,
) {
return ImageGalleryItemPage(
images: items,
initialIndex: index,
);
},
),
);
},
child: ImageGalleryItem(
heroTag: '__hero_${index}__',
imagePath: items[index],
),
),
),
),
);
}
}
| flutter-world-of-shaders/examples/interactive_gallery/lib/pages/image_gallery_page.dart/0 | {'file_path': 'flutter-world-of-shaders/examples/interactive_gallery/lib/pages/image_gallery_page.dart', 'repo_id': 'flutter-world-of-shaders', 'token_count': 735} |
name: interactive_gallery
description: Interactive gallery with shader distortion effect
version: 1.0.0+1
environment:
sdk: '>=2.19.4 <3.0.0'
dependencies:
cached_network_image: ^3.2.3
collection: ^1.17.0
core:
path: ../../packages/core
cupertino_icons: ^1.0.5
flutter:
sdk: flutter
flutter_shaders: ^0.1.1
dev_dependencies:
flutter_test:
sdk: flutter
very_good_analysis: ^4.0.0+1
flutter:
uses-material-design: true
assets:
- assets/
shaders:
- packages/core/shaders/pincushion.glsl | flutter-world-of-shaders/examples/interactive_gallery/pubspec.yaml/0 | {'file_path': 'flutter-world-of-shaders/examples/interactive_gallery/pubspec.yaml', 'repo_id': 'flutter-world-of-shaders', 'token_count': 224} |
name: core
description: A Very Good Project created by Very Good CLI.
version: 0.1.0+1
publish_to: none
environment:
sdk: ">=2.18.0 <3.0.0"
flutter: 3.3.0
dependencies:
flutter:
sdk: flutter
flutter_shaders: ^0.1.1
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
very_good_analysis: ^4.0.0+1 | flutter-world-of-shaders/packages/core/pubspec.yaml/0 | {'file_path': 'flutter-world-of-shaders/packages/core/pubspec.yaml', 'repo_id': 'flutter-world-of-shaders', 'token_count': 150} |
// Copyright 2014 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:complex_layout/src/app.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
/// The speed, in pixels per second, that the drag gestures should end with.
const double speed = 1500.0;
/// The number of down drags and the number of up drags. The total number of
/// gestures is twice this number.
const int maxIterations = 4;
/// The time that is allowed between gestures for the fling effect to settle.
const Duration pauses = Duration(milliseconds: 500);
Future<void> main() async {
final Completer<void> ready = Completer<void>();
runApp(GestureDetector(
onTap: () {
debugPrint('Received tap.');
ready.complete();
},
behavior: HitTestBehavior.opaque,
child: const IgnorePointer(
child: ComplexLayoutApp(),
),
));
await SchedulerBinding.instance.endOfFrame;
/// Wait 50ms to allow the raster thread to actually put up the frame. (The
/// endOfFrame future ends when we send the data to the engine, before
/// the raster thread has had a chance to rasterize, etc.)
await Future<void>.delayed(const Duration(milliseconds: 50));
debugPrint('==== MEMORY BENCHMARK ==== READY ====');
await ready.future; // waits for tap sent by devicelab task
debugPrint('Continuing...');
// remove onTap handler, enable pointer events for app
runApp(GestureDetector(
child: const IgnorePointer(
ignoring: false,
child: ComplexLayoutApp(),
),
));
await SchedulerBinding.instance.endOfFrame;
final WidgetController controller = LiveWidgetController(WidgetsBinding.instance);
// Scroll down
for (int iteration = 0; iteration < maxIterations; iteration += 1) {
debugPrint('Scroll down... $iteration/$maxIterations');
await controller.fling(find.byType(ListView), const Offset(0.0, -700.0), speed);
await Future<void>.delayed(pauses);
}
// Scroll up
for (int iteration = 0; iteration < maxIterations; iteration += 1) {
debugPrint('Scroll up... $iteration/$maxIterations');
await controller.fling(find.byType(ListView), const Offset(0.0, 300.0), speed);
await Future<void>.delayed(pauses);
}
debugPrint('==== MEMORY BENCHMARK ==== DONE ====');
}
| flutter/dev/benchmarks/complex_layout/test_memory/scroll_perf.dart/0 | {'file_path': 'flutter/dev/benchmarks/complex_layout/test_memory/scroll_perf.dart', 'repo_id': 'flutter', 'token_count': 776} |
// Copyright 2014 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';
class AnimationWithMicrotasks extends StatefulWidget {
const AnimationWithMicrotasks({super.key});
@override
State<AnimationWithMicrotasks> createState() => _AnimationWithMicrotasksState();
}
class _AnimationWithMicrotasksState extends State<AnimationWithMicrotasks> {
final _ChunkedWork work = _ChunkedWork();
@override
void initState() {
super.initState();
work.start();
}
@override
void dispose() {
work.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return const Scaffold(
backgroundColor: Colors.grey,
body: Center(
child: SizedBox(
width: 200,
height: 100,
child: LinearProgressIndicator(),
),
),
);
}
}
class _ChunkedWork {
bool _canceled = false;
Future<void> start() async {
// Run 100 pieces of synchronous work.
// Chunked up to allow frames to be drawn.
for (int i = 0; i < 100; ++i) {
_chunkedSynchronousWork();
}
}
void cancel() {
_canceled = true;
}
Future<void> _chunkedSynchronousWork() async {
while (!_canceled) {
// Yield to the event loop to let engine draw frames.
await Future<void>.delayed(Duration.zero);
// Perform synchronous computation for 1 ms.
_syncComputationFor(const Duration(milliseconds: 1));
}
}
void _syncComputationFor(Duration duration) {
final Stopwatch sw = Stopwatch()..start();
while (!_canceled && sw.elapsed < duration) {}
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/animation_with_microtasks.dart/0 | {'file_path': 'flutter/dev/benchmarks/macrobenchmarks/lib/src/animation_with_microtasks.dart', 'repo_id': 'flutter', 'token_count': 626} |
// Copyright 2014 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:math' as math;
import 'dart:ui';
// Used to randomize data.
//
// Using constant seed for reproducibility.
final math.Random _random = math.Random(0);
/// Random words used by benchmarks that contain text.
final List<String> lipsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing '
'elit. Vivamus ut ligula a neque mattis posuere. Sed suscipit lobortis '
'sodales. Morbi sed neque molestie, hendrerit odio ac, aliquam velit. '
'Curabitur non quam sit amet nibh sollicitudin ultrices. Fusce '
'ullamcorper bibendum commodo. In et feugiat nisl. Aenean vulputate in '
'odio vestibulum ultricies. Nunc dolor libero, hendrerit eu urna sit '
'amet, pretium iaculis nulla. Ut porttitor nisl et leo iaculis, vel '
'fringilla odio pulvinar. Ut eget ligula id odio auctor egestas nec a '
'nisl. Aliquam luctus dolor et magna posuere mattis. '
'Suspendisse fringilla nisl et massa congue, eget '
'imperdiet lectus porta. Vestibulum sed dui sed dui porta imperdiet ut in risus. '
'Fusce diam purus, faucibus id accumsan sit amet, semper a sem. Sed aliquam '
'lacus eget libero ultricies, quis hendrerit tortor posuere. Pellentesque '
'sagittis eu est in maximus. Proin auctor fringilla dolor in hendrerit. Nam '
'pulvinar rhoncus tellus. Nullam vel mauris semper, volutpat tellus at, sagittis '
'lectus. Donec vitae nibh mauris. Morbi posuere sem id eros tristique tempus. '
'Vivamus lacinia sapien neque, eu semper purus gravida ut.'.split(' ');
/// Generates strings and builds pre-laid out paragraphs to be used by
/// benchmarks.
List<Paragraph> generateLaidOutParagraphs({
required int paragraphCount,
required int minWordCountPerParagraph,
required int maxWordCountPerParagraph,
required double widthConstraint,
required Color color,
}) {
final List<Paragraph> strings = <Paragraph>[];
int wordPointer = 0; // points to the next word in lipsum to extract
for (int i = 0; i < paragraphCount; i++) {
final int wordCount = minWordCountPerParagraph +
_random.nextInt(maxWordCountPerParagraph - minWordCountPerParagraph + 1);
final List<String> string = <String>[];
for (int j = 0; j < wordCount; j++) {
string.add(lipsum[wordPointer]);
wordPointer = (wordPointer + 1) % lipsum.length;
}
final ParagraphBuilder builder =
ParagraphBuilder(ParagraphStyle(fontFamily: 'sans-serif'))
..pushStyle(TextStyle(color: color, fontSize: 18.0))
..addText(string.join(' '))
..pop();
final Paragraph paragraph = builder.build();
// Fill half the screen.
paragraph.layout(ParagraphConstraints(width: widthConstraint));
strings.add(paragraph);
}
return strings;
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/test_data.dart/0 | {'file_path': 'flutter/dev/benchmarks/macrobenchmarks/lib/src/web/test_data.dart', 'repo_id': 'flutter', 'token_count': 1025} |
// Copyright 2014 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 '../common.dart';
const int _kNumIterations = 100000;
void main() {
assert(false,
"Don't run benchmarks in debug mode! Use 'flutter run --release'.");
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
const StandardMessageCodec codec = StandardMessageCodec();
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(null);
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec null',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_null',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(12345);
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec int',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_int',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage('This is a performance test.');
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec string',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_string',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(<Object>[1234, 'This is a performance test.', 1.25, true]);
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec heterogenous list',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_heterogenous_list',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(<String, Object>{
'integer': 1234,
'string': 'This is a performance test.',
'float': 1.25,
'boolean': true,
});
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec heterogenous map',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_heterogenous_map',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage('special chars >\u263A\u{1F602}<');
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec unicode',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_unicode',
);
watch.reset();
printer.printToStdout();
}
| flutter/dev/benchmarks/microbenchmarks/lib/foundation/standard_message_codec_bench.dart/0 | {'file_path': 'flutter/dev/benchmarks/microbenchmarks/lib/foundation/standard_message_codec_bench.dart', 'repo_id': 'flutter', 'token_count': 1035} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:microbenchmarks/common.dart';
List<Object?> _makeTestBuffer(int size) {
final List<Object?> answer = <Object?>[];
for (int i = 0; i < size; ++i) {
switch (i % 9) {
case 0:
answer.add(1);
break;
case 1:
answer.add(math.pow(2, 65));
break;
case 2:
answer.add(1234.0);
break;
case 3:
answer.add(null);
break;
case 4:
answer.add(<int>[1234]);
break;
case 5:
answer.add(<String, int>{'hello': 1234});
break;
case 6:
answer.add('this is a test');
break;
case 7:
answer.add(true);
break;
case 8:
answer.add(Uint8List(64));
break;
}
}
return answer;
}
Future<double> _runBasicStandardSmall(
BasicMessageChannel<Object?> basicStandard,
int count,
) async {
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < count; ++i) {
await basicStandard.send(1234);
}
watch.stop();
return watch.elapsedMicroseconds / count;
}
class _Counter {
int count = 0;
}
void _runBasicStandardParallelRecurse(
BasicMessageChannel<Object?> basicStandard,
_Counter counter,
int count,
Completer<int> completer,
Object? payload,
) {
counter.count += 1;
if (counter.count == count) {
completer.complete(counter.count);
} else if (counter.count < count) {
basicStandard.send(payload).then((Object? result) {
_runBasicStandardParallelRecurse(
basicStandard, counter, count, completer, payload);
});
}
}
Future<double> _runBasicStandardParallel(
BasicMessageChannel<Object?> basicStandard,
int count,
Object? payload,
int parallel,
) async {
final Stopwatch watch = Stopwatch();
final Completer<int> completer = Completer<int>();
final _Counter counter = _Counter();
watch.start();
for (int i = 0; i < parallel; ++i) {
basicStandard.send(payload).then((Object? result) {
_runBasicStandardParallelRecurse(
basicStandard, counter, count, completer, payload);
});
}
await completer.future;
watch.stop();
return watch.elapsedMicroseconds / count;
}
Future<double> _runBasicStandardLarge(
BasicMessageChannel<Object?> basicStandard,
List<Object?> largeBuffer,
int count,
) async {
int size = 0;
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < count; ++i) {
final List<Object?>? result =
await basicStandard.send(largeBuffer) as List<Object?>?;
// This check should be tiny compared to the actual channel send/receive.
size += (result == null) ? 0 : result.length;
}
watch.stop();
if (size != largeBuffer.length * count) {
throw Exception(
"There is an error with the echo channel, the results don't add up: $size",
);
}
return watch.elapsedMicroseconds / count;
}
Future<double> _runBasicBinary(
BasicMessageChannel<ByteData> basicBinary,
ByteData buffer,
int count,
) async {
int size = 0;
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < count; ++i) {
final ByteData? result = await basicBinary.send(buffer);
// This check should be tiny compared to the actual channel send/receive.
size += (result == null) ? 0 : result.lengthInBytes;
}
watch.stop();
if (size != buffer.lengthInBytes * count) {
throw Exception(
"There is an error with the echo channel, the results don't add up: $size",
);
}
return watch.elapsedMicroseconds / count;
}
Future<void> _runTest({
required Future<double> Function(int) test,
required BasicMessageChannel<Object?> resetChannel,
required BenchmarkResultPrinter printer,
required String description,
required String name,
required int numMessages,
}) async {
print('running $name');
resetChannel.send(true);
// Prime test.
await test(1);
printer.addResult(
description: description,
value: await test(numMessages),
unit: 'µs',
name: name,
);
}
Future<void> _runTests() async {
if (kDebugMode) {
throw Exception(
"Must be run in profile mode! Use 'flutter run --profile'.",
);
}
const BasicMessageChannel<Object?> resetChannel =
BasicMessageChannel<Object?>(
'dev.flutter.echo.reset',
StandardMessageCodec(),
);
const BasicMessageChannel<Object?> basicStandard =
BasicMessageChannel<Object?>(
'dev.flutter.echo.basic.standard',
StandardMessageCodec(),
);
const BasicMessageChannel<ByteData> basicBinary =
BasicMessageChannel<ByteData>(
'dev.flutter.echo.basic.binary',
BinaryCodec(),
);
/// WARNING: Don't change the following line of code, it will invalidate
/// `Large` tests. Instead make a different test. The size of largeBuffer
/// serialized is 14214 bytes.
final List<Object?> largeBuffer = _makeTestBuffer(1000);
final ByteData largeBufferBytes =
const StandardMessageCodec().encodeMessage(largeBuffer)!;
final ByteData oneMB = ByteData(1024 * 1024);
const int numMessages = 2500;
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
await _runTest(
test: (int x) => _runBasicStandardSmall(basicStandard, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/StandardMessageCodec/Flutter->Host/Small',
name: 'platform_channel_basic_standard_2host_small',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicStandardLarge(basicStandard, largeBuffer, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/StandardMessageCodec/Flutter->Host/Large',
name: 'platform_channel_basic_standard_2host_large',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicBinary(basicBinary, largeBufferBytes, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/BinaryCodec/Flutter->Host/Large',
name: 'platform_channel_basic_binary_2host_large',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicBinary(basicBinary, oneMB, x),
resetChannel: resetChannel,
printer: printer,
description: 'BasicMessageChannel/BinaryCodec/Flutter->Host/1MB',
name: 'platform_channel_basic_binary_2host_1MB',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicStandardParallel(basicStandard, x, 1234, 3),
resetChannel: resetChannel,
printer: printer,
description:
'BasicMessageChannel/StandardMessageCodec/Flutter->Host/SmallParallel3',
name: 'platform_channel_basic_standard_2host_small_parallel_3',
numMessages: numMessages,
);
// Background platform channels aren't yet implemented for iOS.
const BasicMessageChannel<Object?> backgroundStandard =
BasicMessageChannel<Object?>(
'dev.flutter.echo.background.standard',
StandardMessageCodec(),
);
await _runTest(
test: (int x) => _runBasicStandardSmall(backgroundStandard, x),
resetChannel: resetChannel,
printer: printer,
description:
'BasicMessageChannel/StandardMessageCodec/Flutter->Host (background)/Small',
name: 'platform_channel_basic_standard_2hostbackground_small',
numMessages: numMessages,
);
await _runTest(
test: (int x) => _runBasicStandardParallel(backgroundStandard, x, 1234, 3),
resetChannel: resetChannel,
printer: printer,
description:
'BasicMessageChannel/StandardMessageCodec/Flutter->Host (background)/SmallParallel3',
name: 'platform_channel_basic_standard_2hostbackground_small_parallel_3',
numMessages: numMessages,
);
printer.printToStdout();
}
class _BenchmarkWidget extends StatefulWidget {
const _BenchmarkWidget(this.tests);
final Future<void> Function() tests;
@override
_BenchmarkWidgetState createState() => _BenchmarkWidgetState();
}
class _BenchmarkWidgetState extends State<_BenchmarkWidget> {
@override
void initState() {
widget.tests();
super.initState();
}
@override
Widget build(BuildContext context) => Container();
}
void main() {
runApp(const _BenchmarkWidget(_runTests));
}
| flutter/dev/benchmarks/platform_channels_benchmarks/lib/main.dart/0 | {'file_path': 'flutter/dev/benchmarks/platform_channels_benchmarks/lib/main.dart', 'repo_id': 'flutter', 'token_count': 3005} |
// Copyright 2014 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.
// THE FOLLOWING FILES WERE GENERATED BY `flutter gen-l10n`.
import 'stock_strings.dart';
/// The translations for Spanish Castilian (`es`).
class StockStringsEs extends StockStrings {
StockStringsEs([super.locale = 'es']);
@override
String get title => 'Acciones';
@override
String get market => 'MERCADO';
@override
String get portfolio => 'CARTERA';
}
| flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_es.dart/0 | {'file_path': 'flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stock_strings_es.dart', 'repo_id': 'flutter', 'token_count': 169} |
// Copyright 2014 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.
/// Sample Code
///
/// Should not be tag-enforced, no analysis failures should be found.
///
/// {@tool snippet}
/// Sample invocations of [matchesGoldenFile].
///
/// ```dart
/// await expectLater(
/// find.text('Save'),
/// matchesGoldenFile('save.png'),
/// );
///
/// await expectLater(
/// image,
/// matchesGoldenFile('save.png'),
/// );
///
/// await expectLater(
/// imageFuture,
/// matchesGoldenFile(
/// 'save.png',
/// version: 2,
/// ),
/// );
///
/// await expectLater(
/// find.byType(MyWidget),
/// matchesGoldenFile('goldens/myWidget.png'),
/// );
/// ```
/// {@end-tool}
///
String? foo;
// Other comments
// matchesGoldenFile('comment.png');
String literal = 'matchesGoldenFile()'; // flutter_ignore: golden_tag (see analyze.dart)
| flutter/dev/bots/test/analyze-test-input/root/packages/foo/golden_doc.dart/0 | {'file_path': 'flutter/dev/bots/test/analyze-test-input/root/packages/foo/golden_doc.dart', 'repo_id': 'flutter', 'token_count': 306} |
// Copyright 2014 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' as io;
import 'package:conductor_core/conductor_core.dart';
import 'package:conductor_core/packages_autoroller.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import './common.dart';
import '../bin/packages_autoroller.dart' show run;
void main() {
const String flutterRoot = '/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/conductor';
const String githubClient = 'gh';
const String token = '0123456789abcdef';
const String orgName = 'flutter-roller';
const String mirrorUrl = 'https://githost.com/flutter-roller/flutter.git';
final String localPathSeparator = const LocalPlatform().pathSeparator;
final String localOperatingSystem = const LocalPlatform().operatingSystem;
late MemoryFileSystem fileSystem;
late TestStdio stdio;
late FrameworkRepository framework;
late PackageAutoroller autoroller;
late FakeProcessManager processManager;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
processManager = FakeProcessManager.empty();
final FakePlatform platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(localPathSeparator),
},
operatingSystem: localOperatingSystem,
pathSeparator: localPathSeparator,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory)
..createSync(recursive: true),
platform: platform,
processManager: processManager,
stdio: stdio,
);
framework = FrameworkRepository(
checkouts,
mirrorRemote: const Remote(
name: RemoteName.mirror,
url: mirrorUrl,
),
);
autoroller = PackageAutoroller(
githubClient: githubClient,
token: token,
framework: framework,
orgName: orgName,
processManager: processManager,
stdio: stdio,
);
});
test('GitHub token is redacted from exceptions while pushing', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'remote',
'add',
'mirror',
mirrorUrl,
]),
const FakeCommand(command: <String>[
'git',
'fetch',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
FrameworkRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: 'deadbeef'),
const FakeCommand(command: <String>[
'git',
'ls-remote',
'--heads',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
'-b',
'packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'help',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'--verbose',
'update-packages',
'--force-upgrade',
]),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
], stdout: '''
M packages/foo/pubspec.yaml
M packages/bar/pubspec.yaml
M dev/integration_tests/test_foo/pubspec.yaml
'''),
const FakeCommand(command: <String>[
'git',
'add',
'--all',
]),
const FakeCommand(command: <String>[
'git',
'commit',
'--message',
'roll packages',
'--author="fluttergithubbot <fluttergithubbot@google.com>"',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: '000deadbeef'),
const FakeCommand(command: <String>[
'git',
'push',
'https://$token@github.com/$orgName/flutter.git',
'packages-autoroller-branch-1:packages-autoroller-branch-1',
], exitCode: 1, stderr: 'Authentication error!'),
]);
await expectLater(
() async {
final Future<void> rollFuture = autoroller.roll();
await controller.stream.drain();
await rollFuture;
},
throwsA(isA<Exception>().having(
(Exception exc) => exc.toString(),
'message',
isNot(contains(token)),
)),
);
});
test('Does not attempt to roll if bot already has an open PR', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'gh',
'pr',
'list',
'--author',
'fluttergithubbot',
'--repo',
'flutter/flutter',
'--state',
'open',
'--label',
'tool',
'--json',
'number',
// Non empty array means there are open PRs by the bot with the tool label
// We expect no further commands to be run
], stdout: '[{"number": 123}]'),
]);
final Future<void> rollFuture = autoroller.roll();
await controller.stream.drain();
await rollFuture;
expect(processManager, hasNoRemainingExpectations);
expect(stdio.stdout, contains('fluttergithubbot already has open tool PRs'));
expect(stdio.stdout, contains(r'[{number: 123}]'));
});
test('Does not commit or create a PR if no changes were made', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'gh',
'pr',
'list',
'--author',
'fluttergithubbot',
'--repo',
'flutter/flutter',
'--state',
'open',
'--label',
'tool',
'--json',
'number',
// Returns empty array, as there are no other open roll PRs from the bot
], stdout: '[]'),
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'remote',
'add',
'mirror',
mirrorUrl,
]),
const FakeCommand(command: <String>[
'git',
'fetch',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
FrameworkRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: 'deadbeef'),
const FakeCommand(command: <String>[
'git',
'ls-remote',
'--heads',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
'-b',
'packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'help',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'--verbose',
'update-packages',
'--force-upgrade',
]),
// Because there is no stdout to git status, the script should exit cleanly here
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
]);
final Future<void> rollFuture = autoroller.roll();
await controller.stream.drain();
await rollFuture;
expect(processManager, hasNoRemainingExpectations);
});
test('can roll with correct inputs', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'gh',
'pr',
'list',
'--author',
'fluttergithubbot',
'--repo',
'flutter/flutter',
'--state',
'open',
'--label',
'tool',
'--json',
'number',
// Returns empty array, as there are no other open roll PRs from the bot
], stdout: '[]'),
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'remote',
'add',
'mirror',
mirrorUrl,
]),
const FakeCommand(command: <String>[
'git',
'fetch',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
FrameworkRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: 'deadbeef'),
const FakeCommand(command: <String>[
'git',
'ls-remote',
'--heads',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
'-b',
'packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'help',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'--verbose',
'update-packages',
'--force-upgrade',
]),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
], stdout: '''
M packages/foo/pubspec.yaml
M packages/bar/pubspec.yaml
M dev/integration_tests/test_foo/pubspec.yaml
'''),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
], stdout: '''
M packages/foo/pubspec.yaml
M packages/bar/pubspec.yaml
M dev/integration_tests/test_foo/pubspec.yaml
'''),
const FakeCommand(command: <String>[
'git',
'add',
'--all',
]),
const FakeCommand(command: <String>[
'git',
'commit',
'--message',
'roll packages',
'--author="fluttergithubbot <fluttergithubbot@gmail.com>"',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: '000deadbeef'),
const FakeCommand(command: <String>[
'git',
'push',
'https://$token@github.com/$orgName/flutter.git',
'packages-autoroller-branch-1:packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'gh',
'pr',
'create',
'--title',
'Roll pub packages',
'--body',
'This PR was generated by `flutter update-packages --force-upgrade`.',
'--head',
'flutter-roller:packages-autoroller-branch-1',
'--base',
FrameworkRepository.defaultBranch,
'--label',
'tool',
'--label',
'autosubmit',
]),
const FakeCommand(command: <String>[
'gh',
'auth',
'logout',
'--hostname',
'github.com',
]),
]);
final Future<void> rollFuture = autoroller.roll();
final String givenToken =
await controller.stream.transform(const Utf8Decoder()).join();
expect(givenToken.trim(), token);
await rollFuture;
expect(processManager, hasNoRemainingExpectations);
});
group('command argument validations', () {
const String tokenPath = '/path/to/token';
const String mirrorRemote = 'https://githost.com/org/project';
test('validates that file exists at --token option', () async {
await expectLater(
() => run(
<String>['--token', tokenPath, '--mirror-remote', mirrorRemote],
fs: fileSystem,
processManager: processManager,
),
throwsA(isA<ArgumentError>().having(
(ArgumentError err) => err.message,
'message',
contains('Provided token path $tokenPath but no file exists at'),
)),
);
expect(processManager, hasNoRemainingExpectations);
});
test('validates that the token file is not empty', () async {
fileSystem.file(tokenPath)
..createSync(recursive: true)
..writeAsStringSync('');
await expectLater(
() => run(
<String>['--token', tokenPath, '--mirror-remote', mirrorRemote],
fs: fileSystem,
processManager: processManager,
),
throwsA(isA<ArgumentError>().having(
(ArgumentError err) => err.message,
'message',
contains('Tried to read a GitHub access token from file $tokenPath but it was empty'),
)),
);
expect(processManager, hasNoRemainingExpectations);
});
});
}
| flutter/dev/conductor/core/test/packages_autoroller_test.dart/0 | {'file_path': 'flutter/dev/conductor/core/test/packages_autoroller_test.dart', 'repo_id': 'flutter', 'token_count': 6652} |
// Copyright 2014 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 'package:args/args.dart';
import 'package:flutter_devicelab/framework/ab.dart';
import 'package:flutter_devicelab/framework/utils.dart';
String kRawSummaryOpt = 'raw-summary';
String kTabTableOpt = 'tsv-table';
String kAsciiTableOpt = 'ascii-table';
void _usage(String error) {
stderr.writeln(error);
stderr.writeln('Usage:\n');
stderr.writeln(_argParser.usage);
exitCode = 1;
}
Future<void> main(List<String> rawArgs) async {
ArgResults args;
try {
args = _argParser.parse(rawArgs);
} on FormatException catch (error) {
_usage('${error.message}\n');
return;
}
final List<String> jsonFiles = args.rest.isNotEmpty ? args.rest : <String>[ 'ABresults.json' ];
for (final String filename in jsonFiles) {
final File file = File(filename);
if (!file.existsSync()) {
_usage('File "$filename" does not exist');
return;
}
ABTest test;
try {
test = ABTest.fromJsonMap(
const JsonDecoder().convert(await file.readAsString()) as Map<String, dynamic>
);
} catch(error) {
_usage('Could not parse json file "$filename"');
return;
}
if (args[kRawSummaryOpt] as bool) {
section('Raw results for "$filename"');
print(test.rawResults());
}
if (args[kTabTableOpt] as bool) {
section('A/B comparison for "$filename"');
print(test.printSummary());
}
if (args[kAsciiTableOpt] as bool) {
section('Formatted summary for "$filename"');
print(test.asciiSummary());
}
}
}
/// Command-line options for the `summarize.dart` command.
final ArgParser _argParser = ArgParser()
..addFlag(
kAsciiTableOpt,
defaultsTo: true,
help: 'Prints the summary in a table formatted nicely for terminal output.',
)
..addFlag(
kTabTableOpt,
defaultsTo: true,
help: 'Prints the summary in a table with tabs for easy spreadsheet entry.',
)
..addFlag(
kRawSummaryOpt,
defaultsTo: true,
help: 'Prints all per-run data collected by the A/B test formatted with\n'
'tabs for easy spreadsheet entry.',
);
| flutter/dev/devicelab/bin/summarize.dart/0 | {'file_path': 'flutter/dev/devicelab/bin/summarize.dart', 'repo_id': 'flutter', 'token_count': 860} |
// Copyright 2014 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:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:flutter_devicelab/tasks/new_gallery.dart';
import 'package:path/path.dart' as path;
Future<void> main() async {
deviceOperatingSystem = DeviceOperatingSystem.android;
final Directory galleryParentDir =
Directory.systemTemp.createTempSync('flutter_new_gallery_test.');
final Directory galleryDir =
Directory(path.join(galleryParentDir.path, 'gallery'));
try {
await task(
NewGalleryPerfTest(
galleryDir,
timelineFileName: 'transitions-crane',
dartDefine: 'onlyCrane=true',
).run,
);
} finally {
rmTree(galleryParentDir);
}
}
| flutter/dev/devicelab/bin/tasks/new_gallery__crane_perf.dart/0 | {'file_path': 'flutter/dev/devicelab/bin/tasks/new_gallery__crane_perf.dart', 'repo_id': 'flutter', 'token_count': 342} |
// Copyright 2014 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 library provides constants and matchers for testing the Android
/// accessibility implementation in a flutter driver environment.
library android_semantics_testing;
export 'src/common.dart';
export 'src/constants.dart';
export 'src/matcher.dart';
| flutter/dev/integration_tests/android_semantics_testing/lib/android_semantics_testing.dart/0 | {'file_path': 'flutter/dev/integration_tests/android_semantics_testing/lib/android_semantics_testing.dart', 'repo_id': 'flutter', 'token_count': 108} |
// Copyright 2014 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/material.dart';
import '../../gallery/demo.dart';
const Color _kKeyUmbraOpacity = Color(0x33000000); // alpha = 0.2
const Color _kKeyPenumbraOpacity = Color(0x24000000); // alpha = 0.14
const Color _kAmbientShadowOpacity = Color(0x1F000000); // alpha = 0.12
class CupertinoSegmentedControlDemo extends StatefulWidget {
const CupertinoSegmentedControlDemo({super.key});
static const String routeName = 'cupertino/segmented_control';
@override
State<CupertinoSegmentedControlDemo> createState() => _CupertinoSegmentedControlDemoState();
}
class _CupertinoSegmentedControlDemoState extends State<CupertinoSegmentedControlDemo> {
final Map<int, Widget> children = const <int, Widget>{
0: Text('Small'),
1: Text('Medium'),
2: Text('Large'),
};
final Map<int, Widget> icons = const <int, Widget>{
0: Center(
child: FlutterLogo(
size: 100.0,
),
),
1: Center(
child: FlutterLogo(
size: 200.0,
),
),
2: Center(
child: FlutterLogo(
size: 300.0,
),
),
};
int? currentSegment = 0;
void onValueChanged(int? newValue) {
setState(() {
currentSegment = newValue;
});
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Segmented Control'),
// We're specifying a back label here because the previous page is a
// Material page. CupertinoPageRoutes could auto-populate these back
// labels.
previousPageTitle: 'Cupertino',
trailing: CupertinoDemoDocumentationButton(CupertinoSegmentedControlDemo.routeName),
),
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle.copyWith(fontSize: 13),
child: SafeArea(
child: Column(
children: <Widget>[
const Padding(padding: EdgeInsets.all(16.0)),
SizedBox(
width: 500.0,
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: onValueChanged,
groupValue: currentSegment,
),
),
SizedBox(
width: 500,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: CupertinoSlidingSegmentedControl<int>(
children: children,
onValueChanged: onValueChanged,
groupValue: currentSegment,
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 32.0,
horizontal: 16.0,
),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Builder(
builder: (BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(
vertical: 64.0,
horizontal: 16.0,
),
decoration: BoxDecoration(
color: CupertinoTheme.of(context).scaffoldBackgroundColor,
borderRadius: BorderRadius.circular(3.0),
boxShadow: const <BoxShadow>[
BoxShadow(
offset: Offset(0.0, 3.0),
blurRadius: 5.0,
spreadRadius: -1.0,
color: _kKeyUmbraOpacity,
),
BoxShadow(
offset: Offset(0.0, 6.0),
blurRadius: 10.0,
color: _kKeyPenumbraOpacity,
),
BoxShadow(
offset: Offset(0.0, 1.0),
blurRadius: 18.0,
color: _kAmbientShadowOpacity,
),
],
),
child: icons[currentSegment!],
);
},
),
),
),
),
],
),
),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_segmented_control_demo.dart/0 | {'file_path': 'flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_segmented_control_demo.dart', 'repo_id': 'flutter', 'token_count': 2705} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_gallery/demo/material/buttons_demo.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Button locations are OK', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/pull/85351
{
await tester.pumpWidget(const MaterialApp(home: ButtonsDemo()));
expect(find.byType(ElevatedButton).evaluate().length, 2);
final Offset topLeft1 = tester.getTopLeft(find.byType(ElevatedButton).first);
final Offset topLeft2 = tester.getTopLeft(find.byType(ElevatedButton).last);
expect(topLeft1.dx, 203);
expect(topLeft2.dx, 453);
expect(topLeft1.dy, topLeft2.dy);
}
{
await tester.tap(find.text('TEXT'));
await tester.pumpAndSettle();
expect(find.byType(TextButton).evaluate().length, 2);
final Offset topLeft1 = tester.getTopLeft(find.byType(TextButton).first);
final Offset topLeft2 = tester.getTopLeft(find.byType(TextButton).last);
expect(topLeft1.dx, 247);
expect(topLeft2.dx, 425);
expect(topLeft1.dy, topLeft2.dy);
}
{
await tester.tap(find.text('OUTLINED'));
await tester.pumpAndSettle();
expect(find.byType(OutlinedButton).evaluate().length, 2);
final Offset topLeft1 = tester.getTopLeft(find.byType(OutlinedButton).first);
final Offset topLeft2 = tester.getTopLeft(find.byType(OutlinedButton).last);
expect(topLeft1.dx, 203);
expect(topLeft2.dx, 453);
expect(topLeft1.dy, topLeft2.dy);
}
});
}
| flutter/dev/integration_tests/flutter_gallery/test/demo/material/buttons_demo_test.dart/0 | {'file_path': 'flutter/dev/integration_tests/flutter_gallery/test/demo/material/buttons_demo_test.dart', 'repo_id': 'flutter', 'token_count': 695} |
// Copyright 2014 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_driver/flutter_driver.dart';
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
void main() {
group('page transition performance test', () {
late FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
await driver.waitUntilFirstFrameRasterized();
});
tearDownAll(() async {
driver.close();
});
test('measure', () async {
final Timeline timeline = await driver.traceAction(() async {
await driver.tap(find.text('Material'));
for (int i = 0; i < 10; i++) {
await driver.tap(find.text('Banner'));
await Future<void>.delayed(const Duration(milliseconds: 500));
await driver.waitFor(find.byTooltip('Back'));
await driver.tap(find.byTooltip('Back'));
await Future<void>.delayed(const Duration(milliseconds: 500));
}
});
final TimelineSummary summary = TimelineSummary.summarize(timeline);
await summary.writeTimelineToFile('page_transition_perf', pretty: true);
}, timeout: Timeout.none);
});
}
| flutter/dev/integration_tests/flutter_gallery/test_driver/page_transitions_perf_test.dart/0 | {'file_path': 'flutter/dev/integration_tests/flutter_gallery/test_driver/page_transitions_perf_test.dart', 'repo_id': 'flutter', 'token_count': 464} |
// Copyright 2014 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/material.dart';
enum TestStatus { ok, pending, failed, complete }
typedef TestStep = Future<TestStepResult> Function();
const String nothing = '-';
class TestStepResult {
const TestStepResult(this.name, this.description, this.status);
factory TestStepResult.fromSnapshot(AsyncSnapshot<TestStepResult> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return const TestStepResult('Not started', nothing, TestStatus.ok);
case ConnectionState.waiting:
return const TestStepResult('Executing', nothing, TestStatus.pending);
case ConnectionState.done:
if (snapshot.hasData) {
return snapshot.data!;
} else {
final Object? result = snapshot.error;
return result! as TestStepResult;
}
case ConnectionState.active:
throw 'Unsupported state ${snapshot.connectionState}';
}
}
final String name;
final String description;
final TestStatus status;
static const TextStyle bold = TextStyle(fontWeight: FontWeight.bold);
static const TestStepResult complete = TestStepResult(
'Test complete',
nothing,
TestStatus.complete,
);
Widget asWidget(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Step: $name', style: bold),
Text(description),
const Text(' '),
Text(
status.toString().substring('TestStatus.'.length),
key: ValueKey<String>(
status == TestStatus.pending ? 'nostatus' : 'status'),
style: bold,
),
],
);
}
}
| flutter/dev/integration_tests/platform_interaction/lib/src/test_step.dart/0 | {'file_path': 'flutter/dev/integration_tests/platform_interaction/lib/src/test_step.dart', 'repo_id': 'flutter', 'token_count': 675} |
// Copyright 2014 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.
const String kDefaultTextField = 'default_textfield';
const String kHeightText = 'height_text';
const String kUnfocusButton = 'unfocus_button';
const String kOffsetText = 'offset_text';
const String kListView = 'list_view';
const String kKeyboardVisibleView = 'keyboard_visible';
| flutter/dev/integration_tests/ui/lib/keys.dart/0 | {'file_path': 'flutter/dev/integration_tests/ui/lib/keys.dart', 'repo_id': 'flutter', 'token_count': 122} |
// Copyright 2014 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_driver/flutter_driver.dart';
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
void main() {
group('FlutterDriver', () {
final SerializableFinder presentText = find.text('present');
late FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
});
tearDownAll(() async {
await driver.close();
});
test('waitFor should find text "present"', () async {
await driver.waitFor(presentText);
}, timeout: Timeout.none);
test('waitForAbsent should time out waiting for text "present" to disappear', () async {
await expectLater(
() => driver.waitForAbsent(presentText, timeout: const Duration(seconds: 1)),
throwsA(isA<DriverError>().having(
(DriverError error) => error.message,
'message',
contains('Timeout while executing waitForAbsent'),
)),
);
}, timeout: Timeout.none);
test('waitForAbsent should resolve when text "present" disappears', () async {
// Begin waiting for it to disappear
final Completer<void> whenWaitForAbsentResolves = Completer<void>();
driver.waitForAbsent(presentText).then(
whenWaitForAbsentResolves.complete,
onError: whenWaitForAbsentResolves.completeError,
);
// Wait 1 second then make it disappear
await Future<void>.delayed(const Duration(seconds: 1));
await driver.tap(find.byValueKey('togglePresent'));
// Ensure waitForAbsent resolves
await whenWaitForAbsentResolves.future;
}, timeout: Timeout.none);
test('waitFor times out waiting for "present" to reappear', () async {
await expectLater(
() => driver.waitFor(presentText, timeout: const Duration(seconds: 1)),
throwsA(isA<DriverError>().having(
(DriverError error) => error.message,
'message',
contains('Timeout while executing waitFor'),
)),
);
}, timeout: Timeout.none);
test('waitFor should resolve when text "present" reappears', () async {
// Begin waiting for it to reappear
final Completer<void> whenWaitForResolves = Completer<void>();
driver.waitFor(presentText).then(
whenWaitForResolves.complete,
onError: whenWaitForResolves.completeError,
);
// Wait 1 second then make it appear
await Future<void>.delayed(const Duration(seconds: 1));
await driver.tap(find.byValueKey('togglePresent'));
// Ensure waitFor resolves
await whenWaitForResolves.future;
}, timeout: Timeout.none);
test('waitForAbsent resolves immediately when the element does not exist', () async {
await driver.waitForAbsent(find.text('that does not exist'));
}, timeout: Timeout.none);
test('uses hit test to determine tappable elements', () async {
final SerializableFinder a = find.byValueKey('a');
final SerializableFinder menu = find.byType('_DropdownMenu<Letter>');
// Dropdown is closed
await driver.waitForAbsent(menu);
// Open dropdown
await driver.tap(a);
await driver.waitFor(menu);
// Close it again
await driver.tap(a);
await driver.waitForAbsent(menu);
}, timeout: Timeout.none);
test('enters text in a text field', () async {
final SerializableFinder textField = find.byValueKey('enter-text-field');
await driver.tap(textField);
await driver.enterText('Hello!');
await driver.waitFor(find.text('Hello!'));
await driver.enterText('World!');
await driver.waitFor(find.text('World!'));
}, timeout: Timeout.none);
});
}
| flutter/dev/integration_tests/ui/test_driver/driver_test.dart/0 | {'file_path': 'flutter/dev/integration_tests/ui/test_driver/driver_test.dart', 'repo_id': 'flutter', 'token_count': 1387} |
// Copyright 2014 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 'template.dart';
class ColorSchemeTemplate extends TokenTemplate {
ColorSchemeTemplate(super.blockName, super.fileName, super.tokens);
// Map of light color scheme token data from tokens.
late Map<String, dynamic> colorTokensLight = tokens['colorsLight'] as Map<String, dynamic>;
// Map of dark color scheme token data from tokens.
late Map<String, dynamic> colorTokensDark = tokens['colorsDark'] as Map<String, dynamic>;
@override
String generate() => '''
const ColorScheme _colorSchemeLightM3 = ColorScheme(
brightness: Brightness.light,
primary: Color(${tokens[colorTokensLight['md.sys.color.primary']]}),
onPrimary: Color(${tokens[colorTokensLight['md.sys.color.on-primary']]}),
primaryContainer: Color(${tokens[colorTokensLight['md.sys.color.primary-container']]}),
onPrimaryContainer: Color(${tokens[colorTokensLight['md.sys.color.on-primary-container']]}),
secondary: Color(${tokens[colorTokensLight['md.sys.color.secondary']]}),
onSecondary: Color(${tokens[colorTokensLight['md.sys.color.on-secondary']]}),
secondaryContainer: Color(${tokens[colorTokensLight['md.sys.color.secondary-container']]}),
onSecondaryContainer: Color(${tokens[colorTokensLight['md.sys.color.on-secondary-container']]}),
tertiary: Color(${tokens[colorTokensLight['md.sys.color.tertiary']]}),
onTertiary: Color(${tokens[colorTokensLight['md.sys.color.on-tertiary']]}),
tertiaryContainer: Color(${tokens[colorTokensLight['md.sys.color.tertiary-container']]}),
onTertiaryContainer: Color(${tokens[colorTokensLight['md.sys.color.on-tertiary-container']]}),
error: Color(${tokens[colorTokensLight['md.sys.color.error']]}),
onError: Color(${tokens[colorTokensLight['md.sys.color.on-error']]}),
errorContainer: Color(${tokens[colorTokensLight['md.sys.color.error-container']]}),
onErrorContainer: Color(${tokens[colorTokensLight['md.sys.color.on-error-container']]}),
background: Color(${tokens[colorTokensLight['md.sys.color.background']]}),
onBackground: Color(${tokens[colorTokensLight['md.sys.color.on-background']]}),
surface: Color(${tokens[colorTokensLight['md.sys.color.surface']]}),
onSurface: Color(${tokens[colorTokensLight['md.sys.color.on-surface']]}),
surfaceVariant: Color(${tokens[colorTokensLight['md.sys.color.surface-variant']]}),
onSurfaceVariant: Color(${tokens[colorTokensLight['md.sys.color.on-surface-variant']]}),
outline: Color(${tokens[colorTokensLight['md.sys.color.outline']]}),
outlineVariant: Color(${tokens[colorTokensLight['md.sys.color.outline-variant']]}),
shadow: Color(${tokens[colorTokensLight['md.sys.color.shadow']]}),
scrim: Color(${tokens[colorTokensLight['md.sys.color.scrim']]}),
inverseSurface: Color(${tokens[colorTokensLight['md.sys.color.inverse-surface']]}),
onInverseSurface: Color(${tokens[colorTokensLight['md.sys.color.inverse-on-surface']]}),
inversePrimary: Color(${tokens[colorTokensLight['md.sys.color.inverse-primary']]}),
// The surfaceTint color is set to the same color as the primary.
surfaceTint: Color(${tokens[colorTokensLight['md.sys.color.primary']]}),
);
const ColorScheme _colorSchemeDarkM3 = ColorScheme(
brightness: Brightness.dark,
primary: Color(${tokens[colorTokensDark['md.sys.color.primary']]}),
onPrimary: Color(${tokens[colorTokensDark['md.sys.color.on-primary']]}),
primaryContainer: Color(${tokens[colorTokensDark['md.sys.color.primary-container']]}),
onPrimaryContainer: Color(${tokens[colorTokensDark['md.sys.color.on-primary-container']]}),
secondary: Color(${tokens[colorTokensDark['md.sys.color.secondary']]}),
onSecondary: Color(${tokens[colorTokensDark['md.sys.color.on-secondary']]}),
secondaryContainer: Color(${tokens[colorTokensDark['md.sys.color.secondary-container']]}),
onSecondaryContainer: Color(${tokens[colorTokensDark['md.sys.color.on-secondary-container']]}),
tertiary: Color(${tokens[colorTokensDark['md.sys.color.tertiary']]}),
onTertiary: Color(${tokens[colorTokensDark['md.sys.color.on-tertiary']]}),
tertiaryContainer: Color(${tokens[colorTokensDark['md.sys.color.tertiary-container']]}),
onTertiaryContainer: Color(${tokens[colorTokensDark['md.sys.color.on-tertiary-container']]}),
error: Color(${tokens[colorTokensDark['md.sys.color.error']]}),
onError: Color(${tokens[colorTokensDark['md.sys.color.on-error']]}),
errorContainer: Color(${tokens[colorTokensDark['md.sys.color.error-container']]}),
onErrorContainer: Color(${tokens[colorTokensDark['md.sys.color.on-error-container']]}),
background: Color(${tokens[colorTokensDark['md.sys.color.background']]}),
onBackground: Color(${tokens[colorTokensDark['md.sys.color.on-background']]}),
surface: Color(${tokens[colorTokensDark['md.sys.color.surface']]}),
onSurface: Color(${tokens[colorTokensDark['md.sys.color.on-surface']]}),
surfaceVariant: Color(${tokens[colorTokensDark['md.sys.color.surface-variant']]}),
onSurfaceVariant: Color(${tokens[colorTokensDark['md.sys.color.on-surface-variant']]}),
outline: Color(${tokens[colorTokensDark['md.sys.color.outline']]}),
outlineVariant: Color(${tokens[colorTokensDark['md.sys.color.outline-variant']]}),
shadow: Color(${tokens[colorTokensDark['md.sys.color.shadow']]}),
scrim: Color(${tokens[colorTokensDark['md.sys.color.scrim']]}),
inverseSurface: Color(${tokens[colorTokensDark['md.sys.color.inverse-surface']]}),
onInverseSurface: Color(${tokens[colorTokensDark['md.sys.color.inverse-on-surface']]}),
inversePrimary: Color(${tokens[colorTokensDark['md.sys.color.inverse-primary']]}),
// The surfaceTint color is set to the same color as the primary.
surfaceTint: Color(${tokens[colorTokensDark['md.sys.color.primary']]}),
);
''';
}
| flutter/dev/tools/gen_defaults/lib/color_scheme_template.dart/0 | {'file_path': 'flutter/dev/tools/gen_defaults/lib/color_scheme_template.dart', 'repo_id': 'flutter', 'token_count': 2061} |
// Copyright 2014 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 'template.dart';
class ProgressIndicatorTemplate extends TokenTemplate {
const ProgressIndicatorTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
});
@override
String generate() => '''
class _Circular${blockName}DefaultsM3 extends ProgressIndicatorThemeData {
_Circular${blockName}DefaultsM3(this.context);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
Color get color => ${componentColor('md.comp.circular-progress-indicator.active-indicator')};
}
class _Linear${blockName}DefaultsM3 extends ProgressIndicatorThemeData {
_Linear${blockName}DefaultsM3(this.context);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
Color get color => ${componentColor('md.comp.linear-progress-indicator.active-indicator')};
@override
Color get linearTrackColor => ${componentColor('md.comp.linear-progress-indicator.track')};
@override
double get linearMinHeight => ${tokens['md.comp.linear-progress-indicator.track.height']};
}
''';
}
| flutter/dev/tools/gen_defaults/lib/progress_indicator_template.dart/0 | {'file_path': 'flutter/dev/tools/gen_defaults/lib/progress_indicator_template.dart', 'repo_id': 'flutter', 'token_count': 392} |
// Copyright 2014 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:developer' as developer;
import 'package:flutter_test/flutter_test.dart';
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
// This test ensures that the engine starts the VM with the timeline streams
// for "Dart", "Embedder", and "GC" recorded from startup.
void main() {
late VmService vmService;
setUpAll(() async {
final developer.ServiceProtocolInfo info = await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test _must_ be run with --enable-vmservice.');
}
vmService = await vmServiceConnectUri(
'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws',
);
});
tearDownAll(() async {
await vmService.dispose();
});
test('Image cache tracing', () async {
final TimelineFlags flags = await vmService.getVMTimelineFlags();
expect(flags.recordedStreams, containsAll(<String>[
'Dart',
'Embedder',
'GC',
]));
}, skip: isBrowser); // [intended] uses dart:isolate and io.
}
| flutter/dev/tracing_tests/test/default_streams_test.dart/0 | {'file_path': 'flutter/dev/tracing_tests/test/default_streams_test.dart', 'repo_id': 'flutter', 'token_count': 417} |
// Copyright 2014 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.
// Flutter code sample for [CupertinoTextField].
import 'package:flutter/cupertino.dart';
void main() => runApp(const CupertinoTextFieldApp());
class CupertinoTextFieldApp extends StatelessWidget {
const CupertinoTextFieldApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: CupertinoTextFieldExample(),
);
}
}
class CupertinoTextFieldExample extends StatefulWidget {
const CupertinoTextFieldExample({super.key});
@override
State<CupertinoTextFieldExample> createState() => _CupertinoTextFieldExampleState();
}
class _CupertinoTextFieldExampleState extends State<CupertinoTextFieldExample> {
late TextEditingController _textController;
@override
void initState() {
super.initState();
_textController = TextEditingController(text: 'initial text');
}
@override
void dispose() {
_textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('CupertinoTextField Sample'),
),
child: Center(
child: CupertinoTextField(
controller: _textController,
)
),
);
}
}
| flutter/examples/api/lib/cupertino/text_field/cupertino_text_field.0.dart/0 | {'file_path': 'flutter/examples/api/lib/cupertino/text_field/cupertino_text_field.0.dart', 'repo_id': 'flutter', 'token_count': 500} |
// Copyright 2014 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.
// Flutter code sample for [MaterialBanner].
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget(),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('The MaterialBanner is below'),
),
body: const MaterialBanner(
padding: EdgeInsets.all(20),
content: Text('Hello, I am a Material Banner'),
leading: Icon(Icons.agriculture_outlined),
backgroundColor: Color(0xFFE0E0E0),
actions: <Widget>[
TextButton(
onPressed: null,
child: Text('OPEN'),
),
TextButton(
onPressed: null,
child: Text('DISMISS'),
),
],
),
);
}
}
| flutter/examples/api/lib/material/banner/material_banner.0.dart/0 | {'file_path': 'flutter/examples/api/lib/material/banner/material_banner.0.dart', 'repo_id': 'flutter', 'token_count': 520} |
// Copyright 2014 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.
// Flutter code sample for [Dialog].
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Dialog Sample')),
body: const Center(
child: DialogExample(),
),
),
);
}
}
class DialogExample extends StatelessWidget {
const DialogExample({super.key});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: () => showDialog<String>(
context: context,
builder: (BuildContext context) => Dialog(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('This is a typical dialog.'),
const SizedBox(height: 15),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Close'),
),
],
),
),
),
),
child: const Text('Show Dialog'),
),
const SizedBox(height: 10),
TextButton(
onPressed: () => showDialog<String>(
context: context,
builder: (BuildContext context) => Dialog.fullscreen(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('This is a fullscreen dialog.'),
const SizedBox(height: 15),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Close'),
),
],
),
),
),
child: const Text('Show Fullscreen Dialog'),
),
],
);
}
}
| flutter/examples/api/lib/material/dialog/dialog.0.dart/0 | {'file_path': 'flutter/examples/api/lib/material/dialog/dialog.0.dart', 'repo_id': 'flutter', 'token_count': 1320} |
// Copyright 2014 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.
// Flutter code sample for [FilledButton].
import 'package:flutter/material.dart';
void main() {
runApp(const FilledButtonApp());
}
class FilledButtonApp extends StatelessWidget {
const FilledButtonApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(colorSchemeSeed: const Color(0xff6750a4), useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('FilledButton Sample')),
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Column(children: <Widget>[
const SizedBox(height: 30),
const Text('Filled'),
const SizedBox(height: 15),
FilledButton(
onPressed: () {},
child: const Text('Enabled'),
),
const SizedBox(height: 30),
const FilledButton(
onPressed: null,
child: Text('Disabled'),
),
]),
const SizedBox(width: 30),
Column(children: <Widget>[
const SizedBox(height: 30),
const Text('Filled tonal'),
const SizedBox(height: 15),
FilledButton.tonal(
onPressed: () {},
child: const Text('Enabled'),
),
const SizedBox(height: 30),
const FilledButton.tonal(
onPressed: null,
child: Text('Disabled'),
),
])
],
),
),
),
);
}
}
| flutter/examples/api/lib/material/filled_button/filled_button.0.dart/0 | {'file_path': 'flutter/examples/api/lib/material/filled_button/filled_button.0.dart', 'repo_id': 'flutter', 'token_count': 968} |
// Copyright 2014 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.
// Flutter code sample for [ListTile].
import 'package:flutter/material.dart';
void main() => runApp(const ListTileApp());
class ListTileApp extends StatelessWidget {
const ListTileApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: LisTileExample(),
);
}
}
class LisTileExample extends StatelessWidget {
const LisTileExample({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('ListTile Sample')),
body: ListView(
children: const <Widget>[
Card(child: ListTile(title: Text('One-line ListTile'))),
Card(
child: ListTile(
leading: FlutterLogo(),
title: Text('One-line with leading widget'),
),
),
Card(
child: ListTile(
title: Text('One-line with trailing widget'),
trailing: Icon(Icons.more_vert),
),
),
Card(
child: ListTile(
leading: FlutterLogo(),
title: Text('One-line with both widgets'),
trailing: Icon(Icons.more_vert),
),
),
Card(
child: ListTile(
title: Text('One-line dense ListTile'),
dense: true,
),
),
Card(
child: ListTile(
leading: FlutterLogo(size: 56.0),
title: Text('Two-line ListTile'),
subtitle: Text('Here is a second line'),
trailing: Icon(Icons.more_vert),
),
),
Card(
child: ListTile(
leading: FlutterLogo(size: 72.0),
title: Text('Three-line ListTile'),
subtitle: Text(
'A sufficiently long subtitle warrants three lines.'
),
trailing: Icon(Icons.more_vert),
isThreeLine: true,
),
),
],
),
);
}
}
| flutter/examples/api/lib/material/list_tile/list_tile.1.dart/0 | {'file_path': 'flutter/examples/api/lib/material/list_tile/list_tile.1.dart', 'repo_id': 'flutter', 'token_count': 1081} |
// Copyright 2014 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.
// Flutter code sample for [NavigationBar].
import 'package:flutter/material.dart';
void main() => runApp(const NavigationBarApp());
class NavigationBarApp extends StatelessWidget {
const NavigationBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: NavigationExample());
}
}
class NavigationExample extends StatefulWidget {
const NavigationExample({super.key});
@override
State<NavigationExample> createState() => _NavigationExampleState();
}
class _NavigationExampleState extends State<NavigationExample> {
int currentPageIndex = 0;
NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow;
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: NavigationBar(
labelBehavior: labelBehavior,
selectedIndex: currentPageIndex,
onDestinationSelected: (int index) {
setState(() {
currentPageIndex = index;
});
},
destinations: const <Widget>[
NavigationDestination(
icon: Icon(Icons.explore),
label: 'Explore',
),
NavigationDestination(
icon: Icon(Icons.commute),
label: 'Commute',
),
NavigationDestination(
selectedIcon: Icon(Icons.bookmark),
icon: Icon(Icons.bookmark_border),
label: 'Saved',
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Label behavior: ${labelBehavior.name}'),
const SizedBox(height: 10),
OverflowBar(
spacing: 10.0,
children: <Widget>[
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior = NavigationDestinationLabelBehavior.alwaysShow;
});
},
child: const Text('alwaysShow'),
),
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior = NavigationDestinationLabelBehavior.onlyShowSelected;
});
},
child: const Text('onlyShowSelected'),
),
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior = NavigationDestinationLabelBehavior.alwaysHide;
});
},
child: const Text('alwaysHide'),
),
],
),
],
),
),
);
}
}
| flutter/examples/api/lib/material/navigation_bar/navigation_bar.1.dart/0 | {'file_path': 'flutter/examples/api/lib/material/navigation_bar/navigation_bar.1.dart', 'repo_id': 'flutter', 'token_count': 1417} |
// Copyright 2014 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.
// Flutter code sample for custom labeled radio.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
void main() => runApp(const LabeledRadioApp());
class LabeledRadioApp extends StatelessWidget {
const LabeledRadioApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('Custom Labeled Radio Sample')),
body: const LabeledRadioExample(),
),
);
}
}
class LinkedLabelRadio extends StatelessWidget {
const LinkedLabelRadio({
super.key,
required this.label,
required this.padding,
required this.groupValue,
required this.value,
required this.onChanged,
});
final String label;
final EdgeInsets padding;
final bool groupValue;
final bool value;
final ValueChanged<bool> onChanged;
@override
Widget build(BuildContext context) {
return Padding(
padding: padding,
child: Row(
children: <Widget>[
Radio<bool>(
groupValue: groupValue,
value: value,
onChanged: (bool? newValue) {
onChanged(newValue!);
},
),
RichText(
text: TextSpan(
text: label,
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () {
debugPrint('Label has been tapped.');
},
),
),
],
),
);
}
}
class LabeledRadioExample extends StatefulWidget {
const LabeledRadioExample({super.key});
@override
State<LabeledRadioExample> createState() => _LabeledRadioExampleState();
}
class _LabeledRadioExampleState extends State<LabeledRadioExample> {
bool _isRadioSelected = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
LinkedLabelRadio(
label: 'First tappable label text',
padding: const EdgeInsets.symmetric(horizontal: 5.0),
value: true,
groupValue: _isRadioSelected,
onChanged: (bool newValue) {
setState(() {
_isRadioSelected = newValue;
});
},
),
LinkedLabelRadio(
label: 'Second tappable label text',
padding: const EdgeInsets.symmetric(horizontal: 5.0),
value: false,
groupValue: _isRadioSelected,
onChanged: (bool newValue) {
setState(() {
_isRadioSelected = newValue;
});
},
),
],
),
);
}
}
| flutter/examples/api/lib/material/radio_list_tile/custom_labeled_radio.0.dart/0 | {'file_path': 'flutter/examples/api/lib/material/radio_list_tile/custom_labeled_radio.0.dart', 'repo_id': 'flutter', 'token_count': 1392} |
// Copyright 2014 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.
// Flutter code sample for [Scaffold.endDrawer].
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
void _openEndDrawer() {
_scaffoldKey.currentState!.openEndDrawer();
}
void _closeEndDrawer() {
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(title: const Text('Drawer Demo')),
body: Center(
child: ElevatedButton(
onPressed: _openEndDrawer,
child: const Text('Open End Drawer'),
),
),
endDrawer: Drawer(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('This is the Drawer'),
ElevatedButton(
onPressed: _closeEndDrawer,
child: const Text('Close Drawer'),
),
],
),
),
),
// Disable opening the end drawer with a swipe gesture.
endDrawerEnableOpenDragGesture: false,
);
}
}
| flutter/examples/api/lib/material/scaffold/scaffold.end_drawer.0.dart/0 | {'file_path': 'flutter/examples/api/lib/material/scaffold/scaffold.end_drawer.0.dart', 'repo_id': 'flutter', 'token_count': 745} |
// Copyright 2014 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.
// Flutter code sample for [SelectionContainer].
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: SelectionArea(
child: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: SelectionAllOrNoneContainer(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Row 1'),
Text('Row 2'),
Text('Row 3'),
],
),
),
),
),
),
);
}
}
class SelectionAllOrNoneContainer extends StatefulWidget {
const SelectionAllOrNoneContainer({
super.key,
required this.child
});
final Widget child;
@override
State<StatefulWidget> createState() => _SelectionAllOrNoneContainerState();
}
class _SelectionAllOrNoneContainerState extends State<SelectionAllOrNoneContainer> {
final SelectAllOrNoneContainerDelegate delegate = SelectAllOrNoneContainerDelegate();
@override
void dispose() {
delegate.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SelectionContainer(
delegate: delegate,
child: widget.child,
);
}
}
class SelectAllOrNoneContainerDelegate extends MultiSelectableSelectionContainerDelegate {
Offset? _adjustedStartEdge;
Offset? _adjustedEndEdge;
bool _isSelected = false;
// This method is called when newly added selectable is in the current
// selected range.
@override
void ensureChildUpdated(Selectable selectable) {
if (_isSelected) {
dispatchSelectionEventToChild(selectable, const SelectAllSelectionEvent());
}
}
@override
SelectionResult handleSelectWord(SelectWordSelectionEvent event) {
// Treat select word as select all.
return handleSelectAll(const SelectAllSelectionEvent());
}
@override
SelectionResult handleSelectionEdgeUpdate(SelectionEdgeUpdateEvent event) {
final Rect containerRect = Rect.fromLTWH(0, 0, containerSize.width, containerSize.height);
final Matrix4 globalToLocal = getTransformTo(null)..invert();
final Offset localOffset = MatrixUtils.transformPoint(globalToLocal, event.globalPosition);
final Offset adjustOffset = SelectionUtils.adjustDragOffset(containerRect, localOffset);
if (event.type == SelectionEventType.startEdgeUpdate) {
_adjustedStartEdge = adjustOffset;
} else {
_adjustedEndEdge = adjustOffset;
}
// Select all content if the selection rect intercepts with the rect.
if (_adjustedStartEdge != null && _adjustedEndEdge != null) {
final Rect selectionRect = Rect.fromPoints(_adjustedStartEdge!, _adjustedEndEdge!);
if (!selectionRect.intersect(containerRect).isEmpty) {
handleSelectAll(const SelectAllSelectionEvent());
} else {
super.handleClearSelection(const ClearSelectionEvent());
}
} else {
super.handleClearSelection(const ClearSelectionEvent());
}
return SelectionUtils.getResultBasedOnRect(containerRect, localOffset);
}
@override
SelectionResult handleClearSelection(ClearSelectionEvent event) {
_adjustedStartEdge = null;
_adjustedEndEdge = null;
_isSelected = false;
return super.handleClearSelection(event);
}
@override
SelectionResult handleSelectAll(SelectAllSelectionEvent event) {
_isSelected = true;
return super.handleSelectAll(event);
}
}
| flutter/examples/api/lib/material/selection_container/selection_container.0.dart/0 | {'file_path': 'flutter/examples/api/lib/material/selection_container/selection_container.0.dart', 'repo_id': 'flutter', 'token_count': 1356} |
// Copyright 2014 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.
// Flutter code sample for [SwitchListTile].
import 'package:flutter/material.dart';
void main() => runApp(const SwitchListTileApp());
class SwitchListTileApp extends StatelessWidget {
const SwitchListTileApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('SwitchListTile Sample')),
body: const Center(
child: SwitchListTileExample(),
),
),
);
}
}
class SwitchListTileExample extends StatefulWidget {
const SwitchListTileExample({super.key});
@override
State<SwitchListTileExample> createState() => _SwitchListTileExampleState();
}
class _SwitchListTileExampleState extends State<SwitchListTileExample> {
bool _lights = false;
@override
Widget build(BuildContext context) {
return SwitchListTile(
title: const Text('Lights'),
value: _lights,
onChanged: (bool value) {
setState(() {
_lights = value;
});
},
secondary: const Icon(Icons.lightbulb_outline),
);
}
}
| flutter/examples/api/lib/material/switch_list_tile/switch_list_tile.0.dart/0 | {'file_path': 'flutter/examples/api/lib/material/switch_list_tile/switch_list_tile.0.dart', 'repo_id': 'flutter', 'token_count': 457} |
// Copyright 2014 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.
// Flutter code sample for [Tooltip].
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Tooltip Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: TooltipSample(title: _title),
);
}
}
class TooltipSample extends StatelessWidget {
const TooltipSample({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
final GlobalKey<TooltipState> tooltipkey = GlobalKey<TooltipState>();
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: Tooltip(
// Provide a global key with the "TooltipState" type to show
// the tooltip manually when trigger mode is set to manual.
key: tooltipkey,
triggerMode: TooltipTriggerMode.manual,
showDuration: const Duration(seconds: 1),
message: 'I am a Tooltip',
child: const Text('Tap on the FAB'),
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
// Show Tooltip programmatically on button tap.
tooltipkey.currentState?.ensureTooltipVisible();
},
label: const Text('Show Tooltip'),
),
);
}
}
| flutter/examples/api/lib/material/tooltip/tooltip.3.dart/0 | {'file_path': 'flutter/examples/api/lib/material/tooltip/tooltip.3.dart', 'repo_id': 'flutter', 'token_count': 575} |
// Copyright 2014 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.
// Flutter code sample for [SliverAnimatedList].
import 'package:flutter/material.dart';
void main() => runApp(const SliverAnimatedListSample());
class SliverAnimatedListSample extends StatefulWidget {
const SliverAnimatedListSample({super.key});
@override
State<SliverAnimatedListSample> createState() =>
_SliverAnimatedListSampleState();
}
class _SliverAnimatedListSampleState extends State<SliverAnimatedListSample> {
final GlobalKey<SliverAnimatedListState> _listKey =
GlobalKey<SliverAnimatedListState>();
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
late ListModel<int> _list;
int? _selectedItem;
late int
_nextItem; // The next item inserted when the user presses the '+' button.
@override
void initState() {
super.initState();
_list = ListModel<int>(
listKey: _listKey,
initialItems: <int>[0, 1, 2],
removedItemBuilder: _buildRemovedItem,
);
_nextItem = 3;
}
// Used to build list items that haven't been removed.
Widget _buildItem(
BuildContext context, int index, Animation<double> animation) {
return CardItem(
animation: animation,
item: _list[index],
selected: _selectedItem == _list[index],
onTap: () {
setState(() {
_selectedItem = _selectedItem == _list[index] ? null : _list[index];
});
},
);
}
/// The builder function used to build items that have been removed.
///
/// Used to build an item after it has been removed from the list. This method
/// is needed because a removed item remains visible until its animation has
/// completed (even though it's gone as far this ListModel is concerned). The
/// widget will be used by the [AnimatedListState.removeItem] method's
/// [AnimatedRemovedItemBuilder] parameter.
Widget _buildRemovedItem(
int item, BuildContext context, Animation<double> animation) {
return CardItem(
animation: animation,
item: item,
);
}
// Insert the "next item" into the list model.
void _insert() {
final int index =
_selectedItem == null ? _list.length : _list.indexOf(_selectedItem!);
_list.insert(index, _nextItem++);
}
// Remove the selected item from the list model.
void _remove() {
if (_selectedItem != null) {
_list.removeAt(_list.indexOf(_selectedItem!));
setState(() {
_selectedItem = null;
});
} else {
_scaffoldMessengerKey.currentState!.showSnackBar(const SnackBar(
content: Text(
'Select an item to remove from the list.',
style: TextStyle(fontSize: 20),
),
));
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
scaffoldMessengerKey: _scaffoldMessengerKey,
home: Scaffold(
key: _scaffoldKey,
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: const Text(
'SliverAnimatedList',
style: TextStyle(fontSize: 30),
),
expandedHeight: 60,
centerTitle: true,
backgroundColor: Colors.amber[900],
leading: IconButton(
icon: const Icon(Icons.add_circle),
onPressed: _insert,
tooltip: 'Insert a new item.',
iconSize: 32,
),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.remove_circle),
onPressed: _remove,
tooltip: 'Remove the selected item.',
iconSize: 32,
),
],
),
SliverAnimatedList(
key: _listKey,
initialItemCount: _list.length,
itemBuilder: _buildItem,
),
],
),
),
);
}
}
typedef RemovedItemBuilder<E> = Widget Function(
E item, BuildContext context, Animation<double> animation);
// Keeps a Dart [List] in sync with an [AnimatedList].
//
// The [insert] and [removeAt] methods apply to both the internal list and
// the animated list that belongs to [listKey].
//
// This class only exposes as much of the Dart List API as is needed by the
// sample app. More list methods are easily added, however methods that
// mutate the list must make the same changes to the animated list in terms
// of [AnimatedListState.insertItem] and [AnimatedList.removeItem].
class ListModel<E> {
ListModel({
required this.listKey,
required this.removedItemBuilder,
Iterable<E>? initialItems,
}) : _items = List<E>.from(initialItems ?? <E>[]);
final GlobalKey<SliverAnimatedListState> listKey;
final RemovedItemBuilder<E> removedItemBuilder;
final List<E> _items;
SliverAnimatedListState get _animatedList => listKey.currentState!;
void insert(int index, E item) {
_items.insert(index, item);
_animatedList.insertItem(index);
}
E removeAt(int index) {
final E removedItem = _items.removeAt(index);
if (removedItem != null) {
_animatedList.removeItem(
index,
(BuildContext context, Animation<double> animation) =>
removedItemBuilder(removedItem, context, animation),
);
}
return removedItem;
}
int get length => _items.length;
E operator [](int index) => _items[index];
int indexOf(E item) => _items.indexOf(item);
}
// Displays its integer item as 'Item N' on a Card whose color is based on
// the item's value.
//
// The card turns gray when [selected] is true. This widget's height
// is based on the [animation] parameter. It varies as the animation value
// transitions from 0.0 to 1.0.
class CardItem extends StatelessWidget {
const CardItem({
super.key,
this.onTap,
this.selected = false,
required this.animation,
required this.item,
}) : assert(item >= 0);
final Animation<double> animation;
final VoidCallback? onTap;
final int item;
final bool selected;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(
left: 2.0,
right: 2.0,
top: 2.0,
),
child: SizeTransition(
sizeFactor: animation,
child: GestureDetector(
onTap: onTap,
child: SizedBox(
height: 80.0,
child: Card(
color: selected
? Colors.black12
: Colors.primaries[item % Colors.primaries.length],
child: Center(
child: Text(
'Item $item',
style: Theme.of(context).textTheme.headlineMedium,
),
),
),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/animated_list/sliver_animated_list.0.dart/0 | {'file_path': 'flutter/examples/api/lib/widgets/animated_list/sliver_animated_list.0.dart', 'repo_id': 'flutter', 'token_count': 2867} |
// Copyright 2014 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.
// Flutter code sample for [ClipRRect].
import 'package:flutter/material.dart';
void main() => runApp(const ClipRRectApp());
class ClipRRectApp extends StatelessWidget {
const ClipRRectApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ClipRRect Sample')),
body: const ClipRRectExample(),
),
);
}
}
class ClipRRectExample extends StatelessWidget {
const ClipRRectExample({super.key});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(40.0),
constraints: const BoxConstraints.expand(),
// Add a FittedBox to make ClipRRect sized accordingly to the image it contains
child: FittedBox(
child: ClipRRect(
borderRadius: BorderRadius.circular(40.0),
child: const _FakedImage(),
),
),
);
}
}
// A widget exposing the FlutterLogo as a 400x400 image.
//
// It can be replaced by a NetworkImage if internet connection is available, e.g. :
// const Image(
// image: NetworkImage(
// 'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
// );
class _FakedImage extends StatelessWidget {
const _FakedImage();
@override
Widget build(BuildContext context) {
return Container(
// Set constraints as if it were a 400x400 image
constraints: BoxConstraints.tight(const Size(400, 400)),
color: Colors.blueGrey,
child: const FlutterLogo(),
);
}
}
| flutter/examples/api/lib/widgets/basic/clip_rrect.1.dart/0 | {'file_path': 'flutter/examples/api/lib/widgets/basic/clip_rrect.1.dart', 'repo_id': 'flutter', 'token_count': 617} |
// Copyright 2014 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.
// Flutter code sample for [ColorFiltered].
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
ColorFiltered(
colorFilter: const ColorFilter.mode(
Colors.red,
BlendMode.modulate,
),
child: Image.network(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg',
),
),
ColorFiltered(
colorFilter: const ColorFilter.mode(
Colors.grey,
BlendMode.saturation,
),
child: Image.network(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg',
),
),
],
),
);
}
}
| flutter/examples/api/lib/widgets/color_filter/color_filtered.0.dart/0 | {'file_path': 'flutter/examples/api/lib/widgets/color_filter/color_filtered.0.dart', 'repo_id': 'flutter', 'token_count': 655} |
// Copyright 2014 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.
// Flutter code sample for [ErrorWidget].
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
// Set the ErrorWidget's builder before the app is started.
ErrorWidget.builder = (FlutterErrorDetails details) {
// If we're in debug mode, use the normal error widget which shows the error
// message:
if (kDebugMode) {
return ErrorWidget(details.exception);
}
// In release builds, show a yellow-on-blue message instead:
return Container(
alignment: Alignment.center,
child: Text(
'Error!\n${details.exception}',
style: const TextStyle(color: Colors.yellow),
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
),
);
};
// Start the app.
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
static const String _title = 'ErrorWidget Sample';
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool throwError = false;
@override
Widget build(BuildContext context) {
if (throwError) {
// Since the error widget is only used during a build, in this contrived example,
// we purposely throw an exception in a build function.
return Builder(
builder: (BuildContext context) {
throw Exception('oh no, an error');
},
);
} else {
return MaterialApp(
title: MyApp._title,
home: Scaffold(
appBar: AppBar(title: const Text(MyApp._title)),
body: Center(
child: TextButton(
onPressed: () {
setState(() { throwError = true; });
},
child: const Text('Error Prone')),
),
),
);
}
}
}
| flutter/examples/api/lib/widgets/framework/error_widget.0.dart/0 | {'file_path': 'flutter/examples/api/lib/widgets/framework/error_widget.0.dart', 'repo_id': 'flutter', 'token_count': 773} |
// Copyright 2014 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.
// Flutter code sample for [RestorableValue].
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return WidgetsApp(
title: 'Flutter Code Sample',
color: const Color(0xffffffff),
builder: (BuildContext context, Widget? child) {
return const Center(
child: MyStatefulWidget(restorationId: 'main'),
);
},
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key, this.restorationId});
final String? restorationId;
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// RestorationProperty objects can be used because of RestorationMixin.
class _MyStatefulWidgetState extends State<MyStatefulWidget>
with RestorationMixin {
// In this example, the restoration ID for the mixin is passed in through
// the [StatefulWidget]'s constructor.
@override
String? get restorationId => widget.restorationId;
// The current value of the answer is stored in a [RestorableProperty].
// During state restoration it is automatically restored to its old value.
// If no restoration data is available to restore the answer from, it is
// initialized to the specified default value, in this case 42.
final RestorableInt _answer = RestorableInt(42);
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
// All restorable properties must be registered with the mixin. After
// registration, the answer either has its old value restored or is
// initialized to its default value.
registerForRestoration(_answer, 'answer');
}
void _incrementAnswer() {
setState(() {
// The current value of the property can be accessed and modified via
// the value getter and setter.
_answer.value += 1;
});
}
@override
void dispose() {
// Properties must be disposed when no longer used.
_answer.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return OutlinedButton(
onPressed: _incrementAnswer,
child: Text('${_answer.value}'),
);
}
}
| flutter/examples/api/lib/widgets/restoration_properties/restorable_value.0.dart/0 | {'file_path': 'flutter/examples/api/lib/widgets/restoration_properties/restorable_value.0.dart', 'repo_id': 'flutter', 'token_count': 747} |
// Copyright 2014 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.
// Flutter code sample for [Shortcuts].
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class Model with ChangeNotifier {
int count = 0;
void incrementBy(int amount) {
count += amount;
notifyListeners();
}
void decrementBy(int amount) {
count -= amount;
notifyListeners();
}
}
class IncrementIntent extends Intent {
const IncrementIntent(this.amount);
final int amount;
}
class DecrementIntent extends Intent {
const DecrementIntent(this.amount);
final int amount;
}
class IncrementAction extends Action<IncrementIntent> {
IncrementAction(this.model);
final Model model;
@override
void invoke(covariant IncrementIntent intent) {
model.incrementBy(intent.amount);
}
}
class DecrementAction extends Action<DecrementIntent> {
DecrementAction(this.model);
final Model model;
@override
void invoke(covariant DecrementIntent intent) {
model.decrementBy(intent.amount);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Model model = Model();
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: <ShortcutActivator, Intent>{
LogicalKeySet(LogicalKeyboardKey.arrowUp): const IncrementIntent(2),
LogicalKeySet(LogicalKeyboardKey.arrowDown): const DecrementIntent(2),
},
child: Actions(
actions: <Type, Action<Intent>>{
IncrementIntent: IncrementAction(model),
DecrementIntent: DecrementAction(model),
},
child: Focus(
autofocus: true,
child: Column(
children: <Widget>[
const Text('Add to the counter by pressing the up arrow key'),
const Text(
'Subtract from the counter by pressing the down arrow key'),
AnimatedBuilder(
animation: model,
builder: (BuildContext context, Widget? child) {
return Text('count: ${model.count}');
},
),
],
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/shortcuts/shortcuts.1.dart/0 | {'file_path': 'flutter/examples/api/lib/widgets/shortcuts/shortcuts.1.dart', 'repo_id': 'flutter', 'token_count': 1108} |
// Copyright 2014 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.
// Flutter code sample for [DecoratedBoxTransition].
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// [AnimationController]s can be created with `vsync: this` because of
/// [TickerProviderStateMixin].
class _MyStatefulWidgetState extends State<MyStatefulWidget>
with TickerProviderStateMixin {
final DecorationTween decorationTween = DecorationTween(
begin: BoxDecoration(
color: const Color(0xFFFFFFFF),
border: Border.all(style: BorderStyle.none),
borderRadius: BorderRadius.circular(60.0),
boxShadow: const <BoxShadow>[
BoxShadow(
color: Color(0x66666666),
blurRadius: 10.0,
spreadRadius: 3.0,
offset: Offset(0, 6.0),
),
],
),
end: BoxDecoration(
color: const Color(0xFFFFFFFF),
border: Border.all(
style: BorderStyle.none,
),
borderRadius: BorderRadius.zero,
// No shadow.
),
);
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
)..repeat(reverse: true);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ColoredBox(
color: Colors.white,
child: Center(
child: DecoratedBoxTransition(
decoration: decorationTween.animate(_controller),
child: Container(
width: 200,
height: 200,
padding: const EdgeInsets.all(10),
child: const FlutterLogo(),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/transitions/decorated_box_transition.0.dart/0 | {'file_path': 'flutter/examples/api/lib/widgets/transitions/decorated_box_transition.0.dart', 'repo_id': 'flutter', 'token_count': 870} |
// Copyright 2014 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_api_samples/cupertino/text_field/cupertino_text_field.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('CupertinoTextField has initial text', (WidgetTester tester) async {
await tester.pumpWidget(
const example.CupertinoTextFieldApp(),
);
expect(find.byType(CupertinoTextField), findsOneWidget);
expect(find.text('initial text'), findsOneWidget);
await tester.enterText(find.byType(CupertinoTextField), 'new text');
await tester.pump();
expect(find.text('new text'), findsOneWidget);
});
}
| flutter/examples/api/test/cupertino/text_field/cupertino_text_field.0.dart/0 | {'file_path': 'flutter/examples/api/test/cupertino/text_field/cupertino_text_field.0.dart', 'repo_id': 'flutter', 'token_count': 273} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/card/card.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Card has clip applied', (WidgetTester tester) async {
await tester.pumpWidget(const example.MyApp());
final Card card = tester.firstWidget(find.byType(Card));
expect(card.clipBehavior, Clip.hardEdge);
});
}
| flutter/examples/api/test/material/card/card.1_test.dart/0 | {'file_path': 'flutter/examples/api/test/material/card/card.1_test.dart', 'repo_id': 'flutter', 'token_count': 188} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_api_samples/material/menu_anchor/menu_bar.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can open menu', (WidgetTester tester) async {
await tester.pumpWidget(
const example.MenuBarApp(),
);
final Finder menuBarFinder = find.byType(MenuBar);
final MenuBar menuBar = tester.widget<MenuBar>(menuBarFinder);
expect(menuBar.children, isNotEmpty);
expect(menuBar.children.length, equals(1));
final Finder menuButtonFinder = find.byType(SubmenuButton).first;
await tester.tap(menuButtonFinder);
await tester.pump();
expect(find.text('About'), findsOneWidget);
expect(find.text('Show Message'), findsOneWidget);
expect(find.text('Reset Message'), findsOneWidget);
expect(find.text('Background Color'), findsOneWidget);
expect(find.text('Red Background'), findsNothing);
expect(find.text('Green Background'), findsNothing);
expect(find.text('Blue Background'), findsNothing);
expect(find.text(example.MenuBarApp.kMessage), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(find.text('About'), findsOneWidget);
expect(find.text('Show Message'), findsOneWidget);
expect(find.text('Reset Message'), findsOneWidget);
expect(find.text('Background Color'), findsOneWidget);
expect(find.text('Red Background'), findsOneWidget);
expect(find.text('Green Background'), findsOneWidget);
expect(find.text('Blue Background'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(find.text(example.MenuBarApp.kMessage), findsOneWidget);
expect(find.text('Last Selected: Show Message'), findsOneWidget);
});
testWidgets('Shortcuts work', (WidgetTester tester) async {
await tester.pumpWidget(
const example.MenuBarApp(),
);
expect(find.text(example.MenuBarApp.kMessage), findsNothing);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyS);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text(example.MenuBarApp.kMessage), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.text(example.MenuBarApp.kMessage), findsNothing);
expect(find.text('Last Selected: Reset Message'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyR);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: Red Background'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: Green Background'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyB);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: Blue Background'), findsOneWidget);
});
}
| flutter/examples/api/test/material/menu_anchor/menu_bar.0_test.dart/0 | {'file_path': 'flutter/examples/api/test/material/menu_anchor/menu_bar.0_test.dart', 'repo_id': 'flutter', 'token_count': 1262} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/radio_list_tile/radio_list_tile.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Radio aligns appropriately', (WidgetTester tester) async {
await tester.pumpWidget(
const example.RadioListTileApp(),
);
expect(find.byType(RadioListTile<example.Groceries>), findsNWidgets(3));
Offset tileTopLeft = tester.getTopLeft(find.byType(RadioListTile<example.Groceries>).at(0));
Offset radioTopLeft = tester.getTopLeft(find.byType(Radio<example.Groceries>).at(0));
// The radio is centered vertically with the text.
expect(radioTopLeft - tileTopLeft, const Offset(16.0, 16.0));
tileTopLeft = tester.getTopLeft(find.byType(RadioListTile<example.Groceries>).at(1));
radioTopLeft = tester.getTopLeft(find.byType(Radio<example.Groceries>).at(1));
// The radio is centered vertically with the text.
expect(radioTopLeft - tileTopLeft, const Offset(16.0, 30.0));
tileTopLeft = tester.getTopLeft(find.byType(RadioListTile<example.Groceries>).at(2));
radioTopLeft = tester.getTopLeft(find.byType(Radio<example.Groceries>).at(2));
// The radio is aligned to the top vertically with the text.
expect(radioTopLeft - tileTopLeft, const Offset(16.0, 8.0));
});
testWidgets('Radios can be checked', (WidgetTester tester) async {
await tester.pumpWidget(
const example.RadioListTileApp(),
);
expect(find.byType(RadioListTile<example.Groceries>), findsNWidgets(3));
final Finder radioListTile = find.byType(RadioListTile<example.Groceries>);
// Initially the first radio is checked.
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(0)).groupValue,
example.Groceries.pickles,
);
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(1)).groupValue,
example.Groceries.pickles,
);
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(2)).groupValue,
example.Groceries.pickles,
);
// Tap the second radio.
await tester.tap(find.byType(Radio<example.Groceries>).at(1));
await tester.pumpAndSettle();
// The second radio is checked.
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(0)).groupValue,
example.Groceries.tomato,
);
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(1)).groupValue,
example.Groceries.tomato,
);
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(2)).groupValue,
example.Groceries.tomato,
);
// Tap the third radio.
await tester.tap(find.byType(Radio<example.Groceries>).at(2));
await tester.pumpAndSettle();
// The third radio is checked.
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(0)).groupValue,
example.Groceries.lettuce,
);
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(1)).groupValue,
example.Groceries.lettuce,
);
expect(
tester.widget<RadioListTile<example.Groceries>>(radioListTile.at(2)).groupValue,
example.Groceries.lettuce,
);
});
}
| flutter/examples/api/test/material/radio_list_tile/radio_list_tile.1_test.dart/0 | {'file_path': 'flutter/examples/api/test/material/radio_list_tile/radio_list_tile.1_test.dart', 'repo_id': 'flutter', 'token_count': 1312} |
// Copyright 2014 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_api_samples/services/keyboard_key/logical_keyboard_key.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Responds to key', (WidgetTester tester) async {
await tester.pumpWidget(
const example.KeyExampleApp(),
);
await tester.tap(find.text('Click to focus'));
await tester.pumpAndSettle();
expect(find.text('Press a key'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.keyQ);
await tester.pumpAndSettle();
expect(find.text('Pressed the "Q" key!'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.keyB);
await tester.pumpAndSettle();
expect(find.text('Not a Q: Pressed Key B'), findsOneWidget);
});
}
| flutter/examples/api/test/services/keyboard_key/logical_keyboard_key.0_test.dart/0 | {'file_path': 'flutter/examples/api/test/services/keyboard_key/logical_keyboard_key.0_test.dart', 'repo_id': 'flutter', 'token_count': 338} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/widgets/animated_grid/sliver_animated_grid.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SliverAnimatedGrid example', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SliverAnimatedGridSample(),
);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
expect(find.text('6'), findsOneWidget);
expect(find.text('7'), findsNothing);
await tester.tap(find.byIcon(Icons.add_circle));
await tester.pumpAndSettle();
expect(find.text('7'), findsOneWidget);
await tester.tap(find.byIcon(Icons.remove_circle));
await tester.pumpAndSettle();
expect(find.text('7'), findsNothing);
await tester.tap(find.text('2'));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.remove_circle));
await tester.pumpAndSettle();
expect(find.text('2'), findsNothing);
expect(find.text('6'), findsOneWidget);
});
}
| flutter/examples/api/test/widgets/animated_grid/sliver_animated_grid.0_test.dart/0 | {'file_path': 'flutter/examples/api/test/widgets/animated_grid/sliver_animated_grid.0_test.dart', 'repo_id': 'flutter', 'token_count': 493} |
// Copyright 2014 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_api_samples/widgets/layout_builder/layout_builder.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('has two containers when wide', (WidgetTester tester) async {
await tester.pumpWidget(
const example.MyApp(),
);
final Finder containerFinder = find.byType(Container);
expect(containerFinder, findsNWidgets(2));
});
testWidgets('has one container when narrow', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: const example.MyApp(),
),
);
final Finder containerFinder = find.byType(Container);
expect(containerFinder, findsNWidgets(2));
});
}
| flutter/examples/api/test/widgets/layout_builder/layout_builder.0_test.dart/0 | {'file_path': 'flutter/examples/api/test/widgets/layout_builder/layout_builder.0_test.dart', 'repo_id': 'flutter', 'token_count': 333} |
// Copyright 2014 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 example shows how to build a render tree with a non-cartesian coordinate
// system. Most of the guts of this examples are in src/sector_layout.dart.
import 'package:flutter/rendering.dart';
import 'src/sector_layout.dart';
RenderBox buildSectorExample() {
final RenderSectorRing rootCircle = RenderSectorRing(padding: 20.0);
rootCircle.add(RenderSolidColor(const Color(0xFF00FFFF), desiredDeltaTheta: kTwoPi * 0.15));
rootCircle.add(RenderSolidColor(const Color(0xFF0000FF), desiredDeltaTheta: kTwoPi * 0.4));
final RenderSectorSlice stack = RenderSectorSlice(padding: 2.0);
stack.add(RenderSolidColor(const Color(0xFFFFFF00), desiredDeltaRadius: 20.0));
stack.add(RenderSolidColor(const Color(0xFFFF9000), desiredDeltaRadius: 20.0));
stack.add(RenderSolidColor(const Color(0xFF00FF00)));
rootCircle.add(stack);
return RenderBoxToRenderSectorAdapter(innerRadius: 50.0, child: rootCircle);
}
void main() {
RenderingFlutterBinding(root: buildSectorExample()).scheduleFrame();
}
| flutter/examples/layers/rendering/custom_coordinate_systems.dart/0 | {'file_path': 'flutter/examples/layers/rendering/custom_coordinate_systems.dart', 'repo_id': 'flutter', 'token_count': 374} |
# Copyright 2014 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.
# For details regarding the *Flutter Fix* feature, see
# https://flutter.dev/docs/development/tools/flutter-fix
# Please add new fixes to the top of the file, separated by one blank line
# from other fixes. In a comment, include a link to the PR where the change
# requiring the fix was made.
# Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md
# file for instructions on testing these data driven fixes.
# For documentation about this file format, see
# https://dart.dev/go/data-driven-fixes.
# * Fixes in this file are for BuildContext from the Widgets library. *
# For fixes to
# * Actions: fix_actions.yaml
# * Element: fix_element.yaml
# * ListWheelScrollView: fix_list_wheel_scroll_view.yaml
# * Widgets (general): fix_widgets.yaml
version: 1
transforms:
# Change made in https://github.com/flutter/flutter/pull/44189.
- title: "Rename to 'dependOnInheritedElement'"
date: 2019-11-22
element:
uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ]
inClass: 'BuildContext'
method: 'inheritFromElement'
changes:
- kind: 'rename'
newName: 'dependOnInheritedElement'
# Change made in https://github.com/flutter/flutter/pull/44189.
- title: "Migrate to 'dependOnInheritedWidgetOfExactType'"
date: 2019-11-22
element:
uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ]
inClass: 'BuildContext'
method: 'inheritFromWidgetOfExactType'
changes:
- kind: 'rename'
newName: 'dependOnInheritedWidgetOfExactType'
- kind: 'removeParameter'
index: 0
- kind: 'addTypeParameter'
index: 0
name: 'T'
argumentValue:
expression: '{% type %}'
variables:
type:
kind: fragment
value: 'arguments[0]'
# Change made in https://github.com/flutter/flutter/pull/44189.
- title: "Migrate to 'getElementForInheritedWidgetOfExactType'"
date: 2019-11-22
element:
uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ]
inClass: 'BuildContext'
method: 'ancestorInheritedElementForWidgetOfExactType'
changes:
- kind: 'rename'
newName: 'getElementForInheritedWidgetOfExactType'
- kind: 'removeParameter'
index: 0
- kind: 'addTypeParameter'
index: 0
name: 'T'
argumentValue:
expression: '{% type %}'
variables:
type:
kind: fragment
value: 'arguments[0]'
# Change made in https://github.com/flutter/flutter/pull/44189.
- title: "Migrate to 'findAncestorWidgetOfExactType'"
date: 2019-11-22
element:
uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ]
inClass: 'BuildContext'
method: 'ancestorWidgetOfExactType'
changes:
- kind: 'rename'
newName: 'findAncestorWidgetOfExactType'
- kind: 'removeParameter'
index: 0
- kind: 'addTypeParameter'
index: 0
name: 'T'
argumentValue:
expression: '{% type %}'
variables:
type:
kind: fragment
value: 'arguments[0]'
# Change made in https://github.com/flutter/flutter/pull/44189.
- title: "Migrate to 'findAncestorStateOfType'"
date: 2019-11-22
element:
uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ]
inClass: 'BuildContext'
method: 'ancestorStateOfType'
changes:
- kind: 'rename'
newName: 'findAncestorStateOfType'
- kind: 'removeParameter'
index: 0
- kind: 'addTypeParameter'
index: 0
name: 'T'
argumentValue:
expression: '{% type %}'
variables:
type:
kind: fragment
value: 'arguments[0].typeArguments[0]'
# Change made in https://github.com/flutter/flutter/pull/44189.
- title: "Migrate to 'rootAncestorStateOfType'"
date: 2019-11-22
element:
uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ]
inClass: 'BuildContext'
method: 'rootAncestorStateOfType'
changes:
- kind: 'rename'
newName: 'findRootAncestorStateOfType'
- kind: 'removeParameter'
index: 0
- kind: 'addTypeParameter'
index: 0
name: 'T'
argumentValue:
expression: '{% type %}'
variables:
type:
kind: fragment
value: 'arguments[0].typeArguments[0]'
# Change made in https://github.com/flutter/flutter/pull/44189.
- title: "Migrate to 'ancestorRenderObjectOfType'"
date: 2019-11-22
element:
uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ]
inClass: 'BuildContext'
method: 'ancestorRenderObjectOfType'
changes:
- kind: 'rename'
newName: 'findAncestorRenderObjectOfType'
- kind: 'removeParameter'
index: 0
- kind: 'addTypeParameter'
index: 0
name: 'T'
argumentValue:
expression: '{% type %}'
variables:
type:
kind: fragment
value: 'arguments[0].typeArguments[0]'
# Before adding a new fix: read instructions at the top of this file.
| flutter/packages/flutter/lib/fix_data/fix_widgets/fix_build_context.yaml/0 | {'file_path': 'flutter/packages/flutter/lib/fix_data/fix_widgets/fix_build_context.yaml', 'repo_id': 'flutter', 'token_count': 2410} |
// Copyright 2014 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 'colors.dart';
// The minimum padding from all edges of the selection toolbar to all edges of
// the screen.
const double _kToolbarScreenPadding = 8.0;
// These values were measured from a screenshot of TextEdit on macOS 10.15.7 on
// a Macbook Pro.
const double _kToolbarWidth = 222.0;
const Radius _kToolbarBorderRadius = Radius.circular(4.0);
const EdgeInsets _kToolbarPadding = EdgeInsets.symmetric(
vertical: 3.0,
);
// These values were measured from a screenshot of TextEdit on macOS 10.16 on a
// Macbook Pro.
const CupertinoDynamicColor _kToolbarBorderColor = CupertinoDynamicColor.withBrightness(
color: Color(0xFFBBBBBB),
darkColor: Color(0xFF505152),
);
const CupertinoDynamicColor _kToolbarBackgroundColor = CupertinoDynamicColor.withBrightness(
color: Color(0xffECE8E6),
darkColor: Color(0xff302928),
);
/// A macOS-style text selection toolbar.
///
/// Typically displays buttons for text manipulation, e.g. copying and pasting
/// text.
///
/// Tries to position itself as closely as possible to [anchor] while remaining
/// fully inside the viewport.
///
/// See also:
///
/// * [CupertinoAdaptiveTextSelectionToolbar], where this is used to build the
/// toolbar for desktop platforms.
/// * [AdaptiveTextSelectionToolbar], where this is used to build the toolbar on
/// macOS.
/// * [DesktopTextSelectionToolbar], which is similar but builds a
/// Material-style desktop toolbar.
class CupertinoDesktopTextSelectionToolbar extends StatelessWidget {
/// Creates a const instance of CupertinoTextSelectionToolbar.
const CupertinoDesktopTextSelectionToolbar({
super.key,
required this.anchor,
required this.children,
}) : assert(children.length > 0);
/// {@macro flutter.material.DesktopTextSelectionToolbar.anchor}
final Offset anchor;
/// {@macro flutter.material.TextSelectionToolbar.children}
///
/// See also:
/// * [CupertinoDesktopTextSelectionToolbarButton], which builds a default
/// macOS-style text selection toolbar text button.
final List<Widget> children;
// Builds a toolbar just like the default Mac toolbar, with the right color
// background, padding, and rounded corners.
static Widget _defaultToolbarBuilder(BuildContext context, Widget child) {
return Container(
width: _kToolbarWidth,
decoration: BoxDecoration(
color: _kToolbarBackgroundColor.resolveFrom(context),
border: Border.all(
color: _kToolbarBorderColor.resolveFrom(context),
),
borderRadius: const BorderRadius.all(_kToolbarBorderRadius),
),
child: Padding(
padding: _kToolbarPadding,
child: child,
),
);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
final double paddingAbove = MediaQuery.paddingOf(context).top + _kToolbarScreenPadding;
final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove);
return Padding(
padding: EdgeInsets.fromLTRB(
_kToolbarScreenPadding,
paddingAbove,
_kToolbarScreenPadding,
_kToolbarScreenPadding,
),
child: CustomSingleChildLayout(
delegate: DesktopTextSelectionToolbarLayoutDelegate(
anchor: anchor - localAdjustment,
),
child: _defaultToolbarBuilder(
context,
Column(
mainAxisSize: MainAxisSize.min,
children: children,
),
),
),
);
}
}
| flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart', 'repo_id': 'flutter', 'token_count': 1268} |
// Copyright 2014 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/painting.dart';
import 'colors.dart';
const Color _kThumbBorderColor = Color(0x0A000000);
const List<BoxShadow> _kSwitchBoxShadows = <BoxShadow> [
BoxShadow(
color: Color(0x26000000),
offset: Offset(0, 3),
blurRadius: 8.0,
),
BoxShadow(
color: Color(0x0F000000),
offset: Offset(0, 3),
blurRadius: 1.0,
),
];
const List<BoxShadow> _kSliderBoxShadows = <BoxShadow> [
BoxShadow(
color: Color(0x26000000),
offset: Offset(0, 3),
blurRadius: 8.0,
),
BoxShadow(
color: Color(0x29000000),
offset: Offset(0, 1),
blurRadius: 1.0,
),
BoxShadow(
color: Color(0x1A000000),
offset: Offset(0, 3),
blurRadius: 1.0,
),
];
/// Paints an iOS-style slider thumb or switch thumb.
///
/// Used by [CupertinoSwitch] and [CupertinoSlider].
class CupertinoThumbPainter {
/// Creates an object that paints an iOS-style slider thumb.
const CupertinoThumbPainter({
this.color = CupertinoColors.white,
this.shadows = _kSliderBoxShadows,
});
/// Creates an object that paints an iOS-style switch thumb.
const CupertinoThumbPainter.switchThumb({
Color color = CupertinoColors.white,
List<BoxShadow> shadows = _kSwitchBoxShadows,
}) : this(color: color, shadows: shadows);
/// The color of the interior of the thumb.
final Color color;
/// The list of [BoxShadow] to paint below the thumb.
///
/// Must not be null.
final List<BoxShadow> shadows;
/// Half the default diameter of the thumb.
static const double radius = 14.0;
/// The default amount the thumb should be extended horizontally when pressed.
static const double extension = 7.0;
/// Paints the thumb onto the given canvas in the given rectangle.
///
/// Consider using [radius] and [extension] when deciding how large a
/// rectangle to use for the thumb.
void paint(Canvas canvas, Rect rect) {
final RRect rrect = RRect.fromRectAndRadius(
rect,
Radius.circular(rect.shortestSide / 2.0),
);
for (final BoxShadow shadow in shadows) {
canvas.drawRRect(rrect.shift(shadow.offset), shadow.toPaint());
}
canvas.drawRRect(
rrect.inflate(0.5),
Paint()..color = _kThumbBorderColor,
);
canvas.drawRRect(rrect, Paint()..color = color);
}
}
| flutter/packages/flutter/lib/src/cupertino/thumb_painter.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/cupertino/thumb_painter.dart', 'repo_id': 'flutter', 'token_count': 885} |
// Copyright 2014 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 '_platform_io.dart'
if (dart.library.js_util) '_platform_web.dart' as platform;
/// The [TargetPlatform] that matches the platform on which the framework is
/// currently executing.
///
/// This is the default value of [ThemeData.platform] (hence the name). Widgets
/// from the material library should use [Theme.of] to determine the current
/// platform for styling purposes, rather than using [defaultTargetPlatform].
/// Widgets and render objects at lower layers that try to emulate the
/// underlying platform can depend on [defaultTargetPlatform] directly. The
/// [dart:io.Platform] object should only be used directly when it's critical to
/// actually know the current platform, without any overrides possible (for
/// example, when a system API is about to be called).
///
/// In a test environment, the platform returned is [TargetPlatform.android]
/// regardless of the host platform. (Android was chosen because the tests were
/// originally written assuming Android-like behavior, and we added platform
/// adaptations for iOS later). Tests can check iOS behavior by using the
/// platform override APIs (such as [ThemeData.platform] in the material
/// library) or by setting [debugDefaultTargetPlatformOverride].
///
/// Tests can also create specific platform tests by and adding a `variant:`
/// argument to the test and using a [TargetPlatformVariant].
//
// When adding support for a new platform (e.g. Windows Phone, Raspberry Pi),
// first create a new value on the [TargetPlatform] enum, then add a rule for
// selecting that platform here.
//
// It would be incorrect to make a platform that isn't supported by
// [TargetPlatform] default to the behavior of another platform, because doing
// that would mean we'd be stuck with that platform forever emulating the other,
// and we'd never be able to introduce dedicated behavior for that platform
// (since doing so would be a big breaking change).
TargetPlatform get defaultTargetPlatform => platform.defaultTargetPlatform;
/// The platform that user interaction should adapt to target.
///
/// The [defaultTargetPlatform] getter returns the current platform.
enum TargetPlatform {
/// Android: <https://www.android.com/>
android,
/// Fuchsia: <https://fuchsia.dev/fuchsia-src/concepts>
fuchsia,
/// iOS: <https://www.apple.com/ios/>
iOS,
/// Linux: <https://www.linux.org>
linux,
/// macOS: <https://www.apple.com/macos>
macOS,
/// Windows: <https://www.windows.com>
windows,
}
/// Override the [defaultTargetPlatform].
///
/// Setting this to null returns the [defaultTargetPlatform] to its original
/// value (based on the actual current platform).
///
/// Generally speaking this override is only useful for tests. To change the
/// platform that widgets resemble, consider using the platform override APIs
/// (such as [ThemeData.platform] in the material library) instead.
///
/// Setting [debugDefaultTargetPlatformOverride] (as opposed to, say,
/// [ThemeData.platform]) will cause unexpected and undesirable effects. For
/// example, setting this to [TargetPlatform.iOS] when the application is
/// running on Android will cause the TalkBack accessibility tool on Android to
/// be confused because it would be receiving data intended for iOS VoiceOver.
/// Similarly, setting it to [TargetPlatform.android] while on iOS will cause
/// certainly widgets to work assuming the presence of a system-wide back
/// button, which will make those widgets unusable since iOS has no such button.
///
/// In general, therefore, this property should not be used in release builds.
TargetPlatform? debugDefaultTargetPlatformOverride;
| flutter/packages/flutter/lib/src/foundation/platform.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/foundation/platform.dart', 'repo_id': 'flutter', 'token_count': 922} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// AUTOGENERATED FILE DO NOT EDIT!
// This file was generated by vitool.
part of material_animated_icons; // ignore: use_string_in_part_of_directives
const _AnimatedIconData _$pause_play = _AnimatedIconData(
Size(48.0, 48.0),
<_PathFrames>[
_PathFrames(
opacities: <double>[
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(12.0, 38.0),
Offset(11.702518567871357, 37.66537647364598),
Offset(10.658516625352865, 36.33928535710834),
Offset(8.824010134196683, 33.09051115695809),
Offset(7.183618981881198, 27.281162329416798),
Offset(7.4961448079806345, 21.476581828368367),
Offset(9.111297618374987, 17.041890063132637),
Offset(10.944617318451954, 14.273857051215758),
Offset(12.539001321903285, 12.570685504133255),
Offset(13.794958189315498, 11.511449771679523),
Offset(14.725226220617056, 10.84845238497297),
Offset(15.369630177419687, 10.439047154098617),
Offset(15.770227104208459, 10.200145460041224),
Offset(15.977727112935135, 10.078681424879498),
Offset(16.046646118566024, 10.039192889334426),
Offset(16.046875, 10.039062500000002),
],
),
_PathCubicTo(
<Offset>[
Offset(12.0, 38.0),
Offset(11.702518567871357, 37.66537647364598),
Offset(10.658516625352865, 36.33928535710834),
Offset(8.824010134196683, 33.09051115695809),
Offset(7.183618981881198, 27.281162329416798),
Offset(7.4961448079806345, 21.476581828368367),
Offset(9.111297618374987, 17.041890063132637),
Offset(10.944617318451954, 14.273857051215758),
Offset(12.539001321903285, 12.570685504133255),
Offset(13.794958189315498, 11.511449771679523),
Offset(14.725226220617056, 10.84845238497297),
Offset(15.369630177419687, 10.439047154098617),
Offset(15.770227104208459, 10.200145460041224),
Offset(15.977727112935135, 10.078681424879498),
Offset(16.046646118566024, 10.039192889334426),
Offset(16.046875, 10.039062500000002),
],
<Offset>[
Offset(20.0, 38.0),
Offset(19.80052916638957, 37.82094858440343),
Offset(19.11164196247534, 37.113338636628065),
Offset(17.966685507002932, 35.41245490387412),
Offset(16.388368582775627, 32.64921363804367),
Offset(15.647464737031132, 29.978925368550197),
Offset(15.429304294338682, 27.901717576585412),
Offset(15.521061545777922, 26.541981731286498),
Offset(15.686957461206134, 25.650190745693187),
Offset(15.84005263487414, 25.05047803281999),
Offset(15.953666440217397, 24.63834819764938),
Offset(16.022300799535966, 24.35280207511846),
Offset(16.047681038809458, 24.15758118207667),
Offset(16.04697282889272, 24.039447195772148),
Offset(16.046875001068816, 24.00013038745822),
Offset(16.046875, 24.0),
],
<Offset>[
Offset(20.0, 38.0),
Offset(19.80052916638957, 37.82094858440343),
Offset(19.11164196247534, 37.113338636628065),
Offset(17.966685507002932, 35.41245490387412),
Offset(16.388368582775627, 32.64921363804367),
Offset(15.647464737031132, 29.978925368550197),
Offset(15.429304294338682, 27.901717576585412),
Offset(15.521061545777922, 26.541981731286498),
Offset(15.686957461206134, 25.650190745693187),
Offset(15.84005263487414, 25.05047803281999),
Offset(15.953666440217397, 24.63834819764938),
Offset(16.022300799535966, 24.35280207511846),
Offset(16.047681038809458, 24.15758118207667),
Offset(16.04697282889272, 24.039447195772148),
Offset(16.046875001068816, 24.00013038745822),
Offset(16.046875, 24.0),
],
),
_PathCubicTo(
<Offset>[
Offset(20.0, 38.0),
Offset(19.80052916638957, 37.82094858440343),
Offset(19.11164196247534, 37.113338636628065),
Offset(17.966685507002932, 35.41245490387412),
Offset(16.388368582775627, 32.64921363804367),
Offset(15.647464737031132, 29.978925368550197),
Offset(15.429304294338682, 27.901717576585412),
Offset(15.521061545777922, 26.541981731286498),
Offset(15.686957461206134, 25.650190745693187),
Offset(15.84005263487414, 25.05047803281999),
Offset(15.953666440217397, 24.63834819764938),
Offset(16.022300799535966, 24.35280207511846),
Offset(16.047681038809458, 24.15758118207667),
Offset(16.04697282889272, 24.039447195772148),
Offset(16.046875001068816, 24.00013038745822),
Offset(16.046875, 24.0),
],
<Offset>[
Offset(20.0, 10.0),
Offset(20.336398367184067, 9.927295626138141),
Offset(21.61961776538543, 9.72474102274872),
Offset(24.500250707242675, 9.686480391272799),
Offset(29.133385987204207, 10.794971358676317),
Offset(33.085276289027, 13.261042804636414),
Offset(35.61934940727931, 16.155597331715125),
Offset(36.90120687325454, 18.566431660274624),
Offset(37.51766973937702, 20.39600693122759),
Offset(37.80131897673813, 21.733189454430033),
Offset(37.922586409468074, 22.681298975667566),
Offset(37.96809580639086, 23.323362088481808),
Offset(37.98160482507013, 23.72156603022978),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(20.0, 10.0),
Offset(20.336398367184067, 9.927295626138141),
Offset(21.61961776538543, 9.72474102274872),
Offset(24.500250707242675, 9.686480391272799),
Offset(29.133385987204207, 10.794971358676317),
Offset(33.085276289027, 13.261042804636414),
Offset(35.61934940727931, 16.155597331715125),
Offset(36.90120687325454, 18.566431660274624),
Offset(37.51766973937702, 20.39600693122759),
Offset(37.80131897673813, 21.733189454430033),
Offset(37.922586409468074, 22.681298975667566),
Offset(37.96809580639086, 23.323362088481808),
Offset(37.98160482507013, 23.72156603022978),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
),
_PathCubicTo(
<Offset>[
Offset(20.0, 10.0),
Offset(20.336398367184067, 9.927295626138141),
Offset(21.61961776538543, 9.72474102274872),
Offset(24.500250707242675, 9.686480391272799),
Offset(29.133385987204207, 10.794971358676317),
Offset(33.085276289027, 13.261042804636414),
Offset(35.61934940727931, 16.155597331715125),
Offset(36.90120687325454, 18.566431660274624),
Offset(37.51766973937702, 20.39600693122759),
Offset(37.80131897673813, 21.733189454430033),
Offset(37.922586409468074, 22.681298975667566),
Offset(37.96809580639086, 23.323362088481808),
Offset(37.98160482507013, 23.72156603022978),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(12.0, 10.0),
Offset(12.471392106978678, 9.776199797090369),
Offset(14.305807236043629, 9.055014880021247),
Offset(18.610309025181536, 8.190625764405059),
Offset(25.30150028462865, 8.56028166562692),
Offset(31.058306963326036, 11.146785273031004),
Offset(34.676551168058815, 14.535050411928939),
Offset(36.494518178468795, 17.476216776016784),
Offset(37.358155554762675, 19.733238289785056),
Offset(37.747534126472296, 21.37712051621949),
Offset(37.90872109014562, 22.525653380696408),
Offset(37.966090830555, 23.280619636994825),
Offset(37.98158497072831, 23.720567249296572),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(12.0, 10.0),
Offset(12.471392106978678, 9.776199797090369),
Offset(14.305807236043629, 9.055014880021247),
Offset(18.610309025181536, 8.190625764405059),
Offset(25.30150028462865, 8.56028166562692),
Offset(31.058306963326036, 11.146785273031004),
Offset(34.676551168058815, 14.535050411928939),
Offset(36.494518178468795, 17.476216776016784),
Offset(37.358155554762675, 19.733238289785056),
Offset(37.747534126472296, 21.37712051621949),
Offset(37.90872109014562, 22.525653380696408),
Offset(37.966090830555, 23.280619636994825),
Offset(37.98158497072831, 23.720567249296572),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
),
_PathCubicTo(
<Offset>[
Offset(12.0, 10.0),
Offset(12.471392106978678, 9.776199797090369),
Offset(14.305807236043629, 9.055014880021247),
Offset(18.610309025181536, 8.190625764405059),
Offset(25.30150028462865, 8.56028166562692),
Offset(31.058306963326036, 11.146785273031004),
Offset(34.676551168058815, 14.535050411928939),
Offset(36.494518178468795, 17.476216776016784),
Offset(37.358155554762675, 19.733238289785056),
Offset(37.747534126472296, 21.37712051621949),
Offset(37.90872109014562, 22.525653380696408),
Offset(37.966090830555, 23.280619636994825),
Offset(37.98158497072831, 23.720567249296572),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(12.0, 38.0),
Offset(11.702518567871357, 37.66537647364598),
Offset(10.658516625352863, 36.33928535710834),
Offset(8.824010134196683, 33.09051115695809),
Offset(7.1836189818552825, 27.281162329401685),
Offset(7.496144808015238, 21.476581828404456),
Offset(9.111297618380014, 17.04189006314128),
Offset(10.944617318448458, 14.273857051206388),
Offset(12.53900132190984, 12.570685504160476),
Offset(13.794958189310869, 11.511449771648872),
Offset(14.725226220612885, 10.848452384926155),
Offset(15.369630177421872, 10.439047154145166),
Offset(15.770227104207432, 10.2001454599895),
Offset(15.977727112935135, 10.078681424879498),
Offset(16.046646118566024, 10.039192889334426),
Offset(16.046875, 10.039062500000002),
],
<Offset>[
Offset(12.0, 38.0),
Offset(11.702518567871357, 37.66537647364598),
Offset(10.658516625352863, 36.33928535710834),
Offset(8.824010134196683, 33.09051115695809),
Offset(7.1836189818552825, 27.281162329401685),
Offset(7.496144808015238, 21.476581828404456),
Offset(9.111297618380014, 17.04189006314128),
Offset(10.944617318448458, 14.273857051206388),
Offset(12.53900132190984, 12.570685504160476),
Offset(13.794958189310869, 11.511449771648872),
Offset(14.725226220612885, 10.848452384926155),
Offset(15.369630177421872, 10.439047154145166),
Offset(15.770227104207432, 10.2001454599895),
Offset(15.977727112935135, 10.078681424879498),
Offset(16.046646118566024, 10.039192889334426),
Offset(16.046875, 10.039062500000002),
],
),
_PathClose(
),
],
),
_PathFrames(
opacities: <double>[
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(28.0, 10.0),
Offset(28.201404627403626, 10.078391455203436),
Offset(28.933428294762216, 10.394467165488965),
Offset(30.390192389339767, 11.182335018165535),
Offset(32.965271689797355, 13.029661051643949),
Offset(35.1122456147493, 15.375300336193657),
Offset(36.562147646495, 17.776144251469397),
Offset(37.30789556803902, 19.656646544522257),
Offset(37.67718392397584, 21.05877557270265),
Offset(37.8551038269895, 22.089258392661982),
Offset(37.936451728823435, 22.836944570678963),
Offset(37.970100782170086, 23.366104539917995),
Offset(37.98162467944151, 23.722564811170674),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
),
_PathCubicTo(
<Offset>[
Offset(28.0, 10.0),
Offset(28.201404627403626, 10.078391455203436),
Offset(28.933428294762216, 10.394467165488965),
Offset(30.390192389339767, 11.182335018165535),
Offset(32.965271689797355, 13.029661051643949),
Offset(35.1122456147493, 15.375300336193657),
Offset(36.562147646495, 17.776144251469397),
Offset(37.30789556803902, 19.656646544522257),
Offset(37.67718392397584, 21.05877557270265),
Offset(37.8551038269895, 22.089258392661982),
Offset(37.936451728823435, 22.836944570678963),
Offset(37.970100782170086, 23.366104539917995),
Offset(37.98162467944151, 23.722564811170674),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(28.0, 38.0),
Offset(27.665535426609125, 37.97204441346873),
Offset(26.425452491852123, 37.78306477936831),
Offset(23.856627189100024, 36.90830953076686),
Offset(20.220254285368775, 34.883903331011304),
Offset(17.674434062753434, 32.09318290010744),
Offset(16.372102533554372, 29.522264496339687),
Offset(15.927750240562414, 27.632196615534127),
Offset(15.84647164580496, 26.31295938716825),
Offset(15.893837485125506, 25.406546971051934),
Offset(15.967531759572758, 24.79399379266078),
Offset(16.024305775315185, 24.395544526554644),
Offset(16.04770089318083, 24.15857996301756),
Offset(16.04697282889272, 24.039447195772148),
Offset(16.046875001068816, 24.00013038745822),
Offset(16.046875, 24.0),
],
<Offset>[
Offset(28.0, 38.0),
Offset(27.665535426609125, 37.97204441346873),
Offset(26.425452491852123, 37.78306477936831),
Offset(23.856627189100024, 36.90830953076686),
Offset(20.220254285368775, 34.883903331011304),
Offset(17.674434062753434, 32.09318290010744),
Offset(16.372102533554372, 29.522264496339687),
Offset(15.927750240562414, 27.632196615534127),
Offset(15.84647164580496, 26.31295938716825),
Offset(15.893837485125506, 25.406546971051934),
Offset(15.967531759572758, 24.79399379266078),
Offset(16.024305775315185, 24.395544526554644),
Offset(16.04770089318083, 24.15857996301756),
Offset(16.04697282889272, 24.039447195772148),
Offset(16.046875001068816, 24.00013038745822),
Offset(16.046875, 24.0),
],
),
_PathCubicTo(
<Offset>[
Offset(28.0, 38.0),
Offset(27.665535426609125, 37.97204441346873),
Offset(26.425452491852123, 37.78306477936831),
Offset(23.856627189100024, 36.90830953076686),
Offset(20.220254285368775, 34.883903331011304),
Offset(17.674434062753434, 32.09318290010744),
Offset(16.372102533554372, 29.522264496339687),
Offset(15.927750240562414, 27.632196615534127),
Offset(15.84647164580496, 26.31295938716825),
Offset(15.893837485125506, 25.406546971051934),
Offset(15.967531759572758, 24.79399379266078),
Offset(16.024305775315185, 24.395544526554644),
Offset(16.04770089318083, 24.15857996301756),
Offset(16.04697282889272, 24.039447195772148),
Offset(16.046875001068816, 24.00013038745822),
Offset(16.046875, 24.0),
],
<Offset>[
Offset(36.0, 38.0),
Offset(35.76354602512734, 38.127616524226184),
Offset(34.8785778289746, 38.55711805888804),
Offset(32.999302561906276, 39.23025327768289),
Offset(29.425003886263205, 40.25195463963817),
Offset(25.82575399180393, 40.59552644028928),
Offset(22.690109209518063, 40.382092009792466),
Offset(20.504194467888382, 39.90032129560486),
Offset(18.99442778510781, 39.39246462872818),
Offset(17.93893193068415, 38.9455752321924),
Offset(17.195971979173102, 38.583889605337184),
Offset(16.676976397431464, 38.30929944757449),
Offset(16.325154827781827, 38.116015685053),
Offset(16.11621854485031, 38.00021296666479),
Offset(16.047103883571605, 37.96106788558201),
Offset(16.046875, 37.9609375),
],
<Offset>[
Offset(36.0, 38.0),
Offset(35.76354602512734, 38.127616524226184),
Offset(34.8785778289746, 38.55711805888804),
Offset(32.999302561906276, 39.23025327768289),
Offset(29.425003886263205, 40.25195463963817),
Offset(25.82575399180393, 40.59552644028928),
Offset(22.690109209518063, 40.382092009792466),
Offset(20.504194467888382, 39.90032129560486),
Offset(18.99442778510781, 39.39246462872818),
Offset(17.93893193068415, 38.9455752321924),
Offset(17.195971979173102, 38.583889605337184),
Offset(16.676976397431464, 38.30929944757449),
Offset(16.325154827781827, 38.116015685053),
Offset(16.11621854485031, 38.00021296666479),
Offset(16.047103883571605, 37.96106788558201),
Offset(16.046875, 37.9609375),
],
),
_PathCubicTo(
<Offset>[
Offset(36.0, 38.0),
Offset(35.76354602512734, 38.127616524226184),
Offset(34.8785778289746, 38.55711805888804),
Offset(32.999302561906276, 39.23025327768289),
Offset(29.425003886263205, 40.25195463963817),
Offset(25.82575399180393, 40.59552644028928),
Offset(22.690109209518063, 40.382092009792466),
Offset(20.504194467888382, 39.90032129560486),
Offset(18.99442778510781, 39.39246462872818),
Offset(17.93893193068415, 38.9455752321924),
Offset(17.195971979173102, 38.583889605337184),
Offset(16.676976397431464, 38.30929944757449),
Offset(16.325154827781827, 38.116015685053),
Offset(16.11621854485031, 38.00021296666479),
Offset(16.047103883571605, 37.96106788558201),
Offset(16.046875, 37.9609375),
],
<Offset>[
Offset(36.0, 10.0),
Offset(36.06641088760902, 10.22948728425121),
Offset(36.247238824104016, 11.064193308216439),
Offset(36.28013407140091, 12.678189645033275),
Offset(36.797157392346996, 15.26435074467823),
Offset(37.13921494048486, 17.48955786783516),
Offset(37.50494588572052, 19.396691171264223),
Offset(37.71458426282127, 20.746861428770725),
Offset(37.836698108596735, 21.721544214172404),
Offset(37.9088886772507, 22.445327330841877),
Offset(37.95031704814173, 22.992590165603303),
Offset(37.972105758008134, 23.40884699145153),
Offset(37.981644533782294, 23.72356359205216),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(36.0, 10.0),
Offset(36.06641088760902, 10.22948728425121),
Offset(36.247238824104016, 11.064193308216439),
Offset(36.28013407140091, 12.678189645033275),
Offset(36.797157392346996, 15.26435074467823),
Offset(37.13921494048486, 17.48955786783516),
Offset(37.50494588572052, 19.396691171264223),
Offset(37.71458426282127, 20.746861428770725),
Offset(37.836698108596735, 21.721544214172404),
Offset(37.9088886772507, 22.445327330841877),
Offset(37.95031704814173, 22.992590165603303),
Offset(37.972105758008134, 23.40884699145153),
Offset(37.981644533782294, 23.72356359205216),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
),
_PathCubicTo(
<Offset>[
Offset(36.0, 10.0),
Offset(36.06641088760902, 10.22948728425121),
Offset(36.247238824104016, 11.064193308216439),
Offset(36.28013407140091, 12.678189645033275),
Offset(36.797157392346996, 15.26435074467823),
Offset(37.13921494048486, 17.48955786783516),
Offset(37.50494588572052, 19.396691171264223),
Offset(37.71458426282127, 20.746861428770725),
Offset(37.836698108596735, 21.721544214172404),
Offset(37.9088886772507, 22.445327330841877),
Offset(37.95031704814173, 22.992590165603303),
Offset(37.972105758008134, 23.40884699145153),
Offset(37.981644533782294, 23.72356359205216),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(28.0, 10.0),
Offset(28.201404627403626, 10.078391455203436),
Offset(28.933428294762216, 10.394467165488965),
Offset(30.390192389339767, 11.182335018165535),
Offset(32.965271689771434, 13.029661051628835),
Offset(35.1122456147839, 15.37530033622975),
Offset(36.56214764650002, 17.776144251478037),
Offset(37.30789556803553, 19.656646544512885),
Offset(37.6771839239824, 21.058775572729875),
Offset(37.855103826984866, 22.08925839263133),
Offset(37.936451728819264, 22.83694457063215),
Offset(37.97010078217227, 23.366104539964546),
Offset(37.98162467944048, 23.72256481111895),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
<Offset>[
Offset(28.0, 10.0),
Offset(28.201404627403626, 10.078391455203436),
Offset(28.933428294762216, 10.394467165488965),
Offset(30.390192389339767, 11.182335018165535),
Offset(32.965271689771434, 13.029661051628835),
Offset(35.1122456147839, 15.37530033622975),
Offset(36.56214764650002, 17.776144251478037),
Offset(37.30789556803553, 19.656646544512885),
Offset(37.6771839239824, 21.058775572729875),
Offset(37.855103826984866, 22.08925839263133),
Offset(37.936451728819264, 22.83694457063215),
Offset(37.97010078217227, 23.366104539964546),
Offset(37.98162467944048, 23.72256481111895),
Offset(37.98420298259533, 23.93063803493896),
Offset(37.98437499812064, 23.99977073325126),
Offset(37.984375, 24.0),
],
),
_PathClose(
),
],
),
_PathFrames(
opacities: <double>[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.4,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(25.9803619385, 10.0808715820312),
Offset(26.24734975266162, 10.121477441291603),
Offset(27.241376275815597, 10.319449968588765),
Offset(29.345667299377446, 10.996623113678018),
Offset(32.72280163575925, 12.973817480806794),
Offset(35.41804029052999, 15.796810056618218),
Offset(36.783888674275296, 18.8537388815253),
Offset(36.76701249453052, 21.35111747744179),
Offset(36.26390281517317, 23.085253769933463),
Offset(35.55535514851543, 24.257370049664456),
Offset(34.77089367166791, 25.028704643469656),
Offset(33.96889356105216, 25.514915651546502),
Offset(33.73686027995342, 25.787198268946305),
Offset(33.7091203242374, 25.93222884083115),
Offset(33.69944957998795, 25.98020292120046),
Offset(33.69941711426, 25.9803619385),
],
),
_PathCubicTo(
<Offset>[
Offset(25.9803619385, 10.0808715820312),
Offset(26.24734975266162, 10.121477441291603),
Offset(27.241376275815597, 10.319449968588765),
Offset(29.345667299377446, 10.996623113678018),
Offset(32.72280163575925, 12.973817480806794),
Offset(35.41804029052999, 15.796810056618218),
Offset(36.783888674275296, 18.8537388815253),
Offset(36.76701249453052, 21.35111747744179),
Offset(36.26390281517317, 23.085253769933463),
Offset(35.55535514851543, 24.257370049664456),
Offset(34.77089367166791, 25.028704643469656),
Offset(33.96889356105216, 25.514915651546502),
Offset(33.73686027995342, 25.787198268946305),
Offset(33.7091203242374, 25.93222884083115),
Offset(33.69944957998795, 25.98020292120046),
Offset(33.69941711426, 25.9803619385),
],
<Offset>[
Offset(21.71524047854, 10.08666992187495),
Offset(21.982903763348478, 10.045351931852684),
Offset(22.99349608666543, 9.936293880836264),
Offset(25.21035246628397, 9.952369351341783),
Offset(29.035517231913246, 10.830169092168797),
Offset(32.462182698221135, 12.722041677870582),
Offset(34.6342053830667, 15.169969772143412),
Offset(35.27135627354946, 17.356833870551508),
Offset(35.261093097185864, 18.9396949456921),
Offset(34.91382519935541, 20.040769389846336),
Offset(34.38827629668238, 20.780777793707646),
Offset(33.765232522395, 21.254657700831064),
Offset(33.64837008011561, 21.522993253407158),
Offset(33.68424238621404, 21.667178311445102),
Offset(33.695656510950016, 21.71508152285272),
Offset(33.69569396972875, 21.71524047854),
],
<Offset>[
Offset(21.71524047854, 10.08666992187495),
Offset(21.982903763348478, 10.045351931852684),
Offset(22.99349608666543, 9.936293880836264),
Offset(25.21035246628397, 9.952369351341783),
Offset(29.035517231913246, 10.830169092168797),
Offset(32.462182698221135, 12.722041677870582),
Offset(34.6342053830667, 15.169969772143412),
Offset(35.27135627354946, 17.356833870551508),
Offset(35.261093097185864, 18.9396949456921),
Offset(34.91382519935541, 20.040769389846336),
Offset(34.38827629668238, 20.780777793707646),
Offset(33.765232522395, 21.254657700831064),
Offset(33.64837008011561, 21.522993253407158),
Offset(33.68424238621404, 21.667178311445102),
Offset(33.695656510950016, 21.71508152285272),
Offset(33.69569396972875, 21.71524047854),
],
),
_PathCubicTo(
<Offset>[
Offset(21.71524047854, 10.08666992187495),
Offset(21.982903763348478, 10.045351931852684),
Offset(22.99349608666543, 9.936293880836264),
Offset(25.21035246628397, 9.952369351341783),
Offset(29.035517231913246, 10.830169092168797),
Offset(32.462182698221135, 12.722041677870582),
Offset(34.6342053830667, 15.169969772143412),
Offset(35.27135627354946, 17.356833870551508),
Offset(35.261093097185864, 18.9396949456921),
Offset(34.91382519935541, 20.040769389846336),
Offset(34.38827629668238, 20.780777793707646),
Offset(33.765232522395, 21.254657700831064),
Offset(33.64837008011561, 21.522993253407158),
Offset(33.68424238621404, 21.667178311445102),
Offset(33.695656510950016, 21.71508152285272),
Offset(33.69569396972875, 21.71524047854),
],
<Offset>[
Offset(20.38534545901, 33.58843994137495),
Offset(20.201841309352226, 33.51724216990988),
Offset(19.52604939723053, 33.21887595990057),
Offset(18.136339024380444, 32.40365324862053),
Offset(16.04712654551591, 30.461865967119433),
Offset(14.577060238240236, 28.0264269776442),
Offset(13.994487095033097, 25.634345790525074),
Offset(14.153634069120049, 23.79893867630368),
Offset(14.553527226932179, 22.528826743801503),
Offset(15.025384555247236, 21.662436101573526),
Offset(15.497710938825563, 21.080134472962335),
Offset(15.942008679892364, 20.700182681641447),
Offset(16.112739485629255, 20.479547499155572),
Offset(16.16612590845245, 20.362297297739467),
Offset(16.184204863198634, 20.323614463660565),
Offset(16.18426513672875, 20.323486328150004),
],
<Offset>[
Offset(20.38534545901, 33.58843994137495),
Offset(20.201841309352226, 33.51724216990988),
Offset(19.52604939723053, 33.21887595990057),
Offset(18.136339024380444, 32.40365324862053),
Offset(16.04712654551591, 30.461865967119433),
Offset(14.577060238240236, 28.0264269776442),
Offset(13.994487095033097, 25.634345790525074),
Offset(14.153634069120049, 23.79893867630368),
Offset(14.553527226932179, 22.528826743801503),
Offset(15.025384555247236, 21.662436101573526),
Offset(15.497710938825563, 21.080134472962335),
Offset(15.942008679892364, 20.700182681641447),
Offset(16.112739485629255, 20.479547499155572),
Offset(16.16612590845245, 20.362297297739467),
Offset(16.184204863198634, 20.323614463660565),
Offset(16.18426513672875, 20.323486328150004),
],
),
_PathCubicTo(
<Offset>[
Offset(20.38534545901, 33.58843994137495),
Offset(20.201841309352226, 33.51724216990988),
Offset(19.52604939723053, 33.21887595990057),
Offset(18.136339024380444, 32.40365324862053),
Offset(16.04712654551591, 30.461865967119433),
Offset(14.577060238240236, 28.0264269776442),
Offset(13.994487095033097, 25.634345790525074),
Offset(14.153634069120049, 23.79893867630368),
Offset(14.553527226932179, 22.528826743801503),
Offset(15.025384555247236, 21.662436101573526),
Offset(15.497710938825563, 21.080134472962335),
Offset(15.942008679892364, 20.700182681641447),
Offset(16.112739485629255, 20.479547499155572),
Offset(16.16612590845245, 20.362297297739467),
Offset(16.184204863198634, 20.323614463660565),
Offset(16.18426513672875, 20.323486328150004),
],
<Offset>[
Offset(26.45292663577, 33.61682128903115),
Offset(26.267757982058896, 33.66216200032068),
Offset(25.565762818520753, 33.800433030319155),
Offset(24.010240085864943, 33.92471641540826),
Offset(21.274220812328387, 33.54307228337337),
Offset(18.755635225924188, 32.42595626039356),
Offset(17.02173119623894, 30.892872384129042),
Offset(16.25004855832711, 29.492905492037444),
Offset(15.94990552834042, 28.433591685898556),
Offset(15.909598267598703, 27.665285725985097),
Offset(16.015710329110547, 27.125598624037742),
Offset(16.207680408412312, 26.761973499405),
Offset(16.21513039026629, 26.546291998077596),
Offset(16.178017367555142, 26.42989412892011),
Offset(16.166100602771248, 26.391195938046174),
Offset(16.16606140137715, 26.391067504910005),
],
<Offset>[
Offset(26.45292663577, 33.61682128903125),
Offset(26.267757982058896, 33.66216200032078),
Offset(25.565762818520742, 33.800433030319255),
Offset(24.010240085864922, 33.924716415408355),
Offset(21.274220812328338, 33.543072283373455),
Offset(18.75563522592411, 32.42595626039363),
Offset(17.02173119623894, 30.892872384129042),
Offset(16.25004855832711, 29.492905492037444),
Offset(15.94990552834032, 28.433591685898577),
Offset(15.909598267598604, 27.66528572598511),
Offset(16.015710329110444, 27.12559862403775),
Offset(16.207680408412212, 26.761973499405002),
Offset(16.21513039026629, 26.546291998077596),
Offset(16.178017367555142, 26.42989412892011),
Offset(16.166100602771248, 26.391195938046174),
Offset(16.16606140137715, 26.391067504910005),
],
),
_PathCubicTo(
<Offset>[
Offset(26.45292663577, 33.61682128903125),
Offset(26.267757982058896, 33.66216200032078),
Offset(25.565762818520742, 33.800433030319255),
Offset(24.010240085864922, 33.924716415408355),
Offset(21.274220812328338, 33.543072283373455),
Offset(18.75563522592411, 32.42595626039363),
Offset(17.02173119623894, 30.892872384129042),
Offset(16.25004855832711, 29.492905492037444),
Offset(15.94990552834032, 28.433591685898577),
Offset(15.909598267598604, 27.66528572598511),
Offset(16.015710329110444, 27.12559862403775),
Offset(16.207680408412212, 26.761973499405002),
Offset(16.21513039026629, 26.546291998077596),
Offset(16.178017367555142, 26.42989412892011),
Offset(16.166100602771248, 26.391195938046174),
Offset(16.16606140137715, 26.391067504910005),
],
<Offset>[
Offset(25.980361938504004, 10.08087158203125),
Offset(26.24734975266562, 10.121477441291729),
Offset(27.241376275819576, 10.319449968589181),
Offset(29.34566729938131, 10.996623113679052),
Offset(32.72280163576268, 12.973817480808854),
Offset(35.418040290532716, 15.796810056621142),
Offset(36.78388867431184, 18.85373888150635),
Offset(36.7670124944848, 21.351117477459912),
Offset(36.26390281513503, 23.08525376994367),
Offset(35.55535514848602, 24.2573700496689),
Offset(34.770893671747466, 25.028704643461566),
Offset(33.968893561041796, 25.51491565154599),
Offset(33.73686027997065, 25.787198268949965),
Offset(33.70912032425456, 25.93222884083507),
Offset(33.6994495800051, 25.98020292120446),
Offset(33.69941711427715, 25.980361938504004),
],
<Offset>[
Offset(25.980361938504004, 10.08087158203125),
Offset(26.24734975266562, 10.121477441291729),
Offset(27.241376275819576, 10.319449968589181),
Offset(29.34566729938131, 10.996623113679052),
Offset(32.72280163576268, 12.973817480808854),
Offset(35.418040290532716, 15.796810056621142),
Offset(36.78388867431184, 18.85373888150635),
Offset(36.7670124944848, 21.351117477459912),
Offset(36.26390281513503, 23.08525376994367),
Offset(35.55535514848602, 24.2573700496689),
Offset(34.770893671747466, 25.028704643461566),
Offset(33.968893561041796, 25.51491565154599),
Offset(33.73686027997065, 25.787198268949965),
Offset(33.70912032425456, 25.93222884083507),
Offset(33.6994495800051, 25.98020292120446),
Offset(33.69941711427715, 25.980361938504004),
],
),
_PathClose(
),
],
),
],
);
| flutter/packages/flutter/lib/src/material/animated_icons/data/pause_play.g.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/material/animated_icons/data/pause_play.g.dart', 'repo_id': 'flutter', 'token_count': 22612} |
// Copyright 2014 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 'material.dart';
import 'text_selection_toolbar.dart';
// These values were measured from a screenshot of TextEdit on macOS 10.15.7 on
// a Macbook Pro.
const double _kToolbarScreenPadding = 8.0;
const double _kToolbarWidth = 222.0;
/// A Material-style desktop text selection toolbar.
///
/// Typically displays buttons for text manipulation, e.g. copying and pasting
/// text.
///
/// Tries to position its top left corner as closely as possible to [anchor]
/// while remaining fully inside the viewport.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar], which builds the toolbar for the current
/// platform.
/// * [TextSelectionToolbar], which is similar, but builds an Android-style
/// toolbar.
class DesktopTextSelectionToolbar extends StatelessWidget {
/// Creates a const instance of DesktopTextSelectionToolbar.
const DesktopTextSelectionToolbar({
super.key,
required this.anchor,
required this.children,
}) : assert(children.length > 0);
/// {@template flutter.material.DesktopTextSelectionToolbar.anchor}
/// The point where the toolbar will attempt to position itself as closely as
/// possible.
/// {@endtemplate}
final Offset anchor;
/// {@macro flutter.material.TextSelectionToolbar.children}
///
/// See also:
/// * [DesktopTextSelectionToolbarButton], which builds a default
/// Material-style desktop text selection toolbar text button.
final List<Widget> children;
// Builds a desktop toolbar in the Material style.
static Widget _defaultToolbarBuilder(BuildContext context, Widget child) {
return SizedBox(
width: _kToolbarWidth,
child: Material(
borderRadius: const BorderRadius.all(Radius.circular(7.0)),
clipBehavior: Clip.antiAlias,
elevation: 1.0,
type: MaterialType.card,
child: child,
),
);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
final double paddingAbove = MediaQuery.paddingOf(context).top + _kToolbarScreenPadding;
final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove);
return Padding(
padding: EdgeInsets.fromLTRB(
_kToolbarScreenPadding,
paddingAbove,
_kToolbarScreenPadding,
_kToolbarScreenPadding,
),
child: CustomSingleChildLayout(
delegate: DesktopTextSelectionToolbarLayoutDelegate(
anchor: anchor - localAdjustment,
),
child: _defaultToolbarBuilder(
context,
Column(
mainAxisSize: MainAxisSize.min,
children: children,
),
),
),
);
}
}
| flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar.dart', 'repo_id': 'flutter', 'token_count': 990} |
// Copyright 2014 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:ui' show TextDirection;
export 'dart:ui' show
BlendMode,
BlurStyle,
Canvas,
Clip,
Color,
ColorFilter,
FilterQuality,
FontStyle,
FontWeight,
ImageShader,
Locale,
MaskFilter,
Offset,
Paint,
PaintingStyle,
Path,
PathFillType,
PathOperation,
RRect,
RSTransform,
Radius,
Rect,
Shader,
Size,
StrokeCap,
StrokeJoin,
TextAffinity,
TextAlign,
TextBaseline,
TextBox,
TextDecoration,
TextDecorationStyle,
TextDirection,
TextPosition,
TileMode,
VertexMode,
// TODO(werainkhatri): remove these after their deprecation period in engine
// https://github.com/flutter/flutter/pull/99505
hashList, // ignore: deprecated_member_use
hashValues; // ignore: deprecated_member_use
export 'package:flutter/foundation.dart' show VoidCallback;
// Intentionally not exported:
// - Image, instantiateImageCodec, decodeImageFromList:
// We use ui.* to make it very explicit that these are low-level image APIs.
// Generally, higher layers provide more reasonable APIs around images.
// - lerpDouble:
// Hopefully this will eventually become Double.lerp.
// - Paragraph, ParagraphBuilder, ParagraphStyle, TextBox:
// These are low-level text primitives. Use this package's TextPainter API.
// - Picture, PictureRecorder, Scene, SceneBuilder:
// These are low-level primitives. Generally, the rendering layer makes these moot.
// - Gradient:
// Use this package's higher-level Gradient API instead.
// - window, WindowPadding
// These are generally wrapped by other APIs so we always refer to them directly
// as ui.* to avoid making them seem like high-level APIs.
/// The description of the difference between two objects, in the context of how
/// it will affect the rendering.
///
/// Used by [TextSpan.compareTo] and [TextStyle.compareTo].
///
/// The values in this enum are ordered such that they are in increasing order
/// of cost. A value with index N implies all the values with index less than N.
/// For example, [layout] (index 3) implies [paint] (2).
enum RenderComparison {
/// The two objects are identical (meaning deeply equal, not necessarily
/// [dart:core.identical]).
identical,
/// The two objects are identical for the purpose of layout, but may be different
/// in other ways.
///
/// For example, maybe some event handlers changed.
metadata,
/// The two objects are different but only in ways that affect paint, not layout.
///
/// For example, only the color is changed.
///
/// [RenderObject.markNeedsPaint] would be necessary to handle this kind of
/// change in a render object.
paint,
/// The two objects are different in ways that affect layout (and therefore paint).
///
/// For example, the size is changed.
///
/// This is the most drastic level of change possible.
///
/// [RenderObject.markNeedsLayout] would be necessary to handle this kind of
/// change in a render object.
layout,
}
/// The two cardinal directions in two dimensions.
///
/// The axis is always relative to the current coordinate space. This means, for
/// example, that a [horizontal] axis might actually be diagonally from top
/// right to bottom left, due to some local [Transform] applied to the scene.
///
/// See also:
///
/// * [AxisDirection], which is a directional version of this enum (with values
/// light left and right, rather than just horizontal).
/// * [TextDirection], which disambiguates between left-to-right horizontal
/// content and right-to-left horizontal content.
enum Axis {
/// Left and right.
///
/// See also:
///
/// * [TextDirection], which disambiguates between left-to-right horizontal
/// content and right-to-left horizontal content.
horizontal,
/// Up and down.
vertical,
}
/// Returns the opposite of the given [Axis].
///
/// Specifically, returns [Axis.horizontal] for [Axis.vertical], and
/// vice versa.
///
/// See also:
///
/// * [flipAxisDirection], which does the same thing for [AxisDirection] values.
Axis flipAxis(Axis direction) {
switch (direction) {
case Axis.horizontal:
return Axis.vertical;
case Axis.vertical:
return Axis.horizontal;
}
}
/// A direction in which boxes flow vertically.
///
/// This is used by the flex algorithm (e.g. [Column]) to decide in which
/// direction to draw boxes.
///
/// This is also used to disambiguate `start` and `end` values (e.g.
/// [MainAxisAlignment.start] or [CrossAxisAlignment.end]).
///
/// See also:
///
/// * [TextDirection], which controls the same thing but horizontally.
enum VerticalDirection {
/// Boxes should start at the bottom and be stacked vertically towards the top.
///
/// The "start" is at the bottom, the "end" is at the top.
up,
/// Boxes should start at the top and be stacked vertically towards the bottom.
///
/// The "start" is at the top, the "end" is at the bottom.
down,
}
/// A direction along either the horizontal or vertical [Axis].
enum AxisDirection {
/// Zero is at the bottom and positive values are above it: `⇈`
///
/// Alphabetical content with a [GrowthDirection.forward] would have the A at
/// the bottom and the Z at the top. This is an unusual configuration.
up,
/// Zero is on the left and positive values are to the right of it: `⇉`
///
/// Alphabetical content with a [GrowthDirection.forward] would have the A on
/// the left and the Z on the right. This is the ordinary reading order for a
/// horizontal set of tabs in an English application, for example.
right,
/// Zero is at the top and positive values are below it: `⇊`
///
/// Alphabetical content with a [GrowthDirection.forward] would have the A at
/// the top and the Z at the bottom. This is the ordinary reading order for a
/// vertical list.
down,
/// Zero is to the right and positive values are to the left of it: `⇇`
///
/// Alphabetical content with a [GrowthDirection.forward] would have the A at
/// the right and the Z at the left. This is the ordinary reading order for a
/// horizontal set of tabs in a Hebrew application, for example.
left,
}
/// Returns the [Axis] that contains the given [AxisDirection].
///
/// Specifically, returns [Axis.vertical] for [AxisDirection.up] and
/// [AxisDirection.down] and returns [Axis.horizontal] for [AxisDirection.left]
/// and [AxisDirection.right].
Axis axisDirectionToAxis(AxisDirection axisDirection) {
switch (axisDirection) {
case AxisDirection.up:
case AxisDirection.down:
return Axis.vertical;
case AxisDirection.left:
case AxisDirection.right:
return Axis.horizontal;
}
}
/// Returns the [AxisDirection] in which reading occurs in the given [TextDirection].
///
/// Specifically, returns [AxisDirection.left] for [TextDirection.rtl] and
/// [AxisDirection.right] for [TextDirection.ltr].
AxisDirection textDirectionToAxisDirection(TextDirection textDirection) {
switch (textDirection) {
case TextDirection.rtl:
return AxisDirection.left;
case TextDirection.ltr:
return AxisDirection.right;
}
}
/// Returns the opposite of the given [AxisDirection].
///
/// Specifically, returns [AxisDirection.up] for [AxisDirection.down] (and
/// vice versa), as well as [AxisDirection.left] for [AxisDirection.right] (and
/// vice versa).
///
/// See also:
///
/// * [flipAxis], which does the same thing for [Axis] values.
AxisDirection flipAxisDirection(AxisDirection axisDirection) {
switch (axisDirection) {
case AxisDirection.up:
return AxisDirection.down;
case AxisDirection.right:
return AxisDirection.left;
case AxisDirection.down:
return AxisDirection.up;
case AxisDirection.left:
return AxisDirection.right;
}
}
/// Returns whether traveling along the given axis direction visits coordinates
/// along that axis in numerically decreasing order.
///
/// Specifically, returns true for [AxisDirection.up] and [AxisDirection.left]
/// and false for [AxisDirection.down] and [AxisDirection.right].
bool axisDirectionIsReversed(AxisDirection axisDirection) {
switch (axisDirection) {
case AxisDirection.up:
case AxisDirection.left:
return true;
case AxisDirection.down:
case AxisDirection.right:
return false;
}
}
| flutter/packages/flutter/lib/src/painting/basic_types.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/painting/basic_types.dart', 'repo_id': 'flutter', 'token_count': 2596} |
// Copyright 2014 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.
/// Whether two doubles are within a given distance of each other.
///
/// The `epsilon` argument must be positive and not null.
/// The `a` and `b` arguments may be null. A null value is only considered
/// near-equal to another null value.
bool nearEqual(double? a, double? b, double epsilon) {
assert(epsilon >= 0.0);
if (a == null || b == null) {
return a == b;
}
return (a > (b - epsilon)) && (a < (b + epsilon)) || a == b;
}
/// Whether a double is within a given distance of zero.
///
/// The epsilon argument must be positive.
bool nearZero(double a, double epsilon) => nearEqual(a, 0.0, epsilon);
| flutter/packages/flutter/lib/src/physics/utils.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/physics/utils.dart', 'repo_id': 'flutter', 'token_count': 248} |
// Copyright 2014 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.
/// Service extension constants for the scheduler library.
///
/// These constants will be used when registering service extensions in the
/// framework, and they will also be used by tools and services that call these
/// service extensions.
///
/// The String value for each of these extension names should be accessed by
/// calling the `.name` property on the enum value.
enum SchedulerServiceExtensions {
/// Name of service extension that, when called, will change the value of
/// [timeDilation], which determines the factor by which to slow down
/// animations for help in development.
///
/// See also:
///
/// * [timeDilation], which is the field that this service extension exposes.
/// * [SchedulerBinding.initServiceExtensions], where the service extension is
/// registered.
timeDilation,
}
| flutter/packages/flutter/lib/src/scheduler/service_extensions.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/scheduler/service_extensions.dart', 'repo_id': 'flutter', 'token_count': 239} |
// Copyright 2014 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 'hardware_keyboard.dart';
export 'hardware_keyboard.dart' show KeyDataTransitMode;
/// Override the transit mode with which key events are simulated.
///
/// Setting [debugKeyEventSimulatorTransitModeOverride] is a good way to make
/// certain tests simulate the behavior of different type of platforms in terms
/// of their extent of support for keyboard API.
KeyDataTransitMode? debugKeyEventSimulatorTransitModeOverride;
/// Profile and print statistics on Platform Channel usage.
///
/// When this is true statistics about the usage of Platform Channels will be
/// printed out periodically to the console and Timeline events will show the
/// time between sending and receiving a message (encoding and decoding time
/// excluded).
///
/// The statistics include the total bytes transmitted and the average number of
/// bytes per invocation in the last quantum. "Up" means in the direction of
/// Flutter to the host platform, "down" is the host platform to flutter.
bool debugProfilePlatformChannels = false;
/// Returns true if none of the widget library debug variables have been changed.
///
/// This function is used by the test framework to ensure that debug variables
/// haven't been inadvertently changed.
///
/// See [the services library](services/services-library.html) for a complete list.
bool debugAssertAllServicesVarsUnset(String reason) {
assert(() {
if (debugKeyEventSimulatorTransitModeOverride != null) {
throw FlutterError(reason);
}
if (debugProfilePlatformChannels) {
throw FlutterError(reason);
}
return true;
}());
return true;
}
| flutter/packages/flutter/lib/src/services/debug.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/services/debug.dart', 'repo_id': 'flutter', 'token_count': 467} |
// Copyright 2014 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 'basic.dart';
import 'framework.dart';
import 'icon_theme_data.dart';
import 'inherited_theme.dart';
// Examples can assume:
// late BuildContext context;
/// Controls the default properties of icons in a widget subtree.
///
/// The icon theme is honored by [Icon] and [ImageIcon] widgets.
class IconTheme extends InheritedTheme {
/// Creates an icon theme that controls properties of descendant widgets.
///
/// Both [data] and [child] arguments must not be null.
const IconTheme({
super.key,
required this.data,
required super.child,
});
/// Creates an icon theme that controls the properties of
/// descendant widgets, and merges in the current icon theme, if any.
///
/// The [data] and [child] arguments must not be null.
static Widget merge({
Key? key,
required IconThemeData data,
required Widget child,
}) {
return Builder(
builder: (BuildContext context) {
return IconTheme(
key: key,
data: _getInheritedIconThemeData(context).merge(data),
child: child,
);
},
);
}
/// The set of properties to use for icons in this subtree.
final IconThemeData data;
/// The data from the closest instance of this class that encloses the given
/// context, if any.
///
/// If there is no ambient icon theme, defaults to [IconThemeData.fallback].
/// The returned [IconThemeData] is concrete (all values are non-null; see
/// [IconThemeData.isConcrete]). Any properties on the ambient icon theme that
/// are null get defaulted to the values specified on
/// [IconThemeData.fallback].
///
/// The [Theme] widget from the `material` library introduces an [IconTheme]
/// widget set to the [ThemeData.iconTheme], so in a Material Design
/// application, this will typically default to the icon theme from the
/// ambient [Theme].
///
/// Typical usage is as follows:
///
/// ```dart
/// IconThemeData theme = IconTheme.of(context);
/// ```
static IconThemeData of(BuildContext context) {
final IconThemeData iconThemeData = _getInheritedIconThemeData(context).resolve(context);
return iconThemeData.isConcrete
? iconThemeData
: iconThemeData.copyWith(
size: iconThemeData.size ?? const IconThemeData.fallback().size,
fill: iconThemeData.fill ?? const IconThemeData.fallback().fill,
weight: iconThemeData.weight ?? const IconThemeData.fallback().weight,
grade: iconThemeData.grade ?? const IconThemeData.fallback().grade,
opticalSize: iconThemeData.opticalSize ?? const IconThemeData.fallback().opticalSize,
color: iconThemeData.color ?? const IconThemeData.fallback().color,
opacity: iconThemeData.opacity ?? const IconThemeData.fallback().opacity,
shadows: iconThemeData.shadows ?? const IconThemeData.fallback().shadows,
);
}
static IconThemeData _getInheritedIconThemeData(BuildContext context) {
final IconTheme? iconTheme = context.dependOnInheritedWidgetOfExactType<IconTheme>();
return iconTheme?.data ?? const IconThemeData.fallback();
}
@override
bool updateShouldNotify(IconTheme oldWidget) => data != oldWidget.data;
@override
Widget wrap(BuildContext context, Widget child) {
return IconTheme(data: data, child: child);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
data.debugFillProperties(properties);
}
}
| flutter/packages/flutter/lib/src/widgets/icon_theme.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/widgets/icon_theme.dart', 'repo_id': 'flutter', 'token_count': 1162} |
// Copyright 2014 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 'framework.dart';
import 'navigator.dart';
import 'routes.dart';
/// Registers a callback to veto attempts by the user to dismiss the enclosing
/// [ModalRoute].
///
/// {@tool dartpad}
/// Whenever the back button is pressed, you will get a callback at [onWillPop],
/// which returns a [Future]. If the [Future] returns true, the screen is
/// popped.
///
/// ** See code in examples/api/lib/widgets/will_pop_scope/will_pop_scope.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ModalRoute.addScopedWillPopCallback] and [ModalRoute.removeScopedWillPopCallback],
/// which this widget uses to register and unregister [onWillPop].
/// * [Form], which provides an `onWillPop` callback that enables the form
/// to veto a `pop` initiated by the app's back button.
///
class WillPopScope extends StatefulWidget {
/// Creates a widget that registers a callback to veto attempts by the user to
/// dismiss the enclosing [ModalRoute].
///
/// The [child] argument must not be null.
const WillPopScope({
super.key,
required this.child,
required this.onWillPop,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// Called to veto attempts by the user to dismiss the enclosing [ModalRoute].
///
/// If the callback returns a Future that resolves to false, the enclosing
/// route will not be popped.
final WillPopCallback? onWillPop;
@override
State<WillPopScope> createState() => _WillPopScopeState();
}
class _WillPopScopeState extends State<WillPopScope> {
ModalRoute<dynamic>? _route;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (widget.onWillPop != null) {
_route?.removeScopedWillPopCallback(widget.onWillPop!);
}
_route = ModalRoute.of(context);
if (widget.onWillPop != null) {
_route?.addScopedWillPopCallback(widget.onWillPop!);
}
}
@override
void didUpdateWidget(WillPopScope oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.onWillPop != oldWidget.onWillPop && _route != null) {
if (oldWidget.onWillPop != null) {
_route!.removeScopedWillPopCallback(oldWidget.onWillPop!);
}
if (widget.onWillPop != null) {
_route!.addScopedWillPopCallback(widget.onWillPop!);
}
}
}
@override
void dispose() {
if (widget.onWillPop != null) {
_route?.removeScopedWillPopCallback(widget.onWillPop!);
}
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
| flutter/packages/flutter/lib/src/widgets/will_pop_scope.dart/0 | {'file_path': 'flutter/packages/flutter/lib/src/widgets/will_pop_scope.dart', 'repo_id': 'flutter', 'token_count': 922} |
// Copyright 2014 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';
void main() {
test('CupertinoTextTheme matches Apple Design resources', () {
// Check the default cupertino text theme against the style values
// Values derived from https://developer.apple.com/design/resources/.
const CupertinoTextThemeData theme = CupertinoTextThemeData();
const FontWeight normal = FontWeight.normal;
const FontWeight regular = FontWeight.w400;
const FontWeight medium = FontWeight.w500;
const FontWeight semiBold = FontWeight.w600;
const FontWeight bold = FontWeight.w700;
// TextStyle 17 -0.41
expect(theme.textStyle.fontSize, 17);
expect(theme.textStyle.fontFamily, '.SF Pro Text');
expect(theme.textStyle.letterSpacing, -0.41);
expect(theme.textStyle.fontWeight, null);
// ActionTextStyle 17 -0.41
expect(theme.actionTextStyle.fontSize, 17);
expect(theme.actionTextStyle.fontFamily, '.SF Pro Text');
expect(theme.actionTextStyle.letterSpacing, -0.41);
expect(theme.actionTextStyle.fontWeight, null);
// TextStyle 17 -0.41
expect(theme.tabLabelTextStyle.fontSize, 10);
expect(theme.tabLabelTextStyle.fontFamily, '.SF Pro Text');
expect(theme.tabLabelTextStyle.letterSpacing, -0.24);
expect(theme.tabLabelTextStyle.fontWeight, medium);
// NavTitle SemiBold 17 -0.41
expect(theme.navTitleTextStyle.fontSize, 17);
expect(theme.navTitleTextStyle.fontFamily, '.SF Pro Text');
expect(theme.navTitleTextStyle.letterSpacing, -0.41);
expect(theme.navTitleTextStyle.fontWeight, semiBold);
// NavLargeTitle Bold 34 0.41
expect(theme.navLargeTitleTextStyle.fontSize, 34);
expect(theme.navLargeTitleTextStyle.fontFamily, '.SF Pro Display');
expect(theme.navLargeTitleTextStyle.letterSpacing, 0.41);
expect(theme.navLargeTitleTextStyle.fontWeight, bold);
// Picker Regular 21 -0.6
expect(theme.pickerTextStyle.fontSize, 21);
expect(theme.pickerTextStyle.fontFamily, '.SF Pro Display');
expect(theme.pickerTextStyle.letterSpacing, -0.6);
expect(theme.pickerTextStyle.fontWeight, regular);
// DateTimePicker Normal 21
expect(theme.dateTimePickerTextStyle.fontSize, 21);
expect(theme.dateTimePickerTextStyle.fontFamily, '.SF Pro Display');
expect(theme.dateTimePickerTextStyle.letterSpacing, null);
expect(theme.dateTimePickerTextStyle.fontWeight, normal);
});
}
| flutter/packages/flutter/test/cupertino/text_theme_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/cupertino/text_theme_test.dart', 'repo_id': 'flutter', 'token_count': 876} |
// Copyright 2014 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:fake_async/fake_async.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'capture_output.dart';
void main() {
test('debugPrint', () {
expect(
captureOutput(() { debugPrintSynchronously('Hello, world'); }),
equals(<String>['Hello, world']),
);
expect(
captureOutput(() { debugPrintSynchronously('Hello, world', wrapWidth: 10); }),
equals(<String>['Hello,\nworld']),
);
for (int i = 0; i < 14; ++i) {
expect(
captureOutput(() { debugPrintSynchronously('Hello, world', wrapWidth: i); }),
equals(<String>['Hello,\nworld']),
);
}
expect(
captureOutput(() { debugPrintThrottled('Hello, world'); }),
equals(<String>['Hello, world']),
);
expect(
captureOutput(() { debugPrintThrottled('Hello, world', wrapWidth: 10); }),
equals(<String>['Hello,', 'world']),
);
});
test('debugPrint throttling', () {
FakeAsync().run((FakeAsync async) {
List<String> log = captureOutput(() {
debugPrintThrottled('${'A' * (22 * 1024)}\nB');
});
expect(log.length, 1);
async.elapse(const Duration(seconds: 2));
expect(log.length, 2);
log = captureOutput(() {
debugPrintThrottled('C' * (22 * 1024));
debugPrintThrottled('D');
});
expect(log.length, 1);
async.elapse(const Duration(seconds: 2));
expect(log.length, 2);
});
});
test('debugPrint can print null', () {
expect(
captureOutput(() { debugPrintThrottled(null); }),
equals(<String>['null']),
);
expect(
captureOutput(() { debugPrintThrottled(null, wrapWidth: 80); }),
equals(<String>['null']),
);
});
}
| flutter/packages/flutter/test/foundation/print_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/foundation/print_test.dart', 'repo_id': 'flutter', 'token_count': 789} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets("builder doesn't get called if app doesn't change", (WidgetTester tester) async {
final List<String> log = <String>[];
final Widget app = MaterialApp(
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const Placeholder(),
builder: (BuildContext context, Widget? child) {
log.add('build');
expect(Theme.of(context).primaryColor, Colors.green);
expect(Directionality.of(context), TextDirection.ltr);
expect(child, isA<FocusScope>());
return const Placeholder();
},
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: app,
),
);
expect(log, <String>['build']);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: app,
),
);
expect(log, <String>['build']);
});
testWidgets("builder doesn't get called if app doesn't change", (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primarySwatch: Colors.yellow,
),
home: Builder(
builder: (BuildContext context) {
log.add('build');
expect(Theme.of(context).primaryColor, Colors.yellow);
expect(Directionality.of(context), TextDirection.rtl);
return const Placeholder();
},
),
builder: (BuildContext context, Widget? child) {
return Directionality(
textDirection: TextDirection.rtl,
child: child!,
);
},
),
);
expect(log, <String>['build']);
});
}
| flutter/packages/flutter/test/material/app_builder_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/material/app_builder_test.dart', 'repo_id': 'flutter', 'token_count': 835} |
// Copyright 2014 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/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'scheduler_tester.dart';
class TestSchedulerBinding extends BindingBase with SchedulerBinding, ServicesBinding { }
void main() {
final SchedulerBinding scheduler = TestSchedulerBinding();
test('Check for a time dilation being in effect', () {
expect(timeDilation, equals(1.0));
});
test('Can cancel queued callback', () {
late int secondId;
bool firstCallbackRan = false;
bool secondCallbackRan = false;
void firstCallback(Duration timeStamp) {
expect(firstCallbackRan, isFalse);
expect(secondCallbackRan, isFalse);
expect(timeStamp.inMilliseconds, equals(0));
firstCallbackRan = true;
scheduler.cancelFrameCallbackWithId(secondId);
}
void secondCallback(Duration timeStamp) {
expect(firstCallbackRan, isTrue);
expect(secondCallbackRan, isFalse);
expect(timeStamp.inMilliseconds, equals(0));
secondCallbackRan = true;
}
scheduler.scheduleFrameCallback(firstCallback);
secondId = scheduler.scheduleFrameCallback(secondCallback);
tick(const Duration(milliseconds: 16));
expect(firstCallbackRan, isTrue);
expect(secondCallbackRan, isFalse);
firstCallbackRan = false;
secondCallbackRan = false;
tick(const Duration(milliseconds: 32));
expect(firstCallbackRan, isFalse);
expect(secondCallbackRan, isFalse);
});
}
| flutter/packages/flutter/test/scheduler/animation_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/scheduler/animation_test.dart', 'repo_id': 'flutter', 'token_count': 576} |
// Copyright 2014 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 files contains message codec tests that are supported both on the Web
// and in the VM. For VM-only tests see message_codecs_vm_test.dart.
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'message_codecs_testing.dart';
void main() {
group('Binary codec', () {
const MessageCodec<ByteData?> binary = BinaryCodec();
test('should encode and decode simple messages', () {
checkEncodeDecode<ByteData?>(binary, null);
checkEncodeDecode<ByteData?>(binary, ByteData(0));
checkEncodeDecode<ByteData?>(binary, ByteData(4)..setInt32(0, -7));
});
});
group('String codec', () {
const MessageCodec<String?> string = StringCodec();
test('should encode and decode simple messages', () {
checkEncodeDecode<String?>(string, null);
checkEncodeDecode<String?>(string, '');
checkEncodeDecode<String?>(string, 'hello');
checkEncodeDecode<String?>(string, 'special chars >\u263A\u{1F602}<');
});
test('ByteData with offset', () {
const MessageCodec<String?> string = StringCodec();
final ByteData helloWorldByteData = string.encodeMessage('hello world')!;
final ByteData helloByteData = string.encodeMessage('hello')!;
final ByteData offsetByteData = ByteData.view(
helloWorldByteData.buffer,
helloByteData.lengthInBytes,
helloWorldByteData.lengthInBytes - helloByteData.lengthInBytes,
);
expect(string.decodeMessage(offsetByteData), ' world');
});
});
group('Standard method codec', () {
const MethodCodec method = StandardMethodCodec();
const StandardMessageCodec messageCodec = StandardMessageCodec();
test('Should encode and decode objects produced from codec', () {
final ByteData? data = messageCodec.encodeMessage(<Object, Object>{
'foo': true,
3: 'fizz',
});
expect(messageCodec.decodeMessage(data), <Object?, Object?>{
'foo': true,
3: 'fizz',
});
});
test('should decode error envelope without native stacktrace', () {
final ByteData errorData = method.encodeErrorEnvelope(
code: 'errorCode',
message: 'errorMessage',
details: 'errorDetails',
);
expect(
() => method.decodeEnvelope(errorData),
throwsA(predicate(
(PlatformException e) =>
e.code == 'errorCode' &&
e.message == 'errorMessage' &&
e.details == 'errorDetails',
)),
);
});
test('should decode error envelope with native stacktrace.', () {
final WriteBuffer buffer = WriteBuffer();
buffer.putUint8(1);
messageCodec.writeValue(buffer, 'errorCode');
messageCodec.writeValue(buffer, 'errorMessage');
messageCodec.writeValue(buffer, 'errorDetails');
messageCodec.writeValue(buffer, 'errorStacktrace');
final ByteData errorData = buffer.done();
expect(
() => method.decodeEnvelope(errorData),
throwsA(predicate((PlatformException e) => e.stacktrace == 'errorStacktrace')),
);
});
test('should allow null error message,', () {
final ByteData errorData = method.encodeErrorEnvelope(
code: 'errorCode',
details: 'errorDetails',
);
expect(
() => method.decodeEnvelope(errorData),
throwsA(
predicate((PlatformException e) {
return e.code == 'errorCode' &&
e.message == null &&
e.details == 'errorDetails';
}),
),
);
});
});
group('Json method codec', () {
const JsonCodec json = JsonCodec();
const StringCodec stringCodec = StringCodec();
const JSONMethodCodec jsonMethodCodec = JSONMethodCodec();
test('should decode error envelope without native stacktrace', () {
final ByteData errorData = jsonMethodCodec.encodeErrorEnvelope(
code: 'errorCode',
message: 'errorMessage',
details: 'errorDetails',
);
expect(
() => jsonMethodCodec.decodeEnvelope(errorData),
throwsA(predicate(
(PlatformException e) =>
e.code == 'errorCode' &&
e.message == 'errorMessage' &&
e.details == 'errorDetails',
)),
);
});
test('should decode error envelope with native stacktrace.', () {
final ByteData? errorData = stringCodec.encodeMessage(json.encode(<dynamic>[
'errorCode',
'errorMessage',
'errorDetails',
'errorStacktrace',
]));
expect(
() => jsonMethodCodec.decodeEnvelope(errorData!),
throwsA(predicate((PlatformException e) => e.stacktrace == 'errorStacktrace')),
);
});
});
group('JSON message codec', () {
const MessageCodec<dynamic> json = JSONMessageCodec();
test('should encode and decode simple messages', () {
checkEncodeDecode<dynamic>(json, null);
checkEncodeDecode<dynamic>(json, true);
checkEncodeDecode<dynamic>(json, false);
checkEncodeDecode<dynamic>(json, 7);
checkEncodeDecode<dynamic>(json, -7);
checkEncodeDecode<dynamic>(json, 98742923489);
checkEncodeDecode<dynamic>(json, -98742923489);
checkEncodeDecode<dynamic>(json, 3.14);
checkEncodeDecode<dynamic>(json, '');
checkEncodeDecode<dynamic>(json, 'hello');
checkEncodeDecode<dynamic>(json, 'special chars >\u263A\u{1F602}<');
});
test('should encode and decode composite message', () {
final List<dynamic> message = <dynamic>[
null,
true,
false,
-707,
-7000000007,
-3.14,
'',
'hello',
<dynamic>['nested', <dynamic>[]],
<dynamic, dynamic>{'a': 'nested', 'b': <dynamic, dynamic>{}},
'world',
];
checkEncodeDecode<dynamic>(json, message);
});
});
group('Standard message codec', () {
const MessageCodec<dynamic> standard = StandardMessageCodec();
test('should encode sizes correctly at boundary cases', () {
checkEncoding<dynamic>(
standard,
Uint8List(253),
<int>[8, 253, ...List<int>.filled(253, 0)],
);
checkEncoding<dynamic>(
standard,
Uint8List(254),
<int>[8, 254, 254, 0, ...List<int>.filled(254, 0)],
);
checkEncoding<dynamic>(
standard,
Uint8List(0xffff),
<int>[8, 254, 0xff, 0xff, ...List<int>.filled(0xffff, 0)],
);
checkEncoding<dynamic>(
standard,
Uint8List(0xffff + 1),
<int>[8, 255, 0, 0, 1, 0, ...List<int>.filled(0xffff + 1, 0)],
);
});
test('should encode and decode simple messages', () {
checkEncodeDecode<dynamic>(standard, null);
checkEncodeDecode<dynamic>(standard, true);
checkEncodeDecode<dynamic>(standard, false);
checkEncodeDecode<dynamic>(standard, 7);
checkEncodeDecode<dynamic>(standard, -7);
checkEncodeDecode<dynamic>(standard, 98742923489);
checkEncodeDecode<dynamic>(standard, -98742923489);
checkEncodeDecode<dynamic>(standard, 3.14);
checkEncodeDecode<dynamic>(standard, double.infinity);
checkEncodeDecode<dynamic>(standard, double.nan);
checkEncodeDecode<dynamic>(standard, '');
checkEncodeDecode<dynamic>(standard, 'hello');
checkEncodeDecode<dynamic>(standard, 'special chars >\u263A\u{1F602}<');
});
test('should encode and decode composite message', () {
final List<dynamic> message = <dynamic>[
null,
true,
false,
-707,
-7000000007,
-3.14,
'',
'hello',
Uint8List.fromList(<int>[0xBA, 0x5E, 0xBA, 0x11]),
Int32List.fromList(<int>[-0x7fffffff - 1, 0, 0x7fffffff]),
null, // ensures the offset of the following list is unaligned.
null, // ensures the offset of the following list is unaligned.
Float64List.fromList(<double>[
double.negativeInfinity,
-double.maxFinite,
-double.minPositive,
-0.0,
0.0,
double.minPositive,
double.maxFinite,
double.infinity,
double.nan,
]),
Float32List.fromList(<double>[
double.negativeInfinity,
-double.maxFinite,
-double.minPositive,
-0.0,
0.0,
double.minPositive,
double.maxFinite,
double.infinity,
double.nan,
]),
<dynamic>['nested', <dynamic>[]],
<dynamic, dynamic>{'a': 'nested', null: <dynamic, dynamic>{}},
'world',
];
checkEncodeDecode<dynamic>(standard, message);
});
test('should align doubles to 8 bytes', () {
checkEncoding<dynamic>(
standard,
1.0,
<int>[
6,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0xf0,
0x3f,
],
);
});
});
test('toString works as intended', () async {
const MethodCall methodCall = MethodCall('sample method');
final PlatformException platformException = PlatformException(code: '100');
final MissingPluginException missingPluginException = MissingPluginException();
expect(methodCall.toString(), 'MethodCall(sample method, null)');
expect(platformException.toString(), 'PlatformException(100, null, null, null)');
expect(missingPluginException.toString(), 'MissingPluginException(null)');
});
}
| flutter/packages/flutter/test/services/message_codecs_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/services/message_codecs_test.dart', 'repo_id': 'flutter', 'token_count': 4217} |
// Copyright 2014 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';
class Inside extends StatefulWidget {
const Inside({ super.key });
@override
InsideState createState() => InsideState();
}
class InsideState extends State<Inside> {
@override
Widget build(BuildContext context) {
return Listener(
onPointerDown: _handlePointerDown,
child: const Text('INSIDE', textDirection: TextDirection.ltr),
);
}
void _handlePointerDown(PointerDownEvent event) {
setState(() { });
}
}
class Middle extends StatefulWidget {
const Middle({
super.key,
this.child,
});
final Inside? child;
@override
MiddleState createState() => MiddleState();
}
class MiddleState extends State<Middle> {
@override
Widget build(BuildContext context) {
return Listener(
onPointerDown: _handlePointerDown,
child: widget.child,
);
}
void _handlePointerDown(PointerDownEvent event) {
setState(() { });
}
}
class Outside extends StatefulWidget {
const Outside({ super.key });
@override
OutsideState createState() => OutsideState();
}
class OutsideState extends State<Outside> {
@override
Widget build(BuildContext context) {
return const Middle(child: Inside());
}
}
void main() {
testWidgets('setState() smoke test', (WidgetTester tester) async {
await tester.pumpWidget(const Outside());
final Offset location = tester.getCenter(find.text('INSIDE'));
final TestGesture gesture = await tester.startGesture(location);
await tester.pump();
await gesture.up();
await tester.pump();
});
}
| flutter/packages/flutter/test/widgets/set_state_1_test.dart/0 | {'file_path': 'flutter/packages/flutter/test/widgets/set_state_1_test.dart', 'repo_id': 'flutter', 'token_count': 591} |
// Copyright 2014 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:js';
import 'dart:js_util' as js_util;
/// The dart:html implementation of [registerWebServiceExtension].
///
/// Registers Web Service Extension for Flutter Web application.
///
/// window.$flutterDriver will be called by Flutter Web Driver to process
/// Flutter Command.
///
/// See also:
///
/// * [_extension_io.dart], which has the dart:io implementation
void registerWebServiceExtension(Future<Map<String, dynamic>> Function(Map<String, String>) call) {
// Define the result variable because packages/flutter_driver/lib/src/driver/web_driver.dart
// checks for this value to become non-null when waiting for the result. If this value is
// undefined at the time of the check, WebDriver throws an exception.
context[r'$flutterDriverResult'] = null;
js_util.setProperty(html.window, r'$flutterDriver', allowInterop((dynamic message) async {
final Map<String, String> params = Map<String, String>.from(
jsonDecode(message as String) as Map<String, dynamic>);
final Map<String, dynamic> result = Map<String, dynamic>.from(
await call(params));
context[r'$flutterDriverResult'] = json.encode(result);
}));
}
| flutter/packages/flutter_driver/lib/src/extension/_extension_web.dart/0 | {'file_path': 'flutter/packages/flutter_driver/lib/src/extension/_extension_web.dart', 'repo_id': 'flutter', 'token_count': 417} |
// Copyright 2014 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_driver/src/driver/timeline.dart';
import '../../common.dart';
void main() {
group('Timeline', () {
test('parses JSON', () {
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
'traceEvents': <Map<String, dynamic>>[
<String, dynamic>{
'name': 'test event',
'cat': 'test category',
'ph': 'B',
'pid': 123,
'tid': 234,
'dur': 345,
'tdur': 245,
'ts': 456,
'tts': 567,
'args': <String, dynamic>{
'arg1': true,
},
},
// Tests that we don't choke on missing data
<String, dynamic>{},
],
});
expect(timeline.events, hasLength(2));
final TimelineEvent e1 = timeline.events![1];
expect(e1.name, 'test event');
expect(e1.category, 'test category');
expect(e1.phase, 'B');
expect(e1.processId, 123);
expect(e1.threadId, 234);
expect(e1.duration, const Duration(microseconds: 345));
expect(e1.threadDuration, const Duration(microseconds: 245));
expect(e1.timestampMicros, 456);
expect(e1.threadTimestampMicros, 567);
expect(e1.arguments, <String, dynamic>{'arg1': true});
final TimelineEvent e2 = timeline.events![0];
expect(e2.name, isNull);
expect(e2.category, isNull);
expect(e2.phase, isNull);
expect(e2.processId, isNull);
expect(e2.threadId, isNull);
expect(e2.duration, isNull);
expect(e2.threadDuration, isNull);
expect(e2.timestampMicros, isNull);
expect(e2.threadTimestampMicros, isNull);
expect(e2.arguments, isNull);
});
test('sorts JSON', () {
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
'traceEvents': <Map<String, dynamic>>[
<String, dynamic>{
'name': 'test event 1',
'ts': 457,
},
<String, dynamic>{
'name': 'test event 2',
'ts': 456,
},
],
});
expect(timeline.events, hasLength(2));
expect(timeline.events![0].timestampMicros, equals(456));
expect(timeline.events![1].timestampMicros, equals(457));
expect(timeline.events![0].name, equals('test event 2'));
expect(timeline.events![1].name, equals('test event 1'));
});
test('sorts JSON nulls first', () {
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
'traceEvents': <Map<String, dynamic>>[
<String, dynamic>{
'name': 'test event 0',
'ts': null,
},
<String, dynamic>{
'name': 'test event 1',
'ts': 457,
},
<String, dynamic>{
'name': 'test event 2',
'ts': 456,
},
<String, dynamic>{
'name': 'test event 3',
'ts': null,
},
],
});
expect(timeline.events, hasLength(4));
expect(timeline.events![0].timestampMicros, isNull);
expect(timeline.events![1].timestampMicros, isNull);
expect(timeline.events![2].timestampMicros, equals(456));
expect(timeline.events![3].timestampMicros, equals(457));
expect(timeline.events![0].name, equals('test event 0'));
expect(timeline.events![1].name, equals('test event 3'));
expect(timeline.events![2].name, equals('test event 2'));
expect(timeline.events![3].name, equals('test event 1'));
});
});
}
| flutter/packages/flutter_driver/test/src/real_tests/timeline_test.dart/0 | {'file_path': 'flutter/packages/flutter_driver/test/src/real_tests/timeline_test.dart', 'repo_id': 'flutter', 'token_count': 1741} |
// Copyright 2014 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.
/// Localizations for the Flutter library.
library flutter_localizations;
export 'src/cupertino_localizations.dart';
export 'src/l10n/generated_cupertino_localizations.dart';
export 'src/l10n/generated_material_localizations.dart';
export 'src/material_localizations.dart';
export 'src/widgets_localizations.dart';
| flutter/packages/flutter_localizations/lib/flutter_localizations.dart/0 | {'file_path': 'flutter/packages/flutter_localizations/lib/flutter_localizations.dart', 'repo_id': 'flutter', 'token_count': 143} |
# package:test configuration
# https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md
# Some of our tests take an absurdly long time to run, and on some
# hosts they can take even longer due to the host suddenly being
# overloaded. For this reason, we set the test timeout to
# significantly more than it would be by default, and we never set the
# timeouts in the tests themselves.
#
# For the `test/general.shard` specifically, the `dev/bots/test.dart` script
# overrides this, reducing it to only 2000ms. Unit tests must run fast!
timeout: 15m
tags:
# This tag tells the test framework to not shuffle the test order according to
# the --test-randomize-ordering-seed for the suites that have this tag.
no-shuffle:
allow_test_randomization: false
| flutter/packages/flutter_tools/dart_test.yaml/0 | {'file_path': 'flutter/packages/flutter_tools/dart_test.yaml', 'repo_id': 'flutter', 'token_count': 222} |
// Copyright 2014 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:meta/meta.dart';
import 'package:process/process.dart';
import '../artifacts.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/terminal.dart';
import '../project_validator.dart';
import '../runner/flutter_command.dart';
import 'analyze_base.dart';
import 'analyze_continuously.dart';
import 'analyze_once.dart';
import 'validate_project.dart';
class AnalyzeCommand extends FlutterCommand {
AnalyzeCommand({
bool verboseHelp = false,
this.workingDirectory,
required FileSystem fileSystem,
required Platform platform,
required Terminal terminal,
required Logger logger,
required ProcessManager processManager,
required Artifacts artifacts,
required List<ProjectValidator> allProjectValidators,
}) : _artifacts = artifacts,
_fileSystem = fileSystem,
_processManager = processManager,
_logger = logger,
_terminal = terminal,
_allProjectValidators = allProjectValidators,
_platform = platform {
argParser.addFlag('flutter-repo',
negatable: false,
help: 'Include all the examples and tests from the Flutter repository.',
hide: !verboseHelp);
argParser.addFlag('current-package',
help: 'Analyze the current project, if applicable.', defaultsTo: true);
argParser.addFlag('dartdocs',
negatable: false,
help: '(deprecated) List every public member that is lacking documentation. '
'This command will be removed in a future version of Flutter.',
hide: !verboseHelp);
argParser.addFlag('watch',
help: 'Run analysis continuously, watching the filesystem for changes.',
negatable: false);
argParser.addOption('write',
valueHelp: 'file',
help: 'Also output the results to a file. This is useful with "--watch" '
'if you want a file to always contain the latest results.');
argParser.addOption('dart-sdk',
valueHelp: 'path-to-sdk',
help: 'The path to the Dart SDK.',
hide: !verboseHelp);
argParser.addOption('protocol-traffic-log',
valueHelp: 'path-to-protocol-traffic-log',
help: 'The path to write the request and response protocol. This is '
'only intended to be used for debugging the tooling.',
hide: !verboseHelp);
argParser.addFlag('suggestions',
help: 'Show suggestions about the current flutter project.'
);
argParser.addFlag('machine',
negatable: false,
help: 'Dumps a JSON with a subset of relevant data about the tool, project, '
'and environment.',
hide: !verboseHelp,
);
// Hidden option to enable a benchmarking mode.
argParser.addFlag('benchmark',
negatable: false,
hide: !verboseHelp,
help: 'Also output the analysis time.');
usesPubOption();
// Not used by analyze --watch
argParser.addFlag('congratulate',
help: 'Show output even when there are no errors, warnings, hints, or lints. '
'Ignored if "--watch" is specified.',
defaultsTo: true);
argParser.addFlag('preamble',
defaultsTo: true,
help: 'When analyzing the flutter repository, display the number of '
'files that will be analyzed.\n'
'Ignored if "--watch" is specified.');
argParser.addFlag('fatal-infos',
help: 'Treat info level issues as fatal.',
defaultsTo: true);
argParser.addFlag('fatal-warnings',
help: 'Treat warning level issues as fatal.',
defaultsTo: true);
}
/// The working directory for testing analysis using dartanalyzer.
final Directory? workingDirectory;
final Artifacts _artifacts;
final FileSystem _fileSystem;
final Logger _logger;
final Terminal _terminal;
final ProcessManager _processManager;
final Platform _platform;
final List<ProjectValidator> _allProjectValidators;
@override
String get name => 'analyze';
@override
String get description => "Analyze the project's Dart code.";
@override
String get category => FlutterCommandCategory.project;
@visibleForTesting
List<ProjectValidator> allProjectValidators() => _allProjectValidators;
@override
bool get shouldRunPub {
// If they're not analyzing the current project.
if (!boolArgDeprecated('current-package')) {
return false;
}
// Or we're not in a project directory.
if (!_fileSystem.file('pubspec.yaml').existsSync()) {
return false;
}
// Don't run pub if asking for machine output.
if (boolArg('machine') != null && boolArg('machine')!) {
return false;
}
return super.shouldRunPub;
}
@override
Future<FlutterCommandResult> runCommand() async {
final bool? suggestionFlag = boolArg('suggestions');
final bool machineFlag = boolArg('machine') ?? false;
if (suggestionFlag != null && suggestionFlag == true) {
final String directoryPath;
final bool? watchFlag = boolArg('watch');
if (watchFlag != null && watchFlag) {
throwToolExit('flag --watch is not compatible with --suggestions');
}
if (workingDirectory == null) {
final Set<String> items = findDirectories(argResults!, _fileSystem);
if (items.isEmpty) { // user did not specify any path
directoryPath = _fileSystem.currentDirectory.path;
_logger.printTrace('Showing suggestions for current directory: $directoryPath');
} else if (items.length > 1) { // if the user sends more than one path
throwToolExit('The suggestions flag can process only one directory path');
} else {
directoryPath = items.first;
}
} else {
directoryPath = workingDirectory!.path;
}
return ValidateProject(
fileSystem: _fileSystem,
logger: _logger,
allProjectValidators: _allProjectValidators,
userPath: directoryPath,
processManager: _processManager,
machine: machineFlag,
).run();
} else if (boolArgDeprecated('watch')) {
await AnalyzeContinuously(
argResults!,
runner!.getRepoRoots(),
runner!.getRepoPackages(),
fileSystem: _fileSystem,
logger: _logger,
platform: _platform,
processManager: _processManager,
terminal: _terminal,
artifacts: _artifacts,
).analyze();
} else {
await AnalyzeOnce(
argResults!,
runner!.getRepoRoots(),
runner!.getRepoPackages(),
workingDirectory: workingDirectory,
fileSystem: _fileSystem,
logger: _logger,
platform: _platform,
processManager: _processManager,
terminal: _terminal,
artifacts: _artifacts,
).analyze();
}
return FlutterCommandResult.success();
}
}
| flutter/packages/flutter_tools/lib/src/commands/analyze.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/commands/analyze.dart', 'repo_id': 'flutter', 'token_count': 2608} |
// Copyright 2014 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 '../globals.dart' as globals;
import '../runner/flutter_command.dart';
class GenerateCommand extends FlutterCommand {
GenerateCommand() {
usesTargetOption();
}
@override
String get description => 'run code generators.';
@override
String get name => 'generate';
@override
bool get hidden => true;
@override
Future<FlutterCommandResult> runCommand() async {
globals.printError(
'"flutter generate" is deprecated, use "dart pub run build_runner" instead. '
'The following dependencies must be added to dev_dependencies in pubspec.yaml:\n'
'build_runner: ^1.10.0\n'
'including all dependencies under the "builders" key'
);
return FlutterCommandResult.fail();
}
}
| flutter/packages/flutter_tools/lib/src/commands/generate.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/commands/generate.dart', 'repo_id': 'flutter', 'token_count': 288} |
// Copyright 2014 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:process/process.dart';
import 'android/android_sdk.dart';
import 'android/application_package.dart';
import 'application_package.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/process.dart';
import 'base/user_messages.dart';
import 'build_info.dart';
import 'fuchsia/application_package.dart';
import 'globals.dart' as globals;
import 'ios/application_package.dart';
import 'linux/application_package.dart';
import 'macos/application_package.dart';
import 'project.dart';
import 'tester/flutter_tester.dart';
import 'web/web_device.dart';
import 'windows/application_package.dart';
/// A package factory that supports all Flutter target platforms.
class FlutterApplicationPackageFactory extends ApplicationPackageFactory {
FlutterApplicationPackageFactory({
required AndroidSdk? androidSdk,
required ProcessManager processManager,
required Logger logger,
required UserMessages userMessages,
required FileSystem fileSystem,
}) : _androidSdk = androidSdk,
_processManager = processManager,
_logger = logger,
_userMessages = userMessages,
_fileSystem = fileSystem,
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
final AndroidSdk? _androidSdk;
final ProcessManager _processManager;
final Logger _logger;
final ProcessUtils _processUtils;
final UserMessages _userMessages;
final FileSystem _fileSystem;
@override
Future<ApplicationPackage?> getPackageForPlatform(
TargetPlatform platform, {
BuildInfo? buildInfo,
File? applicationBinary,
}) async {
switch (platform) {
case TargetPlatform.android:
case TargetPlatform.android_arm:
case TargetPlatform.android_arm64:
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
if (applicationBinary == null) {
return AndroidApk.fromAndroidProject(
FlutterProject.current().android,
processManager: _processManager,
processUtils: _processUtils,
logger: _logger,
androidSdk: _androidSdk,
userMessages: _userMessages,
fileSystem: _fileSystem,
buildInfo: buildInfo,
);
}
return AndroidApk.fromApk(
applicationBinary,
processManager: _processManager,
logger: _logger,
androidSdk: _androidSdk!,
userMessages: _userMessages,
processUtils: _processUtils,
);
case TargetPlatform.ios:
return applicationBinary == null
? await IOSApp.fromIosProject(FlutterProject.current().ios, buildInfo)
: IOSApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.tester:
return FlutterTesterApp.fromCurrentDirectory(globals.fs);
case TargetPlatform.darwin:
return applicationBinary == null
? MacOSApp.fromMacOSProject(FlutterProject.current().macos)
: MacOSApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.web_javascript:
if (!FlutterProject.current().web.existsSync()) {
return null;
}
return WebApplicationPackage(FlutterProject.current());
case TargetPlatform.linux_x64:
case TargetPlatform.linux_arm64:
return applicationBinary == null
? LinuxApp.fromLinuxProject(FlutterProject.current().linux)
: LinuxApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.windows_x64:
return applicationBinary == null
? WindowsApp.fromWindowsProject(FlutterProject.current().windows)
: WindowsApp.fromPrebuiltApp(applicationBinary);
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
return applicationBinary == null
? FuchsiaApp.fromFuchsiaProject(FlutterProject.current().fuchsia)
: FuchsiaApp.fromPrebuiltApp(applicationBinary);
}
}
}
| flutter/packages/flutter_tools/lib/src/flutter_application_package.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/flutter_application_package.dart', 'repo_id': 'flutter', 'token_count': 1564} |
// Copyright 2014 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 '../artifacts.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../device.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../web/chrome.dart';
import '../web/memory_fs.dart';
import 'flutter_platform.dart' as loader;
import 'flutter_web_platform.dart';
import 'test_time_recorder.dart';
import 'test_wrapper.dart';
import 'watcher.dart';
import 'web_test_compiler.dart';
/// A class that abstracts launching the test process from the test runner.
abstract class FlutterTestRunner {
const factory FlutterTestRunner() = _FlutterTestRunnerImpl;
/// Runs tests using package:test and the Flutter engine.
Future<int> runTests(
TestWrapper testWrapper,
List<String> testFiles, {
required DebuggingOptions debuggingOptions,
List<String> names = const <String>[],
List<String> plainNames = const <String>[],
String? tags,
String? excludeTags,
bool enableObservatory = false,
bool ipv6 = false,
bool machine = false,
String? precompiledDillPath,
Map<String, String>? precompiledDillFiles,
bool updateGoldens = false,
TestWatcher? watcher,
required int? concurrency,
String? testAssetDirectory,
FlutterProject? flutterProject,
String? icudtlPath,
Directory? coverageDirectory,
bool web = false,
String? randomSeed,
String? reporter,
String? timeout,
bool runSkipped = false,
int? shardIndex,
int? totalShards,
Device? integrationTestDevice,
String? integrationTestUserIdentifier,
TestTimeRecorder? testTimeRecorder,
});
}
class _FlutterTestRunnerImpl implements FlutterTestRunner {
const _FlutterTestRunnerImpl();
@override
Future<int> runTests(
TestWrapper testWrapper,
List<String> testFiles, {
required DebuggingOptions debuggingOptions,
List<String> names = const <String>[],
List<String> plainNames = const <String>[],
String? tags,
String? excludeTags,
bool enableObservatory = false,
bool ipv6 = false,
bool machine = false,
String? precompiledDillPath,
Map<String, String>? precompiledDillFiles,
bool updateGoldens = false,
TestWatcher? watcher,
required int? concurrency,
String? testAssetDirectory,
FlutterProject? flutterProject,
String? icudtlPath,
Directory? coverageDirectory,
bool web = false,
String? randomSeed,
String? reporter,
String? timeout,
bool runSkipped = false,
int? shardIndex,
int? totalShards,
Device? integrationTestDevice,
String? integrationTestUserIdentifier,
TestTimeRecorder? testTimeRecorder,
}) async {
// Configure package:test to use the Flutter engine for child processes.
final String shellPath = globals.artifacts!.getArtifactPath(Artifact.flutterTester);
// Compute the command-line arguments for package:test.
final List<String> testArgs = <String>[
if (!globals.terminal.supportsColor)
'--no-color',
if (debuggingOptions.startPaused)
'--pause-after-load',
if (machine)
...<String>['-r', 'json']
else if (reporter != null)
...<String>['-r', reporter],
if (timeout != null)
...<String>['--timeout', timeout],
'--concurrency=$concurrency',
for (final String name in names)
...<String>['--name', name],
for (final String plainName in plainNames)
...<String>['--plain-name', plainName],
if (randomSeed != null)
'--test-randomize-ordering-seed=$randomSeed',
if (tags != null)
...<String>['--tags', tags],
if (excludeTags != null)
...<String>['--exclude-tags', excludeTags],
if (runSkipped)
'--run-skipped',
if (totalShards != null)
'--total-shards=$totalShards',
if (shardIndex != null)
'--shard-index=$shardIndex',
'--chain-stack-traces',
];
if (web) {
final String tempBuildDir = globals.fs.systemTempDirectory
.createTempSync('flutter_test.')
.absolute
.uri
.toFilePath();
final WebMemoryFS result = await WebTestCompiler(
logger: globals.logger,
fileSystem: globals.fs,
platform: globals.platform,
artifacts: globals.artifacts!,
processManager: globals.processManager,
config: globals.config,
).initialize(
projectDirectory: flutterProject!.directory,
testOutputDir: tempBuildDir,
testFiles: testFiles,
buildInfo: debuggingOptions.buildInfo,
);
testArgs
..add('--platform=chrome')
..add('--')
..addAll(testFiles);
testWrapper.registerPlatformPlugin(
<Runtime>[Runtime.chrome],
() {
return FlutterWebPlatform.start(
flutterProject.directory.path,
updateGoldens: updateGoldens,
shellPath: shellPath,
flutterProject: flutterProject,
pauseAfterLoad: debuggingOptions.startPaused,
nullAssertions: debuggingOptions.nullAssertions,
buildInfo: debuggingOptions.buildInfo,
webMemoryFS: result,
logger: globals.logger,
fileSystem: globals.fs,
artifacts: globals.artifacts,
processManager: globals.processManager,
chromiumLauncher: ChromiumLauncher(
fileSystem: globals.fs,
platform: globals.platform,
processManager: globals.processManager,
operatingSystemUtils: globals.os,
browserFinder: findChromeExecutable,
logger: globals.logger,
),
cache: globals.cache,
testTimeRecorder: testTimeRecorder,
);
},
);
await testWrapper.main(testArgs);
return exitCode;
}
testArgs
..add('--')
..addAll(testFiles);
final InternetAddressType serverType =
ipv6 ? InternetAddressType.IPv6 : InternetAddressType.IPv4;
final loader.FlutterPlatform platform = loader.installHook(
testWrapper: testWrapper,
shellPath: shellPath,
debuggingOptions: debuggingOptions,
watcher: watcher,
enableObservatory: enableObservatory,
machine: machine,
serverType: serverType,
precompiledDillPath: precompiledDillPath,
precompiledDillFiles: precompiledDillFiles,
updateGoldens: updateGoldens,
testAssetDirectory: testAssetDirectory,
projectRootDirectory: globals.fs.currentDirectory.uri,
flutterProject: flutterProject,
icudtlPath: icudtlPath,
integrationTestDevice: integrationTestDevice,
integrationTestUserIdentifier: integrationTestUserIdentifier,
testTimeRecorder: testTimeRecorder,
);
try {
globals.printTrace('running test package with arguments: $testArgs');
await testWrapper.main(testArgs);
// test.main() sets dart:io's exitCode global.
globals.printTrace('test package returned with exit code $exitCode');
return exitCode;
} finally {
await platform.close();
}
}
}
| flutter/packages/flutter_tools/lib/src/test/runner.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/test/runner.dart', 'repo_id': 'flutter', 'token_count': 2868} |
// Copyright 2014 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 '../base/context.dart';
import '../base/user_messages.dart' hide userMessages;
import '../doctor_validator.dart';
import 'visual_studio.dart';
VisualStudioValidator? get visualStudioValidator => context.get<VisualStudioValidator>();
class VisualStudioValidator extends DoctorValidator {
const VisualStudioValidator({
required VisualStudio visualStudio,
required UserMessages userMessages,
}) : _visualStudio = visualStudio,
_userMessages = userMessages,
super('Visual Studio - develop for Windows');
final VisualStudio _visualStudio;
final UserMessages _userMessages;
@override
Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType status = ValidationType.missing;
String? versionInfo;
if (_visualStudio.isInstalled) {
status = ValidationType.success;
messages.add(ValidationMessage(
_userMessages.visualStudioLocation(_visualStudio.installLocation ?? 'unknown')
));
messages.add(ValidationMessage(_userMessages.visualStudioVersion(
_visualStudio.displayName ?? 'unknown',
_visualStudio.fullVersion ?? 'unknown',
)));
if (_visualStudio.isPrerelease) {
messages.add(ValidationMessage(_userMessages.visualStudioIsPrerelease));
}
final String? windows10SdkVersion = _visualStudio.getWindows10SDKVersion();
if (windows10SdkVersion != null) {
messages.add(ValidationMessage(_userMessages.windows10SdkVersion(windows10SdkVersion)));
}
// Messages for faulty installations.
if (!_visualStudio.isAtLeastMinimumVersion) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(
_userMessages.visualStudioTooOld(
_visualStudio.minimumVersionDescription,
_visualStudio.workloadDescription,
),
));
} else if (_visualStudio.isRebootRequired) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(_userMessages.visualStudioRebootRequired));
} else if (!_visualStudio.isComplete) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(_userMessages.visualStudioIsIncomplete));
} else if (!_visualStudio.isLaunchable) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(_userMessages.visualStudioNotLaunchable));
} else if (!_visualStudio.hasNecessaryComponents) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(
_userMessages.visualStudioMissingComponents(
_visualStudio.workloadDescription,
_visualStudio.necessaryComponentDescriptions(),
),
));
} else if (windows10SdkVersion == null) {
status = ValidationType.partial;
messages.add(ValidationMessage.hint(_userMessages.windows10SdkNotFound));
}
versionInfo = '${_visualStudio.displayName} ${_visualStudio.displayVersion}';
} else {
status = ValidationType.missing;
messages.add(ValidationMessage.error(
_userMessages.visualStudioMissing(
_visualStudio.workloadDescription,
),
));
}
return ValidationResult(status, messages, statusInfo: versionInfo);
}
}
| flutter/packages/flutter_tools/lib/src/windows/visual_studio_validator.dart/0 | {'file_path': 'flutter/packages/flutter_tools/lib/src/windows/visual_studio_validator.dart', 'repo_id': 'flutter', 'token_count': 1276} |
// Copyright 2014 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/memory.dart';
import 'package:flutter_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/shell_completion.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import '../../src/context.dart';
import '../../src/fakes.dart';
import '../../src/test_flutter_command_runner.dart';
void main() {
group('shell_completion', () {
late FakeStdio fakeStdio;
setUp(() {
Cache.disableLocking();
fakeStdio = FakeStdio()..stdout.terminalColumns = 80;
});
testUsingContext('generates bash initialization script to stdout', () async {
final ShellCompletionCommand command = ShellCompletionCommand();
await createTestCommandRunner(command).run(<String>['bash-completion']);
expect(fakeStdio.writtenToStdout.length, equals(1));
expect(fakeStdio.writtenToStdout.first, contains('__flutter_completion'));
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Stdio: () => fakeStdio,
});
testUsingContext('generates bash initialization script to stdout with arg', () async {
final ShellCompletionCommand command = ShellCompletionCommand();
await createTestCommandRunner(command).run(<String>['bash-completion', '-']);
expect(fakeStdio.writtenToStdout.length, equals(1));
expect(fakeStdio.writtenToStdout.first, contains('__flutter_completion'));
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Stdio: () => fakeStdio,
});
testUsingContext('generates bash initialization script to output file', () async {
final ShellCompletionCommand command = ShellCompletionCommand();
const String outputFile = 'bash-setup.sh';
await createTestCommandRunner(command).run(
<String>['bash-completion', outputFile],
);
expect(globals.fs.isFileSync(outputFile), isTrue);
expect(globals.fs.file(outputFile).readAsStringSync(), contains('__flutter_completion'));
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Stdio: () => fakeStdio,
});
testUsingContext("won't overwrite existing output file ", () async {
final ShellCompletionCommand command = ShellCompletionCommand();
const String outputFile = 'bash-setup.sh';
globals.fs.file(outputFile).createSync();
await expectLater(
() => createTestCommandRunner(command).run(
<String>['bash-completion', outputFile],
),
throwsA(
isA<ToolExit>()
.having((ToolExit error) => error.exitCode, 'exitCode', anyOf(isNull, 1))
.having((ToolExit error) => error.message, 'message', contains('Use --overwrite')),
),
);
expect(globals.fs.isFileSync(outputFile), isTrue);
expect(globals.fs.file(outputFile).readAsStringSync(), isEmpty);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Stdio: () => fakeStdio,
});
testUsingContext('will overwrite existing output file if given --overwrite', () async {
final ShellCompletionCommand command = ShellCompletionCommand();
const String outputFile = 'bash-setup.sh';
globals.fs.file(outputFile).createSync();
await createTestCommandRunner(command).run(
<String>['bash-completion', '--overwrite', outputFile],
);
expect(globals.fs.isFileSync(outputFile), isTrue);
expect(globals.fs.file(outputFile).readAsStringSync(), contains('__flutter_completion'));
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Stdio: () => fakeStdio,
});
});
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/shell_completion_test.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/commands.shard/hermetic/shell_completion_test.dart', 'repo_id': 'flutter', 'token_count': 1544} |
// Copyright 2014 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_tools/src/base/utils.dart';
import '../src/common.dart';
void main() {
group('ItemListNotifier', () {
test('sends notifications', () async {
final ItemListNotifier<String> list = ItemListNotifier<String>();
expect(list.items, isEmpty);
final Future<List<String>> addedStreamItems = list.onAdded.toList();
final Future<List<String>> removedStreamItems = list.onRemoved.toList();
list.updateWithNewList(<String>['aaa']);
list.removeItem('bogus');
list.updateWithNewList(<String>['aaa', 'bbb', 'ccc']);
list.updateWithNewList(<String>['bbb', 'ccc']);
list.removeItem('bbb');
expect(list.items, <String>['ccc']);
list.dispose();
final List<String> addedItems = await addedStreamItems;
final List<String> removedItems = await removedStreamItems;
expect(addedItems.length, 3);
expect(addedItems.first, 'aaa');
expect(addedItems[1], 'bbb');
expect(addedItems[2], 'ccc');
expect(removedItems.length, 2);
expect(removedItems.first, 'aaa');
expect(removedItems[1], 'bbb');
});
});
}
| flutter/packages/flutter_tools/test/general.shard/base_utils_test.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/general.shard/base_utils_test.dart', 'repo_id': 'flutter', 'token_count': 489} |
// Copyright 2014 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/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/persistent_tool_state.dart';
import 'package:flutter_tools/src/version.dart';
import '../src/common.dart';
void main() {
testWithoutContext('state can be set and persists', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final Directory directory = fileSystem.directory('state_dir');
directory.createSync();
final File stateFile = directory.childFile('.flutter_tool_state');
final PersistentToolState state1 = PersistentToolState.test(
directory: directory,
logger: BufferLogger.test(),
);
expect(state1.shouldRedisplayWelcomeMessage, null);
state1.setShouldRedisplayWelcomeMessage(true);
expect(stateFile.existsSync(), true);
expect(state1.shouldRedisplayWelcomeMessage, true);
state1.setShouldRedisplayWelcomeMessage(false);
expect(state1.shouldRedisplayWelcomeMessage, false);
final PersistentToolState state2 = PersistentToolState.test(
directory: directory,
logger: BufferLogger.test(),
);
expect(state2.shouldRedisplayWelcomeMessage, false);
});
testWithoutContext('channel versions can be cached and stored', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final Directory directory = fileSystem.directory('state_dir')..createSync();
final PersistentToolState state1 = PersistentToolState.test(
directory: directory,
logger: BufferLogger.test(),
);
state1.updateLastActiveVersion('abc', Channel.master);
state1.updateLastActiveVersion('ghi', Channel.beta);
state1.updateLastActiveVersion('jkl', Channel.stable);
final PersistentToolState state2 = PersistentToolState.test(
directory: directory,
logger: BufferLogger.test(),
);
expect(state2.lastActiveVersion(Channel.master), 'abc');
expect(state2.lastActiveVersion(Channel.beta), 'ghi');
expect(state2.lastActiveVersion(Channel.stable), 'jkl');
});
}
| flutter/packages/flutter_tools/test/general.shard/persistent_tool_state_test.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/general.shard/persistent_tool_state_test.dart', 'repo_id': 'flutter', 'token_count': 725} |
// Copyright 2014 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_tools/src/base/platform.dart';
import 'package:flutter_tools/src/web/workflow.dart';
import '../../src/common.dart';
import '../../src/fakes.dart';
void main() {
testWithoutContext('WebWorkflow applies on Linux', () {
final WebWorkflow workflow = WebWorkflow(
platform: FakePlatform(),
featureFlags: TestFeatureFlags(isWebEnabled: true),
);
expect(workflow.appliesToHostPlatform, true);
expect(workflow.canLaunchDevices, true);
expect(workflow.canListDevices, true);
expect(workflow.canListEmulators, false);
});
testWithoutContext('WebWorkflow applies on macOS', () {
final WebWorkflow workflow = WebWorkflow(
platform: FakePlatform(operatingSystem: 'macos'),
featureFlags: TestFeatureFlags(isWebEnabled: true),
);
expect(workflow.appliesToHostPlatform, true);
expect(workflow.canLaunchDevices, true);
expect(workflow.canListDevices, true);
expect(workflow.canListEmulators, false);
});
testWithoutContext('WebWorkflow applies on Windows', () {
final WebWorkflow workflow = WebWorkflow(
platform: FakePlatform(operatingSystem: 'windows'),
featureFlags: TestFeatureFlags(isWebEnabled: true),
);
expect(workflow.appliesToHostPlatform, true);
expect(workflow.canLaunchDevices, true);
expect(workflow.canListDevices, true);
expect(workflow.canListEmulators, false);
});
testWithoutContext('WebWorkflow does not apply on other platforms', () {
final WebWorkflow workflow = WebWorkflow(
platform: FakePlatform(operatingSystem: 'fuchsia'),
featureFlags: TestFeatureFlags(isWebEnabled: true),
);
expect(workflow.appliesToHostPlatform, false);
});
testWithoutContext('WebWorkflow does not apply if feature flag is disabled', () {
final WebWorkflow workflow = WebWorkflow(
platform: FakePlatform(),
featureFlags: TestFeatureFlags(),
);
expect(workflow.appliesToHostPlatform, false);
expect(workflow.canLaunchDevices, false);
expect(workflow.canListDevices, false);
expect(workflow.canListEmulators, false);
});
}
| flutter/packages/flutter_tools/test/general.shard/web/workflow_test.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/general.shard/web/workflow_test.dart', 'repo_id': 'flutter', 'token_count': 753} |
// Copyright 2014 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:flutter_tools/src/base/io.dart';
import '../src/common.dart';
import 'test_utils.dart';
void main() {
late Directory tempDir;
setUp(() async {
tempDir = createResolvedTempDirectorySync('run_test.');
});
tearDown(() async {
tryToDelete(tempDir);
});
testWithoutContext('build succeeds with api 33 features', () async {
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
ProcessResult result = await processManager.run(<String>[
flutterBin,
'create',
tempDir.path,
'--project-name=testapp',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
final File api33File = tempDir
.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childDirectory('java')
.childFile('Android33Api.java');
api33File.createSync(recursive: true);
// AccessibilityManager.isAudioDescriptionRequested() is an API 33 feature
api33File.writeAsStringSync('''
import android.app.Activity;
import android.view.accessibility.AccessibilityManager;
import androidx.annotation.Keep;
import io.flutter.Log;
@Keep
public final class Android33Api extends Activity {
private AccessibilityManager accessibilityManager;
public Android33Api() {
accessibilityManager = getSystemService(AccessibilityManager.class);
}
public void doSomething() {
if (accessibilityManager.isAudioDescriptionRequested()) {
Log.e("flutter", "User has requested to enable audio descriptions");
}
}
}
''');
result = await processManager.run(<String>[
flutterBin,
...getLocalEngineArguments(),
'build',
'apk',
], workingDirectory: tempDir.path);
expect(result.exitCode, 0);
expect(result.stdout.toString(), contains('app-release.apk'));
});
}
| flutter/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart', 'repo_id': 'flutter', 'token_count': 708} |
// Copyright 2014 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:flutter_tools/src/base/file_system.dart';
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
import '../src/common.dart';
import 'test_data/basic_project.dart';
import 'test_driver.dart';
import 'test_utils.dart';
void main() {
group('Flutter Tool VMService method', () {
late Directory tempDir;
late FlutterRunTestDriver flutter;
late VmService vmService;
setUp(() async {
tempDir = createResolvedTempDirectorySync('vmservice_integration_test.');
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
flutter = FlutterRunTestDriver(tempDir);
await flutter.run(withDebugger: true);
final int? port = flutter.vmServicePort;
expect(port != null, true);
vmService = await vmServiceConnectUri('ws://localhost:$port/ws');
});
tearDown(() async {
await flutter.stop();
tryToDelete(tempDir);
});
testWithoutContext('getSupportedProtocols includes DDS', () async {
final ProtocolList protocolList =
await vmService.getSupportedProtocols();
expect(protocolList.protocols, hasLength(2));
for (final Protocol protocol in protocolList.protocols!) {
expect(protocol.protocolName, anyOf('VM Service', 'DDS'));
}
});
testWithoutContext('flutterVersion can be called', () async {
final Response response =
await vmService.callServiceExtension('s0.flutterVersion');
expect(response.type, 'Success');
expect(response.json, containsPair('frameworkRevisionShort', isNotNull));
expect(response.json, containsPair('engineRevisionShort', isNotNull));
});
testWithoutContext('flutterMemoryInfo can be called', () async {
final Response response =
await vmService.callServiceExtension('s0.flutterMemoryInfo');
expect(response.type, 'Success');
});
testWithoutContext('reloadSources can be called', () async {
final VM vm = await vmService.getVM();
final IsolateRef? isolateRef = vm.isolates?.first;
expect(isolateRef != null, true);
final Response response = await vmService.callMethod('s0.reloadSources',
isolateId: isolateRef!.id);
expect(response.type, 'Success');
});
testWithoutContext('reloadSources fails on bad params', () async {
final Future<Response> response =
vmService.callMethod('s0.reloadSources', isolateId: '');
expect(response, throwsA(const TypeMatcher<RPCError>()));
});
testWithoutContext('hotRestart can be called', () async {
final VM vm = await vmService.getVM();
final IsolateRef? isolateRef = vm.isolates?.first;
expect(isolateRef != null, true);
final Response response =
await vmService.callMethod('s0.hotRestart', isolateId: isolateRef!.id);
expect(response.type, 'Success');
});
testWithoutContext('hotRestart fails on bad params', () async {
final Future<Response> response = vmService.callMethod('s0.hotRestart',
args: <String, dynamic>{'pause': 'not_a_bool'});
expect(response, throwsA(const TypeMatcher<RPCError>()));
});
testWithoutContext('flutterGetSkSL can be called', () async {
final Response response = await vmService.callMethod('s0.flutterGetSkSL');
expect(response.type, 'Success');
});
testWithoutContext('ext.flutter.brightnessOverride can toggle window brightness', () async {
final Isolate isolate = await waitForExtension(vmService, 'ext.flutter.brightnessOverride');
final Response response = await vmService.callServiceExtension(
'ext.flutter.brightnessOverride',
isolateId: isolate.id,
);
expect(response.json?['value'], 'Brightness.light');
final Response updateResponse = await vmService.callServiceExtension(
'ext.flutter.brightnessOverride',
isolateId: isolate.id,
args: <String, String>{
'value': 'Brightness.dark',
}
);
expect(updateResponse.json?['value'], 'Brightness.dark');
// Change the brightness back to light
final Response verifyResponse = await vmService.callServiceExtension(
'ext.flutter.brightnessOverride',
isolateId: isolate.id,
args: <String, String>{
'value': 'Brightness.light',
}
);
expect(verifyResponse.json?['value'], 'Brightness.light');
// Change with a bogus value
final Response bogusResponse = await vmService.callServiceExtension(
'ext.flutter.brightnessOverride',
isolateId: isolate.id,
args: <String, String>{
'value': 'dark', // Intentionally invalid value.
}
);
expect(bogusResponse.json?['value'], 'Brightness.light');
});
testWithoutContext('ext.flutter.debugPaint can toggle debug painting', () async {
final Isolate isolate = await waitForExtension(vmService, 'ext.flutter.debugPaint');
final Response response = await vmService.callServiceExtension(
'ext.flutter.debugPaint',
isolateId: isolate.id,
);
expect(response.json?['enabled'], 'false');
final Response updateResponse = await vmService.callServiceExtension(
'ext.flutter.debugPaint',
isolateId: isolate.id,
args: <String, String>{
'enabled': 'true',
}
);
expect(updateResponse.json?['enabled'], 'true');
});
});
}
| flutter/packages/flutter_tools/test/integration.shard/vmservice_integration_test.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/integration.shard/vmservice_integration_test.dart', 'repo_id': 'flutter', 'token_count': 2093} |
// Copyright 2014 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:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/user_messages.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/create.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/runner/flutter_command_runner.dart';
export 'package:test_api/test_api.dart' hide isInstanceOf, test; // ignore: deprecated_member_use
CommandRunner<void> createTestCommandRunner([ FlutterCommand? command ]) {
final FlutterCommandRunner runner = TestFlutterCommandRunner();
if (command != null) {
runner.addCommand(command);
}
return runner;
}
/// Creates a flutter project in the [temp] directory using the
/// [arguments] list if specified, or `--no-pub` if not.
/// Returns the path to the flutter project.
Future<String> createProject(Directory temp, { List<String>? arguments }) async {
arguments ??= <String>['--no-pub'];
final String projectPath = globals.fs.path.join(temp.path, 'flutter_project');
final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command);
await runner.run(<String>['create', ...arguments, projectPath]);
// Create `.packages` since it's not created when the flag `--no-pub` is passed.
globals.fs.file(globals.fs.path.join(projectPath, '.packages')).createSync();
return projectPath;
}
class TestFlutterCommandRunner extends FlutterCommandRunner {
@override
Future<void> runCommand(ArgResults topLevelResults) async {
final Logger topLevelLogger = globals.logger;
final Map<Type, dynamic> contextOverrides = <Type, dynamic>{
if (topLevelResults['verbose'] as bool)
Logger: VerboseLogger(topLevelLogger),
};
return context.run<void>(
overrides: contextOverrides.map<Type, Generator>((Type type, dynamic value) {
return MapEntry<Type, Generator>(type, () => value);
}),
body: () {
Cache.flutterRoot ??= Cache.defaultFlutterRoot(
platform: globals.platform,
fileSystem: globals.fs,
userMessages: UserMessages(),
);
// For compatibility with tests that set this to a relative path.
Cache.flutterRoot = globals.fs.path.normalize(globals.fs.path.absolute(Cache.flutterRoot!));
return super.runCommand(topLevelResults);
}
);
}
}
| flutter/packages/flutter_tools/test/src/test_flutter_command_runner.dart/0 | {'file_path': 'flutter/packages/flutter_tools/test/src/test_flutter_command_runner.dart', 'repo_id': 'flutter', 'token_count': 961} |
// Copyright 2014 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('chrome') // Uses web-only Flutter SDK
library;
import 'dart:ui' as ui;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
class TestPlugin {
static void registerWith(Registrar registrar) {
final MethodChannel channel = MethodChannel(
'test_plugin',
const StandardMethodCodec(),
registrar.messenger,
);
final TestPlugin testPlugin = TestPlugin();
channel.setMethodCallHandler(testPlugin.handleMethodCall);
}
static final List<String> calledMethods = <String>[];
Future<void> handleMethodCall(MethodCall call) async {
calledMethods.add(call.method);
}
}
void main() {
// Disabling tester emulation because this test relies on real message channel communication.
ui.debugEmulateFlutterTesterEnvironment = false; // ignore: undefined_prefixed_name
group('Plugin Registry', () {
setUp(() {
TestWidgetsFlutterBinding.ensureInitialized();
webPluginRegistry.registerMessageHandler();
final Registrar registrar = webPluginRegistry.registrarFor(TestPlugin);
TestPlugin.registerWith(registrar);
});
test('can register a plugin', () {
TestPlugin.calledMethods.clear();
const MethodChannel frameworkChannel =
MethodChannel('test_plugin');
frameworkChannel.invokeMethod<void>('test1');
expect(TestPlugin.calledMethods, equals(<String>['test1']));
});
test('can send a message from the plugin to the framework', () async {
const StandardMessageCodec codec = StandardMessageCodec();
final List<String> loggedMessages = <String>[];
ServicesBinding.instance.defaultBinaryMessenger
.setMessageHandler('test_send', (ByteData? data) {
loggedMessages.add(codec.decodeMessage(data)! as String);
return Future<ByteData?>.value();
});
await pluginBinaryMessenger.send(
'test_send', codec.encodeMessage('hello'));
expect(loggedMessages, equals(<String>['hello']));
await pluginBinaryMessenger.send(
'test_send', codec.encodeMessage('world'));
expect(loggedMessages, equals(<String>['hello', 'world']));
ServicesBinding.instance.defaultBinaryMessenger
.setMessageHandler('test_send', null);
});
});
}
| flutter/packages/flutter_web_plugins/test/plugin_registry_test.dart/0 | {'file_path': 'flutter/packages/flutter_web_plugins/test/plugin_registry_test.dart', 'repo_id': 'flutter', 'token_count': 857} |
// Copyright 2014 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 is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'dart:html' as html;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:integration_test_example/main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('verify text', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// Trigger a frame.
await tester.pumpAndSettle();
// Verify that platform is retrieved.
expect(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text &&
widget.data!
.startsWith('Platform: ${html.window.navigator.platform}\n'),
),
findsOneWidget,
);
});
}
| flutter/packages/integration_test/example/integration_test/_example_test_web.dart/0 | {'file_path': 'flutter/packages/integration_test/example/integration_test/_example_test_web.dart', 'repo_id': 'flutter', 'token_count': 433} |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:integration_test_example/main.dart' as app;
/// This file is placed in `test_driver/` instead of `integration_test/`, so
/// that the CI tooling of flutter/plugins only uses this together with
/// `failure_test.dart` as the driver. It is only used for testing of
/// `package:integration_test` – do not follow the conventions here if you are a
/// user of `package:integration_test`.
// Tests the failure behavior of the IntegrationTestWidgetsFlutterBinding
//
// This test fails intentionally! It should be run using a test runner that
// expects failure.
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('success', (WidgetTester tester) async {
expect(1 + 1, 2); // This should pass
});
testWidgets('failure 1', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// Verify that platform version is retrieved.
await expectLater(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text && widget.data!.startsWith('This should fail'),
),
findsOneWidget,
);
});
testWidgets('failure 2', (WidgetTester tester) async {
expect(1 + 1, 3); // This should fail
});
}
| flutter/packages/integration_test/example/test_driver/failure.dart/0 | {'file_path': 'flutter/packages/integration_test/example/test_driver/failure.dart', 'repo_id': 'flutter', 'token_count': 488} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.