code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// Copyright 2017 The Chromium Authors. All rights reserved. Use of this source // code is governed by a BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:cli_util/cli_logging.dart'; import 'package:git/git.dart'; import 'build_spec.dart'; import 'globals.dart'; Future<int> exec(String cmd, List<String> args, {String? cwd}) async { if (cwd != null) { log(_shorten('$cmd ${args.join(' ')} {cwd=$cwd}')); } else { log(_shorten('$cmd ${args.join(' ')}')); } final process = await Process.start(cmd, args, workingDirectory: cwd); _toLineStream(process.stderr).listen(log); _toLineStream(process.stdout).listen(log); return await process.exitCode; } Future<String> makeDevLog(BuildSpec spec) async { if (lastReleaseName.isEmpty) { return ''; } // The shallow on travis causes problems. _checkGitDir(); var gitDir = await GitDir.fromExisting(rootPath); var since = lastReleaseName; var processResult = await gitDir.runCommand(['log', '--oneline', '$since..HEAD']); String out = processResult.stdout; var messages = out.trim().split('\n'); var devLog = StringBuffer(); devLog.writeln('## Changes since ${since.replaceAll('_', ' ')}'); for (var m in messages) { devLog.writeln(m.replaceFirst(RegExp(r'^[A-Fa-f\d]+\s+'), '- ')); } devLog.writeln(); return devLog.toString(); } Future<DateTime> dateOfLastRelease() async { _checkGitDir(); var gitDir = await GitDir.fromExisting(rootPath); var processResult = await gitDir .runCommand(['branch', '--list', '-v', '--no-abbrev', lastReleaseName]); String out = processResult.stdout; var logLine = out.trim().split('\n').first.trim(); var match = RegExp(r'release_\d+\s+([A-Fa-f\d]{40})\s').matchAsPrefix(logLine); var commitHash = match!.group(1); processResult = await gitDir.runCommand(['show', '--pretty=tformat:"%cI"', commitHash!]); out = processResult.stdout; var date = out.trim().split('\n').first.trim(); return DateTime.parse(date.replaceAll('"', '')); } Future<String> lastRelease() async { _checkGitDir(); var gitDir = await GitDir.fromExisting(rootPath); var processResult = await gitDir.runCommand(['branch', '--list', 'release_*']); String out = processResult.stdout; var release = out.trim().split('\n').last.trim(); if (release.isNotEmpty) return release; processResult = await gitDir.runCommand(['branch', '--list', '-a', '*release_*']); out = processResult.stdout; var remote = out.trim().split('\n').last.trim(); // "remotes/origin/release_43" release = remote.substring(remote.lastIndexOf('/') + 1); await gitDir.runCommand(['branch', '--track', release, remote]); return release; } final Ansi ansi = Ansi(true); void separator(String name) { log(''); log('${ansi.red}${ansi.bold}$name${ansi.none}', indent: false); } void log(String s, {bool indent = true}) { indent ? print(' $s') : print(s); } void createDir(String name) { final dir = Directory(name); if (!dir.existsSync()) { log('creating $name/'); dir.createSync(recursive: true); } } Future<int> curl(String url, {required String to}) async { return await exec('curl', ['-o', to, url]); } /// Remove the directory without exceptions if it does not exists. Future<void> removeAll(String dir) async { await Directory(dir).delete(recursive: true).then((_) {}, onError: (_) {}); } bool isNewer(FileSystemEntity newer, FileSystemEntity older) { return newer.statSync().modified.isAfter(older.statSync().modified); } void _checkGitDir() async { var isGitDir = await GitDir.isGitDir(rootPath); if (!isGitDir) { throw 'the current working directory is not managed by git: $rootPath'; } } String _shorten(String str) { return str.length < 200 ? str : '${str.substring(0, 170)} ... ${str.substring(str.length - 30)}'; } Stream<String> _toLineStream(Stream<List<int>> s) => s.transform(utf8.decoder).transform(const LineSplitter()); String readTokenFromKeystore(String keyName) { var env = Platform.environment; var base = env['KOKORO_KEYSTORE_DIR']; var id = env['FLUTTER_KEYSTORE_ID']; var name = env[keyName]; var file = File('$base/${id}_$name'); return file.existsSync() ? file.readAsStringSync() : ''; } int get devBuildNumber { // The dev channel is automatically refreshed weekly, so the build number // is just the number of weeks since the last stable release. var today = DateTime.now(); var daysSinceRelease = today.difference(lastReleaseDate).inDays; var weekNumber = daysSinceRelease ~/ 7 + 1; return weekNumber; } String buildVersionNumber(BuildSpec spec) { var releaseNo = spec.isDevChannel ? _nextRelease() : spec.release; if (releaseNo == null) { releaseNo = 'SNAPSHOT'; } else { releaseNo = '$releaseNo.$pluginCount'; if (spec.isDevChannel) { releaseNo += '-dev.$devBuildNumber'; } } return releaseNo; } String _nextRelease() { var current = RegExp(r'release_(\d+)').matchAsPrefix(lastReleaseName)!.group(1); var val = int.parse(current!) + 1; return '$val.0'; }
flutter-intellij/tool/plugin/lib/util.dart/0
{'file_path': 'flutter-intellij/tool/plugin/lib/util.dart', 'repo_id': 'flutter-intellij', 'token_count': 1863}
name: flutter_masked_text description: Masked text input for flutter. version: 0.8.1 author: Ben-hur Santos Ott <ben-hur@outlook.com> homepage: https://github.com/benhurott/flutter-masked-text dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter environment: sdk: '>=1.23.0 <3.0.0' # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec # The following section is specific to Flutter. flutter: # To add assets to your package, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # # For details regarding assets in packages, see # https://flutter.io/assets-and-images/#from-packages # # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.io/assets-and-images/#resolution-aware. # To add custom fonts to your package, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts in packages, see # https://flutter.io/custom-fonts/#from-packages
flutter-masked-text/pubspec.yaml/0
{'file_path': 'flutter-masked-text/pubspec.yaml', 'repo_id': 'flutter-masked-text', 'token_count': 664}
class ConnectivityRepository { Future<bool> isConnected() async { throw UnsupportedError('dont run this file.dart'); } }
flutter-notes-app/lib/base/repositories/connectivity/connectivity_repository_stub.dart/0
{'file_path': 'flutter-notes-app/lib/base/repositories/connectivity/connectivity_repository_stub.dart', 'repo_id': 'flutter-notes-app', 'token_count': 42}
import 'package:flutter/material.dart'; class AppColors { static const Color primary = Color(0xff16b9fd); static const Color primaryOption2 = Color(0xff03569b); static const Color primaryOption3 = Color(0xffd23156); static const Color primaryOption4 = Color(0xff13d0c1); static const Color primaryOption5 = Color(0xffe5672f); static const Color primaryOption6 = Color(0xffb73d99); static const Color white = Color(0xffffffff); static const Color white50 = Color(0x88ffffff); static const Color grayDark = Color(0xffeaeaea); static const Color gray = Color(0xfff3f3f3); static const Color text = Color(0xff000000); static const Color text50 = Color(0x88000000); static const Color black = Color(0xff001424); static const Color black50 = Color(0x88001424); static const Color blackLight = Color(0xff011f35); static List<Color> primaryColorOptions = const [ primary, primaryOption2, primaryOption3, primaryOption4, primaryOption5, primaryOption6, ]; static Color getShade(Color color, {bool darker = false, double value = .1}) { assert(value >= 0 && value <= 1); final hsl = HSLColor.fromColor(color); final hslDark = hsl.withLightness( (darker ? (hsl.lightness - value) : (hsl.lightness + value)) .clamp(0.0, 1.0)); return hslDark.toColor(); } static MaterialColor getMaterialColorFromColor(Color color) { Map<int, Color> _colorShades = { 50: getShade(color, value: 0.5), 100: getShade(color, value: 0.4), 200: getShade(color, value: 0.3), 300: getShade(color, value: 0.2), 400: getShade(color, value: 0.1), 500: color, //Primary value 600: getShade(color, value: 0.1, darker: true), 700: getShade(color, value: 0.15, darker: true), 800: getShade(color, value: 0.2, darker: true), 900: getShade(color, value: 0.25, darker: true), }; return MaterialColor(color.value, _colorShades); } }
flutter-theme-switcher/lib/presentation/styles/app_colors.dart/0
{'file_path': 'flutter-theme-switcher/lib/presentation/styles/app_colors.dart', 'repo_id': 'flutter-theme-switcher', 'token_count': 735}
import 'package:flutter/material.dart'; import 'package:flutter_tutorials/data/app_data.dart'; class ScrollPhysicsThreadHome extends StatelessWidget { static const String routeName = 'scroll-physics-thread-home'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'ScrollPhysics Types w/ Examples', style: Theme.of(context).textTheme.subtitle1!.copyWith(color: Colors.white), ), ), body: ListView.builder( itemCount: AppData.scrollPhysicsTypes.length, itemBuilder: (c, i) => InkWell( onTap: () => Navigator.of(context).pushNamed(AppData.scrollPhysicsTypes[i].pageRoute), child: Container( padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 20), decoration: BoxDecoration( border: Border( bottom: BorderSide(color: Theme.of(context).dividerColor), ), ), child: Text( AppData.scrollPhysicsTypes[i].title, style: Theme.of(context).textTheme.headline6, ), ), ), ), ); } }
flutter-tutorials/lib/scroll-physics-thread/scroll_physics_thread_home.dart/0
{'file_path': 'flutter-tutorials/lib/scroll-physics-thread/scroll_physics_thread_home.dart', 'repo_id': 'flutter-tutorials', 'token_count': 539}
import 'package:flutter/material.dart'; import 'package:playground/playground/shapes_shaders.dart'; class PlaygroundPage extends StatelessWidget { const PlaygroundPage({super.key}); @override Widget build(BuildContext context) { return const Scaffold( body: ShapesShaders(), ); } }
flutter-world-of-shaders/examples/playground/lib/playground/playground_page.dart/0
{'file_path': 'flutter-world-of-shaders/examples/playground/lib/playground/playground_page.dart', 'repo_id': 'flutter-world-of-shaders', 'token_count': 104}
changelog: exclude: authors: - engine-flutter-autoroll - fluttergithubbot labels: - passed first triage - passed secondary triage categories: - title: Framework labels: - framework - title: Tooling labels: - tool - title: MacOS labels: - platform-mac
flutter/.github/release.yml/0
{'file_path': 'flutter/.github/release.yml', 'repo_id': 'flutter', 'token_count': 155}
#!/usr/bin/env bash # 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. # ---------------------------------- NOTE ---------------------------------- # # # Please keep the logic in this file consistent with the logic in the # `dart.bat` script in the same directory to ensure that Flutter & Dart continue # to work across all platforms! # # -------------------------------------------------------------------------- # set -e # Needed because if it is set, cd may print the path it changed to. unset CDPATH # On Mac OS, readlink -f doesn't work, so follow_links traverses the path one # link at a time, and then cds into the link destination and find out where it # ends up. # # The returned filesystem path must be a format usable by Dart's URI parser, # since the Dart command line tool treats its argument as a file URI, not a # filename. For instance, multiple consecutive slashes should be reduced to a # single slash, since double-slashes indicate a URI "authority", and these are # supposed to be filenames. There is an edge case where this will return # multiple slashes: when the input resolves to the root directory. However, if # that were the case, we wouldn't be running this shell, so we don't do anything # about it. # # The function is enclosed in a subshell to avoid changing the working directory # of the caller. function follow_links() ( cd -P "$(dirname -- "$1")" file="$PWD/$(basename -- "$1")" while [[ -h "$file" ]]; do cd -P "$(dirname -- "$file")" file="$(readlink -- "$file")" cd -P "$(dirname -- "$file")" file="$PWD/$(basename -- "$file")" done echo "$file" ) PROG_NAME="$(follow_links "${BASH_SOURCE[0]}")" BIN_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)" OS="$(uname -s)" # If we're on Windows, invoke the batch script instead to get proper locking. if [[ $OS =~ MINGW.* || $OS =~ CYGWIN.* || $OS =~ MSYS.* ]]; then exec "${BIN_DIR}/dart.bat" "$@" fi # To define `shared::execute()` function source "$BIN_DIR/internal/shared.sh" shared::execute "$@"
flutter/bin/dart/0
{'file_path': 'flutter/bin/dart', 'repo_id': 'flutter', 'token_count': 638}
// 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 HeavyGridViewPage extends StatelessWidget { const HeavyGridViewPage({super.key}); @override Widget build(BuildContext context) { return GridView.builder( itemCount: 1000, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemBuilder: (BuildContext context, int index) => HeavyWidget(index), ).build(context); } } class HeavyWidget extends StatelessWidget { HeavyWidget(this.index) : super(key: ValueKey<int>(index)); final int index; final List<int> _weight = List<int>.filled(1000000, 0); @override Widget build(BuildContext context) { return SizedBox( width: 200, height: 200, child: Text('$index: ${_weight.length}'), ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/heavy_grid_view.dart/0
{'file_path': 'flutter/dev/benchmarks/macrobenchmarks/lib/src/heavy_grid_view.dart', 'repo_id': 'flutter', 'token_count': 316}
// 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 'recorder.dart'; /// Measures how expensive it is to construct material checkboxes. /// /// Creates a 10x10 grid of tristate checkboxes. class BenchBuildMaterialCheckbox extends WidgetBuildRecorder { BenchBuildMaterialCheckbox() : super(name: benchmarkName); static const String benchmarkName = 'build_material_checkbox'; static bool? _isChecked; @override Widget createWidget() { return Directionality( textDirection: TextDirection.ltr, child: Material( child: Column( children: List<Widget>.generate(10, (int i) { return _buildRow(); }), ), ), ); } Row _buildRow() { if (_isChecked == null) { _isChecked = true; } else if (_isChecked!) { _isChecked = false; } else { _isChecked = null; } return Row( children: List<Widget>.generate(10, (int i) { return Expanded( child: Checkbox( value: _isChecked, tristate: true, onChanged: (bool? newValue) { // Intentionally empty. }, ), ); }), ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_build_material_checkbox.dart/0
{'file_path': 'flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_build_material_checkbox.dart', 'repo_id': 'flutter', 'token_count': 563}
// 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/widgets.dart'; import 'recorder.dart'; import 'test_data.dart'; /// Creates several list views containing text items, then continuously scrolls /// them up and down. /// /// Measures our ability to lazily render virtually infinitely big content. class BenchSimpleLazyTextScroll extends WidgetRecorder { BenchSimpleLazyTextScroll() : super(name: benchmarkName); static const String benchmarkName = 'bench_simple_lazy_text_scroll'; @override Widget createWidget() { return const Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ Flexible( child: _TestScrollingWidget( initialScrollOffset: 0, scrollDistance: 300, scrollDuration: Duration(seconds: 1), ), ), Flexible( child: _TestScrollingWidget( initialScrollOffset: 1000, scrollDistance: 500, scrollDuration: Duration(milliseconds: 1500), ), ), Flexible( child: _TestScrollingWidget( initialScrollOffset: 2000, scrollDistance: 700, scrollDuration: Duration(milliseconds: 2000), ), ), ], ), ); } } class _TestScrollingWidget extends StatefulWidget { const _TestScrollingWidget({ required this.initialScrollOffset, required this.scrollDistance, required this.scrollDuration, }); final double initialScrollOffset; final double scrollDistance; final Duration scrollDuration; @override State<StatefulWidget> createState() { return _TestScrollingWidgetState(); } } class _TestScrollingWidgetState extends State<_TestScrollingWidget> { late ScrollController scrollController; @override void initState() { super.initState(); scrollController = ScrollController( initialScrollOffset: widget.initialScrollOffset, ); // Without the timer the animation doesn't begin. Timer.run(() async { bool forward = true; while (true) { await scrollController.animateTo( forward ? widget.initialScrollOffset + widget.scrollDistance : widget.initialScrollOffset, curve: Curves.linear, duration: widget.scrollDuration, ); forward = !forward; } }); } @override void dispose() { scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ListView.builder( controller: scrollController, itemCount: 10000, itemBuilder: (BuildContext context, int index) { return Text(lipsum[index % lipsum.length]); }, ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_simple_lazy_text_scroll.dart/0
{'file_path': 'flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_simple_lazy_text_scroll.dart', 'repo_id': 'flutter', 'token_count': 1144}
// 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:macrobenchmarks/common.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; typedef DriverTestCallBack = Future<void> Function(FlutterDriver driver); Future<void> runDriverTestForRoute(String routeName, DriverTestCallBack body) async { final FlutterDriver driver = await FlutterDriver.connect(); // The slight initial delay avoids starting the timing during a // period of increased load on the device. Without this delay, the // benchmark has greater noise. // See: https://github.com/flutter/flutter/issues/19434 await Future<void>.delayed(const Duration(milliseconds: 250)); await driver.forceGC(); final SerializableFinder scrollable = find.byValueKey(kScrollableName); expect(scrollable, isNotNull); final SerializableFinder button = find.byValueKey(routeName); expect(button, isNotNull); await driver.scrollUntilVisible(scrollable, button, dyScroll: -50.0); await driver.tap(button); await body(driver); driver.close(); } void macroPerfTest( String testName, String routeName, { Duration? pageDelay, Duration duration = const Duration(seconds: 3), Future<void> Function(FlutterDriver driver)? driverOps, Future<void> Function(FlutterDriver driver)? setupOps, }) { test(testName, () async { late Timeline timeline; await runDriverTestForRoute(routeName, (FlutterDriver driver) async { if (pageDelay != null) { // Wait for the page to load await Future<void>.delayed(pageDelay); } if (setupOps != null) { await setupOps(driver); } timeline = await driver.traceAction(() async { final Future<void> durationFuture = Future<void>.delayed(duration); if (driverOps != null) { await driverOps(driver); } await durationFuture; }); }); expect(timeline, isNotNull); final TimelineSummary summary = TimelineSummary.summarize(timeline); await summary.writeTimelineToFile(testName, pretty: true); }, timeout: Timeout.none); }
flutter/dev/benchmarks/macrobenchmarks/test_driver/util.dart/0
{'file_path': 'flutter/dev/benchmarks/macrobenchmarks/test_driver/util.dart', 'repo_id': 'flutter', 'token_count': 727}
// 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 '../common.dart'; const int _kNumIterations = 1000; const int _kNumWarmUp = 100; void main() { assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'."); // Warm up lap for (int i = 0; i < _kNumWarmUp; i += 1) { sumIterable(generateIterableSyncStar()); sumIterable(generateIterableList()); sumIterable(Iterable<int>.generate(100, generate)); } final Stopwatch watch = Stopwatch(); watch.start(); for (int i = 0; i < _kNumIterations; i += 1) { sumIterable(generateIterableSyncStar()); } final int traverseIterableSyncStar = watch.elapsedMicroseconds; watch ..reset() ..start(); for (int i = 0; i < _kNumIterations; i += 1) { sumIterable(generateIterableList()); } final int traverseIterableList = watch.elapsedMicroseconds; watch ..reset() ..start(); for (int i = 0; i < _kNumIterations; i += 1) { sumIterable(Iterable<int>.generate(100, generate)); } final int traverseIterableGenerated = watch.elapsedMicroseconds; watch ..reset() ..start(); final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); const double scale = 1000.0 / _kNumIterations; printer.addResult( description: 'traverseIterableSyncStar', value: traverseIterableSyncStar * scale, unit: 'ns per iteration', name: 'traverseIterableSyncStar_iteration', ); printer.addResult( description: 'traverseIterableList', value: traverseIterableList * scale, unit: 'ns per iteration', name: 'traverseIterableList_iteration', ); printer.addResult( description: 'traverseIterableGenerated', value: traverseIterableGenerated * scale, unit: 'ns per iteration', name: 'traverseIterableGenerated_iteration', ); printer.printToStdout(); } int generate(int index) => index; // Generate an Iterable using a sync* method. Iterable<int> generateIterableSyncStar() sync* { for (int i = 0; i < 100; i++) { yield i; } } // Generate an Iterable using a List. Iterable<int> generateIterableList() { final List<int> items = <int>[]; for (int i = 0; i < 100; i++) { items.add(i); } return items; } int sumIterable(Iterable<int> values) { int result = 0; for (final int value in values) { result += value; } return result; }
flutter/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart/0
{'file_path': 'flutter/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart', 'repo_id': 'flutter', 'token_count': 858}
// 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/material.dart'; import 'package:flutter/scheduler.dart' show timeDilation; import 'package:flutter_driver/driver_extension.dart'; import 'android_platform_view.dart'; void main() { enableFlutterDriverExtension(); runApp( const PlatformViewApp() ); } class PlatformViewApp extends StatefulWidget { const PlatformViewApp({ super.key }); @override PlatformViewAppState createState() => PlatformViewAppState(); } class PlatformViewAppState extends State<PlatformViewApp> { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(), title: 'Advanced Layout', home: const PlatformViewLayout(), ); } void toggleAnimationSpeed() { setState(() { timeDilation = (timeDilation != 1.0) ? 1.0 : 5.0; }); } } class PlatformViewLayout extends StatelessWidget { const PlatformViewLayout({ super.key }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Platform View Scrolling Layout')), body: ListView.builder( key: const Key('platform-views-scroll'), // This key is used by the driver test. itemCount: 200, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(5.0), child: Material( elevation: (index % 5 + 1).toDouble(), color: Colors.white, child: const Stack( children: <Widget> [ DummyPlatformView(), RotationContainer(), ], ), ), ); }, ), ); } } class DummyPlatformView extends StatelessWidget { const DummyPlatformView({super.key}); @override Widget build(BuildContext context) { const String viewType = 'benchmarks/platform_views_layout_hybrid_composition/DummyPlatformView'; late Widget nativeView; if (Platform.isIOS) { nativeView = const UiKitView( viewType: viewType, ); } else if (Platform.isAndroid) { nativeView = const AndroidPlatformView( viewType: viewType, ); } else { assert(false, 'Invalid platform'); } return Container( color: Colors.purple, height: 200.0, width: 300.0, child: nativeView, ); } } class RotationContainer extends StatefulWidget { const RotationContainer({super.key}); @override State<RotationContainer> createState() => _RotationContainerState(); } class _RotationContainerState extends State<RotationContainer> with SingleTickerProviderStateMixin { late AnimationController _rotationController; @override void initState() { super.initState(); _rotationController = AnimationController( vsync: this, duration: const Duration(seconds: 1), value: 1, ); _rotationController.repeat(); } @override void dispose() { _rotationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return RotationTransition( turns: Tween<double>(begin: 0.0, end: 1.0).animate(_rotationController), child: Container( color: Colors.purple, width: 50.0, height: 50.0, ), ); } }
flutter/dev/benchmarks/platform_views_layout_hybrid_composition/lib/main.dart/0
{'file_path': 'flutter/dev/benchmarks/platform_views_layout_hybrid_composition/lib/main.dart', 'repo_id': 'flutter', 'token_count': 1356}
# Options used by the localizations tool ## `arb-dir` sets the input directory. The output directory will match ## the input directory if the output directory is not set. arb-dir: lib/i18n ## `header-file` is the file that contains a custom ## header for each of the generated files. header-file: header.txt ## `output-class` is the name of the localizations class your ## Flutter application will use. The file will need to be ## imported throughout your application. output-class: StockStrings ## `output-localization-file` is the name of the generated file. output-localization-file: stock_strings.dart ## `template-arb-file` describes the template arb file that the tool ## will use to check and validate the remaining arb files when ## generating Flutter's localization files. synthetic-package: false template-arb-file: stocks_en.arb ## setting `nullable-getter` to false generates a non-nullable ## StockStrings getter. This removes the need for adding null checks ## in the Flutter application itself. nullable-getter: false
flutter/dev/benchmarks/test_apps/stocks/l10n.yaml/0
{'file_path': 'flutter/dev/benchmarks/test_apps/stocks/l10n.yaml', 'repo_id': 'flutter', 'token_count': 270}
// 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:path/path.dart' as path; import 'common.dart'; void main() { test('We are in a directory with a space in it', () async { // The Flutter SDK should be in a directory with a space in it, to make sure // our tools support that. final String? expectedName = Platform.environment['FLUTTER_SDK_PATH_WITH_SPACE']; expect(expectedName, 'flutter sdk'); expect(expectedName, contains(' ')); final List<String> parts = path.split(Directory.current.absolute.path); expect(parts.reversed.take(3), <String?>['bots', 'dev', expectedName]); }, skip: true); // https://github.com/flutter/flutter/issues/87285 }
flutter/dev/bots/test/sdk_directory_has_space_test.dart/0
{'file_path': 'flutter/dev/bots/test/sdk_directory_has_space_test.dart', 'repo_id': 'flutter', 'token_count': 268}
include: ../../analysis_options.yaml analyzer: exclude: # Ignore protoc generated files - "lib/src/proto/*" linter: rules: avoid_catches_without_on_clauses: true prefer_relative_imports: true unawaited_futures: true
flutter/dev/conductor/core/analysis_options.yaml/0
{'file_path': 'flutter/dev/conductor/core/analysis_options.yaml', 'repo_id': 'flutter', 'token_count': 96}
// 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:test/test.dart' hide isInstanceOf; export 'package:test/test.dart' hide isInstanceOf; /// A matcher that compares the type of the actual value to the type argument T. TypeMatcher<T> isInstanceOf<T>() => isA<T>();
flutter/dev/customer_testing/test/common.dart/0
{'file_path': 'flutter/dev/customer_testing/test/common.dart', 'repo_id': 'flutter', 'token_count': 118}
// 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_devicelab/framework/devices.dart'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:flutter_devicelab/tasks/integration_tests.dart'; Future<void> main() async { deviceOperatingSystem = DeviceOperatingSystem.macos; await task(() async { await createFlavorsTest().call(); await createIntegrationTestFlavorsTest().call(); await inDirectory('${flutterDirectory.path}/dev/integration_tests/flavors', () async { final StringBuffer stderr = StringBuffer(); await evalFlutter( 'install', canFail: true, stderr: stderr, options: <String>[ '--d', 'macos', '--flavor', 'free' ], ); final String stderrString = stderr.toString(); if (!stderrString.contains('Host and target are the same. Nothing to install.')) { print(stderrString); return TaskResult.failure('Installing a macOS app on macOS should no-op'); } }); return TaskResult.success(null); }); }
flutter/dev/devicelab/bin/tasks/flavors_test_macos.dart/0
{'file_path': 'flutter/dev/devicelab/bin/tasks/flavors_test_macos.dart', 'repo_id': 'flutter', 'token_count': 492}
// 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/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:path/path.dart' as path; Future<void> main() async { await task(() async { section('Copy test Flutter App with watchOS Companion'); final Directory tempDir = Directory.systemTemp .createTempSync('flutter_ios_app_with_extensions_test.'); final Directory projectDir = Directory(path.join(tempDir.path, 'app_with_extensions')); try { mkdir(projectDir); recursiveCopy( Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'ios_app_with_extensions')), projectDir, ); section('Create release build'); // This attempts to build the companion watchOS app. However, the watchOS // SDK is not available in CI and therefore the build will fail. // Check to make sure that the tool attempts to build the companion watchOS app. // See https://github.com/flutter/flutter/pull/94190. await inDirectory(projectDir, () async { final String buildOutput = await evalFlutter( 'build', options: <String>['ios', '--no-codesign', '--release', '--verbose'], ); if (!buildOutput.contains('-destination generic/platform=watchOS')) { print(buildOutput); throw TaskResult.failure('Did not try to get watch build settings'); } }); return TaskResult.success(null); } catch (e) { return TaskResult.failure(e.toString()); } finally { rmTree(tempDir); } }); }
flutter/dev/devicelab/bin/tasks/ios_app_with_extensions_test.dart/0
{'file_path': 'flutter/dev/devicelab/bin/tasks/ios_app_with_extensions_test.dart', 'repo_id': 'flutter', 'token_count': 686}
// 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_devicelab/framework/framework.dart'; /// Smoke test of a task that fails with an exception. Future<void> main() async { await task(() async { throw 'failed'; }); }
flutter/dev/devicelab/bin/tasks/smoke_test_throws.dart/0
{'file_path': 'flutter/dev/devicelab/bin/tasks/smoke_test_throws.dart', 'repo_id': 'flutter', 'token_count': 106}
// 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:path/path.dart' as path; import '../framework/task_result.dart'; import '../framework/utils.dart'; /// Run each benchmark this many times and compute average, min, max. /// /// This must be small enough that we can do all the work in 15 minutes, the /// devicelab deadline. Since there's four different analysis tasks, on average, /// each can have 4 minutes. The tasks currently average a little more than a /// minute, so that allows three runs per task. const int _kRunsPerBenchmark = 3; /// Path to the generated "mega gallery" app. Directory get _megaGalleryDirectory => dir(path.join(Directory.systemTemp.path, 'mega_gallery')); Future<TaskResult> analyzerBenchmarkTask() async { await inDirectory<void>(flutterDirectory, () async { rmTree(_megaGalleryDirectory); mkdirs(_megaGalleryDirectory); await flutter('update-packages'); await dart(<String>['dev/tools/mega_gallery.dart', '--out=${_megaGalleryDirectory.path}']); }); final Map<String, dynamic> data = <String, dynamic>{ ...(await _run(_FlutterRepoBenchmark())).asMap('flutter_repo', 'batch'), ...(await _run(_FlutterRepoBenchmark(watch: true))).asMap('flutter_repo', 'watch'), ...(await _run(_MegaGalleryBenchmark())).asMap('mega_gallery', 'batch'), ...(await _run(_MegaGalleryBenchmark(watch: true))).asMap('mega_gallery', 'watch'), }; return TaskResult.success(data, benchmarkScoreKeys: data.keys.toList()); } class _BenchmarkResult { const _BenchmarkResult(this.mean, this.min, this.max); final double mean; // seconds final double min; // seconds final double max; // seconds Map<String, dynamic> asMap(String benchmark, String mode) { return <String, dynamic>{ '${benchmark}_$mode': mean, '${benchmark}_${mode}_minimum': min, '${benchmark}_${mode}_maximum': max, }; } } abstract class _Benchmark { _Benchmark({this.watch = false}); final bool watch; String get title; Directory get directory; List<String> get options => <String>[ '--benchmark', if (watch) '--watch', ]; Future<double> execute(int iteration, int targetIterations) async { section('Analyze $title ${watch ? 'with watcher' : ''} - ${iteration + 1} / $targetIterations'); final Stopwatch stopwatch = Stopwatch(); await inDirectory<void>(directory, () async { stopwatch.start(); await flutter('analyze', options: options); stopwatch.stop(); }); return stopwatch.elapsedMicroseconds / (1000.0 * 1000.0); } } /// Times how long it takes to analyze the Flutter repository. class _FlutterRepoBenchmark extends _Benchmark { _FlutterRepoBenchmark({super.watch}); @override String get title => 'Flutter repo'; @override Directory get directory => flutterDirectory; @override List<String> get options { return super.options..add('--flutter-repo'); } } /// Times how long it takes to analyze the generated "mega_gallery" app. class _MegaGalleryBenchmark extends _Benchmark { _MegaGalleryBenchmark({super.watch}); @override String get title => 'mega gallery'; @override Directory get directory => _megaGalleryDirectory; } /// Runs `benchmark` several times and reports the results. Future<_BenchmarkResult> _run(_Benchmark benchmark) async { final List<double> results = <double>[]; for (int i = 0; i < _kRunsPerBenchmark; i += 1) { // Delete cached analysis results. rmTree(dir('${Platform.environment['HOME']}/.dartServer')); results.add(await benchmark.execute(i, _kRunsPerBenchmark)); } results.sort(); final double sum = results.fold<double>( 0.0, (double previousValue, double element) => previousValue + element, ); return _BenchmarkResult(sum / results.length, results.first, results.last); }
flutter/dev/devicelab/lib/tasks/analysis.dart/0
{'file_path': 'flutter/dev/devicelab/lib/tasks/analysis.dart', 'repo_id': 'flutter', 'token_count': 1274}
// 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_devicelab/framework/task_result.dart'; import 'common.dart'; void main() { group('TaskResult fromJson', () { test('succeeded', () { final Map<String, dynamic> expectedJson = <String, dynamic>{ 'success': true, 'data': <String, dynamic>{ 'i': 5, 'j': 10, 'not_a_metric': 'something', }, 'benchmarkScoreKeys': <String>['i', 'j'], 'detailFiles': <String>[], }; final TaskResult result = TaskResult.fromJson(expectedJson); expect(result.toJson(), expectedJson); }); test('succeeded with empty data', () { final TaskResult result = TaskResult.fromJson(<String, dynamic>{ 'success': true, }); final Map<String, dynamic> expectedJson = <String, dynamic>{ 'success': true, 'data': null, 'benchmarkScoreKeys': <String>[], 'detailFiles': <String>[], }; expect(result.toJson(), expectedJson); }); test('failed', () { final Map<String, dynamic> expectedJson = <String, dynamic>{ 'success': false, 'reason': 'failure message', }; final TaskResult result = TaskResult.fromJson(expectedJson); expect(result.toJson(), expectedJson); }); }); }
flutter/dev/devicelab/test/task_result_test.dart/0
{'file_path': 'flutter/dev/devicelab/test/task_result_test.dart', 'repo_id': 'flutter', 'token_count': 601}
// 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 name of the route containing the text field tests. const String textFieldRoute = 'textField'; /// The string supplied to the [ValueKey] for the normal text field. const String normalTextFieldKeyValue = 'textFieldNormal'; /// The string supplied to the [ValueKey] for the password text field. const String passwordTextFieldKeyValue = 'passwordField'; /// The string supplied to the [ValueKey] for the page navigation back button. const String backButtonKeyValue = 'back';
flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/text_field_constants.dart/0
{'file_path': 'flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/text_field_constants.dart', 'repo_id': 'flutter', 'token_count': 159}
// 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 '../../gallery/demo.dart'; class CupertinoAlertDemo extends StatefulWidget { const CupertinoAlertDemo({super.key}); static const String routeName = '/cupertino/alert'; @override State<CupertinoAlertDemo> createState() => _CupertinoAlertDemoState(); } class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> { String? lastSelectedValue; void showDemoDialog({required BuildContext context, Widget? child}) { showCupertinoDialog<String>( context: context, builder: (BuildContext context) => child!, ).then((String? value) { if (value != null) { setState(() { lastSelectedValue = value; }); } }); } void showDemoActionSheet({required BuildContext context, Widget? child}) { showCupertinoModalPopup<String>( context: context, builder: (BuildContext context) => child!, ).then((String? value) { if (value != null) { setState(() { lastSelectedValue = value; }); } }); } @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Alerts'), // 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(CupertinoAlertDemo.routeName), ), child: DefaultTextStyle( style: CupertinoTheme.of(context).textTheme.textStyle, child: Builder( builder: (BuildContext context) { return Stack( alignment: Alignment.center, children: <Widget>[ CupertinoScrollbar( child: ListView( primary: true, // Add more padding to the normal safe area. padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0) + MediaQuery.of(context).padding, children: <Widget>[ CupertinoButton.filled( child: const Text('Alert'), onPressed: () => _onAlertPress(context), ), const Padding(padding: EdgeInsets.all(8.0)), CupertinoButton.filled( padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), child: const Text('Alert with Title'), onPressed: () => _onAlertWithTitlePress(context), ), const Padding(padding: EdgeInsets.all(8.0)), CupertinoButton.filled( padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), child: const Text('Alert with Buttons'), onPressed: () => _onAlertWithButtonsPress(context), ), const Padding(padding: EdgeInsets.all(8.0)), CupertinoButton.filled( padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), child: const Text('Alert Buttons Only'), onPressed: () { showDemoDialog( context: context, child: const CupertinoDessertDialog(), ); }, ), const Padding(padding: EdgeInsets.all(8.0)), CupertinoButton.filled( padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), child: const Text('Action Sheet'), onPressed: () => _onActionSheetPress(context), ), ], ), ), if (lastSelectedValue != null) Positioned( bottom: 32.0, child: Text('You selected: $lastSelectedValue'), ), ], ); }, ), ), ); } void _onAlertPress(BuildContext context) { showDemoDialog( context: context, child: CupertinoAlertDialog( title: const Text('Discard draft?'), actions: <Widget>[ CupertinoDialogAction( isDestructiveAction: true, child: const Text('Discard'), onPressed: () => Navigator.pop(context, 'Discard'), ), CupertinoDialogAction( isDefaultAction: true, child: const Text('Cancel'), onPressed: () => Navigator.pop(context, 'Cancel'), ), ], ), ); } void _onAlertWithTitlePress(BuildContext context) { showDemoDialog( context: context, child: CupertinoAlertDialog( title: const Text('Allow "Maps" to access your location while you are using the app?'), content: const Text('Your current location will be displayed on the map and used ' 'for directions, nearby search results, and estimated travel times.'), actions: <Widget>[ CupertinoDialogAction( child: const Text("Don't Allow"), onPressed: () => Navigator.pop(context, 'Disallow'), ), CupertinoDialogAction( child: const Text('Allow'), onPressed: () => Navigator.pop(context, 'Allow'), ), ], ), ); } void _onAlertWithButtonsPress(BuildContext context) { showDemoDialog( context: context, child: const CupertinoDessertDialog( title: Text('Select Favorite Dessert'), content: Text('Please select your favorite type of dessert from the ' 'list below. Your selection will be used to customize the suggested ' 'list of eateries in your area.'), ), ); } void _onActionSheetPress(BuildContext context) { showDemoActionSheet( context: context, child: CupertinoActionSheet( title: const Text('Favorite Dessert'), message: const Text('Please select the best dessert from the options below.'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('Profiteroles'), onPressed: () => Navigator.pop(context, 'Profiteroles'), ), CupertinoActionSheetAction( child: const Text('Cannolis'), onPressed: () => Navigator.pop(context, 'Cannolis'), ), CupertinoActionSheetAction( child: const Text('Trifle'), onPressed: () => Navigator.pop(context, 'Trifle'), ), ], cancelButton: CupertinoActionSheetAction( isDefaultAction: true, child: const Text('Cancel'), onPressed: () => Navigator.pop(context, 'Cancel'), ), ), ); } } class CupertinoDessertDialog extends StatelessWidget { const CupertinoDessertDialog({super.key, this.title, this.content}); final Widget? title; final Widget? content; @override Widget build(BuildContext context) { return CupertinoAlertDialog( title: title, content: content, actions: <Widget>[ CupertinoDialogAction( child: const Text('Cheesecake'), onPressed: () { Navigator.pop(context, 'Cheesecake'); }, ), CupertinoDialogAction( child: const Text('Tiramisu'), onPressed: () { Navigator.pop(context, 'Tiramisu'); }, ), CupertinoDialogAction( child: const Text('Apple Pie'), onPressed: () { Navigator.pop(context, 'Apple Pie'); }, ), CupertinoDialogAction( child: const Text("Devil's food cake"), onPressed: () { Navigator.pop(context, "Devil's food cake"); }, ), CupertinoDialogAction( child: const Text('Banana Split'), onPressed: () { Navigator.pop(context, 'Banana Split'); }, ), CupertinoDialogAction( child: const Text('Oatmeal Cookie'), onPressed: () { Navigator.pop(context, 'Oatmeal Cookies'); }, ), CupertinoDialogAction( child: const Text('Chocolate Brownie'), onPressed: () { Navigator.pop(context, 'Chocolate Brownies'); }, ), CupertinoDialogAction( isDestructiveAction: true, child: const Text('Cancel'), onPressed: () { Navigator.pop(context, 'Cancel'); }, ), ], ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart/0
{'file_path': 'flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart', 'repo_id': 'flutter', 'token_count': 4370}
// 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 '../../gallery/demo.dart'; class MenuDemo extends StatefulWidget { const MenuDemo({ super.key }); static const String routeName = '/material/menu'; @override MenuDemoState createState() => MenuDemoState(); } class MenuDemoState extends State<MenuDemo> { final String _simpleValue1 = 'Menu item value one'; final String _simpleValue2 = 'Menu item value two'; final String _simpleValue3 = 'Menu item value three'; String? _simpleValue; final String _checkedValue1 = 'One'; final String _checkedValue2 = 'Two'; final String _checkedValue3 = 'Free'; final String _checkedValue4 = 'Four'; late List<String> _checkedValues; @override void initState() { super.initState(); _simpleValue = _simpleValue2; _checkedValues = <String>[_checkedValue3]; } void showInSnackBar(String value) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text(value), )); } void showMenuSelection(String value) { if (<String>[_simpleValue1, _simpleValue2, _simpleValue3].contains(value)) { setState(() => _simpleValue = value); } showInSnackBar('You selected: $value'); } void showCheckedMenuSelections(String value) { if (_checkedValues.contains(value)) { _checkedValues.remove(value); } else { _checkedValues.add(value); } showInSnackBar('Checked $_checkedValues'); } bool isChecked(String value) => _checkedValues.contains(value); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Menus'), actions: <Widget>[ MaterialDemoDocumentationButton(MenuDemo.routeName), PopupMenuButton<String>( onSelected: showMenuSelection, itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[ const PopupMenuItem<String>( value: 'Toolbar menu', child: Text('Toolbar menu'), ), const PopupMenuItem<String>( value: 'Right here', child: Text('Right here'), ), const PopupMenuItem<String>( value: 'Hooray!', child: Text('Hooray!'), ), ], ), ], ), body: ListTileTheme( iconColor: Theme.of(context).brightness == Brightness.light ? Colors.grey[600] : Colors.grey[500], child: ListView( padding: kMaterialListPadding, children: <Widget>[ // Pressing the PopupMenuButton on the right of this item shows // a simple menu with one disabled item. Typically the contents // of this "contextual menu" would reflect the app's state. ListTile( title: const Text('An item with a context menu button'), trailing: PopupMenuButton<String>( padding: EdgeInsets.zero, onSelected: showMenuSelection, itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[ PopupMenuItem<String>( value: _simpleValue1, child: const Text('Context menu item one'), ), const PopupMenuItem<String>( enabled: false, child: Text('A disabled menu item'), ), PopupMenuItem<String>( value: _simpleValue3, child: const Text('Context menu item three'), ), ], ), ), // Pressing the PopupMenuButton on the right of this item shows // a menu whose items have text labels and icons and a divider // That separates the first three items from the last one. ListTile( title: const Text('An item with a sectioned menu'), trailing: PopupMenuButton<String>( padding: EdgeInsets.zero, onSelected: showMenuSelection, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'Preview', child: ListTile( leading: Icon(Icons.visibility), title: Text('Preview'), ), ), const PopupMenuItem<String>( value: 'Share', child: ListTile( leading: Icon(Icons.person_add), title: Text('Share'), ), ), const PopupMenuItem<String>( value: 'Get Link', child: ListTile( leading: Icon(Icons.link), title: Text('Get link'), ), ), const PopupMenuDivider(), const PopupMenuItem<String>( value: 'Remove', child: ListTile( leading: Icon(Icons.delete), title: Text('Remove'), ), ), ], ), ), // This entire list item is a PopupMenuButton. Tapping anywhere shows // a menu whose current value is highlighted and aligned over the // list item's center line. PopupMenuButton<String>( padding: EdgeInsets.zero, initialValue: _simpleValue, onSelected: showMenuSelection, child: ListTile( title: const Text('An item with a simple menu'), subtitle: Text(_simpleValue!), ), itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[ PopupMenuItem<String>( value: _simpleValue1, child: Text(_simpleValue1), ), PopupMenuItem<String>( value: _simpleValue2, child: Text(_simpleValue2), ), PopupMenuItem<String>( value: _simpleValue3, child: Text(_simpleValue3), ), ], ), // Pressing the PopupMenuButton on the right of this item shows a menu // whose items have checked icons that reflect this app's state. ListTile( title: const Text('An item with a checklist menu'), trailing: PopupMenuButton<String>( padding: EdgeInsets.zero, onSelected: showCheckedMenuSelections, itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[ CheckedPopupMenuItem<String>( value: _checkedValue1, checked: isChecked(_checkedValue1), child: Text(_checkedValue1), ), CheckedPopupMenuItem<String>( value: _checkedValue2, enabled: false, checked: isChecked(_checkedValue2), child: Text(_checkedValue2), ), CheckedPopupMenuItem<String>( value: _checkedValue3, checked: isChecked(_checkedValue3), child: Text(_checkedValue3), ), CheckedPopupMenuItem<String>( value: _checkedValue4, checked: isChecked(_checkedValue4), child: Text(_checkedValue4), ), ], ), ), ], ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart/0
{'file_path': 'flutter/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart', 'repo_id': 'flutter', 'token_count': 4099}
// 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'; const String _kStartTag = '// START '; const String _kEndTag = '// END'; Map<String?, String>? _exampleCode; Future<String?> getExampleCode(String? tag, AssetBundle bundle) async { if (_exampleCode == null) { await _parseExampleCode(bundle); } return _exampleCode![tag]; } Future<void> _parseExampleCode(AssetBundle bundle) async { final String code = await bundle.loadString('lib/gallery/example_code.dart'); _exampleCode = <String?, String>{}; final List<String> lines = code.split('\n'); List<String>? codeBlock; String? codeTag; for (final String line in lines) { if (codeBlock == null) { // Outside a block. if (line.startsWith(_kStartTag)) { // Starting a new code block. codeBlock = <String>[]; codeTag = line.substring(_kStartTag.length).trim(); } else { // Just skipping the line. } } else { // Inside a block. if (line.startsWith(_kEndTag)) { // Add the block. _exampleCode![codeTag] = codeBlock.join('\n'); codeBlock = null; codeTag = null; } else { // Add to the current block // trimRight() to remove any \r on Windows // without removing any useful indentation codeBlock.add(line.trimRight()); } } } }
flutter/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart/0
{'file_path': 'flutter/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart', 'repo_id': 'flutter', 'token_count': 573}
// 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/gallery/app.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; } // Regression test for https://github.com/flutter/flutter/pull/5168 testWidgets('Pesto appbar heroics', (WidgetTester tester) async { await tester.pumpWidget( // The bug only manifests itself when the screen's orientation is portrait const Center( child: SizedBox( width: 450.0, height: 800.0, child: GalleryApp(testMode: true), ), ) ); await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame await tester.tap(find.text('Studies')); await tester.pumpAndSettle(); await tester.tap(find.text('Pesto')); await tester.pumpAndSettle(); await tester.tap(find.text('Roasted Chicken')); await tester.pumpAndSettle(); await tester.drag(find.text('Roasted Chicken'), const Offset(0.0, -300.0)); await tester.pumpAndSettle(); Navigator.pop(find.byType(Scaffold).evaluate().single); await tester.pumpAndSettle(); }); testWidgets('Pesto can be scrolled all the way down', (WidgetTester tester) async { await tester.pumpWidget(const GalleryApp(testMode: true)); await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame await tester.tap(find.text('Studies')); await tester.pumpAndSettle(); await tester.tap(find.text('Pesto')); await tester.pumpAndSettle(); await tester.fling(find.text('Roasted Chicken'), const Offset(0.0, -200.0), 10000.0); await tester.pumpAndSettle(); // start and finish fling expect(find.text('Spanakopita'), findsOneWidget); }); }
flutter/dev/integration_tests/flutter_gallery/test/pesto_test.dart/0
{'file_path': 'flutter/dev/integration_tests/flutter_gallery/test/pesto_test.dart', 'repo_id': 'flutter', 'token_count': 804}
// 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:html' as html; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:meta/dart2js.dart'; // Tests that the framework prints stack traces in all build modes. // // Regression test for https://github.com/flutter/flutter/issues/68616. // // See also `dev/integration_tests/web/lib/stack_trace.dart` that tests the // framework's ability to parse stack traces in all build modes. Future<void> main() async { final StringBuffer errorMessage = StringBuffer(); debugPrint = (String? message, { int? wrapWidth }) { errorMessage.writeln(message); }; runApp(const ThrowingWidget()); // Let the framework flush error messages. await Future<void>.delayed(Duration.zero); final StringBuffer output = StringBuffer(); if (_errorMessageFormattedCorrectly(errorMessage.toString())) { output.writeln('--- TEST SUCCEEDED ---'); } else { output.writeln('--- UNEXPECTED ERROR MESSAGE FORMAT ---'); output.writeln(errorMessage); output.writeln('--- TEST FAILED ---'); } print(output); html.HttpRequest.request( '/test-result', method: 'POST', sendData: '$output', ); } bool _errorMessageFormattedCorrectly(String errorMessage) { if (!errorMessage.contains('Test error message')) { return false; } // In release mode symbols are minified. No sense testing the contents of the stack trace. if (kReleaseMode) { return true; } const List<String> expectedFunctions = <String>[ 'topLevelFunction', 'secondLevelFunction', 'thirdLevelFunction', ]; return expectedFunctions.every(errorMessage.contains); } class ThrowingWidget extends StatefulWidget { const ThrowingWidget({super.key}); @override State<ThrowingWidget> createState() => _ThrowingWidgetState(); } class _ThrowingWidgetState extends State<ThrowingWidget> { @override void initState() { super.initState(); topLevelFunction(); } @override Widget build(BuildContext context) { return Container(); } } @noInline void topLevelFunction() { secondLevelFunction(); } @noInline void secondLevelFunction() { thirdLevelFunction(); } @noInline void thirdLevelFunction() { throw Exception('Test error message'); }
flutter/dev/integration_tests/web/lib/framework_stack_trace.dart/0
{'file_path': 'flutter/dev/integration_tests/web/lib/framework_stack_trace.dart', 'repo_id': 'flutter', 'token_count': 751}
// 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:html' as html; import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Scroll Wheel Test', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'RobotoMono', visualDensity: VisualDensity.adaptivePlatformDensity, ), home: const MyHomePage(title: 'Flutter Scroll Wheel Test'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView.builder( itemCount: 1000, itemBuilder: (BuildContext context, int index) => Padding( padding: const EdgeInsets.all(20), child: Container( height: 100, color: Colors.lightBlue, child: Center( child: Text('Item $index'), ), ), ), ), floatingActionButton: FloatingActionButton.extended( key: const Key('scroll-button'), onPressed: () { const int centerX = 100; //html.window.innerWidth ~/ 2; const int centerY = 100; //html.window.innerHeight ~/ 2; dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); }, label: const Text('Scroll'), icon: const Icon(Icons.thumb_up), ), ); } } abstract class DeltaMode { static const int kPixel = 0x00; static const int kLine = 0x01; static const int kPage = 0x02; } void dispatchMouseWheelEvent(int mouseX, int mouseY, int deltaMode, double deltaX, double deltaY) { final html.EventTarget target = html.document.elementFromPoint(mouseX, mouseY)!; target.dispatchEvent(html.MouseEvent('mouseover', screenX: mouseX, screenY: mouseY, clientX: mouseX, clientY: mouseY, )); target.dispatchEvent(html.MouseEvent('mousemove', screenX: mouseX, screenY: mouseY, clientX: mouseX, clientY: mouseY, )); target.dispatchEvent(html.WheelEvent('wheel', screenX: mouseX, screenY: mouseY, clientX: mouseX, clientY: mouseY, deltaMode: deltaMode, deltaX : deltaX, deltaY : deltaY, )); }
flutter/dev/integration_tests/web_e2e_tests/lib/scroll_wheel_main.dart/0
{'file_path': 'flutter/dev/integration_tests/web_e2e_tests/lib/scroll_wheel_main.dart', 'repo_id': 'flutter', 'token_count': 1212}
// 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 'package:flutter/material.dart'; class ExampleDragTarget extends StatefulWidget { const ExampleDragTarget({super.key}); @override ExampleDragTargetState createState() => ExampleDragTargetState(); } class ExampleDragTargetState extends State<ExampleDragTarget> { Color _color = Colors.grey; void _handleAccept(Color data) { setState(() { _color = data; }); } @override Widget build(BuildContext context) { return DragTarget<Color>( onAccept: _handleAccept, builder: (BuildContext context, List<Color?> data, List<dynamic> rejectedData) { return Container( height: 100.0, margin: const EdgeInsets.all(10.0), decoration: BoxDecoration( color: data.isEmpty ? _color : Colors.grey.shade200, border: Border.all( width: 3.0, color: data.isEmpty ? Colors.white : Colors.blue, ), ), ); }, ); } } class Dot extends StatefulWidget { const Dot({ super.key, this.color, this.size, this.child, this.tappable = false }); final Color? color; final double? size; final Widget? child; final bool tappable; @override DotState createState() => DotState(); } class DotState extends State<Dot> { int taps = 0; @override Widget build(BuildContext context) { return GestureDetector( onTap: widget.tappable ? () { setState(() { taps += 1; }); } : null, child: Container( width: widget.size, height: widget.size, decoration: BoxDecoration( color: widget.color, border: Border.all(width: taps.toDouble()), shape: BoxShape.circle, ), child: widget.child, ), ); } } class ExampleDragSource extends StatelessWidget { const ExampleDragSource({ super.key, this.color, this.heavy = false, this.under = true, this.child, }); final Color? color; final bool heavy; final bool under; final Widget? child; static const double kDotSize = 50.0; static const double kHeavyMultiplier = 1.5; static const double kFingerSize = 50.0; @override Widget build(BuildContext context) { double size = kDotSize; if (heavy) { size *= kHeavyMultiplier; } final Widget contents = DefaultTextStyle( style: Theme.of(context).textTheme.bodyMedium!, textAlign: TextAlign.center, child: Dot( color: color, size: size, child: Center(child: child), ), ); Widget feedback = Opacity( opacity: 0.75, child: contents, ); Offset feedbackOffset; DragAnchorStrategy dragAnchorStrategy; if (!under) { feedback = Transform( transform: Matrix4.identity() ..translate(-size / 2.0, -(size / 2.0 + kFingerSize)), child: feedback, ); feedbackOffset = const Offset(0.0, -kFingerSize); dragAnchorStrategy = pointerDragAnchorStrategy; } else { feedbackOffset = Offset.zero; dragAnchorStrategy = childDragAnchorStrategy; } if (heavy) { return LongPressDraggable<Color>( data: color, feedback: feedback, feedbackOffset: feedbackOffset, dragAnchorStrategy: dragAnchorStrategy, child: contents, ); } else { return Draggable<Color>( data: color, feedback: feedback, feedbackOffset: feedbackOffset, dragAnchorStrategy: dragAnchorStrategy, child: contents, ); } } } class DashOutlineCirclePainter extends CustomPainter { const DashOutlineCirclePainter(); static const int segments = 17; static const double deltaTheta = math.pi * 2 / segments; // radians static const double segmentArc = deltaTheta / 2.0; // radians static const double startOffset = 1.0; // radians @override void paint(Canvas canvas, Size size) { final double radius = size.shortestSide / 2.0; final Paint paint = Paint() ..color = const Color(0xFF000000) ..style = PaintingStyle.stroke ..strokeWidth = radius / 10.0; final Path path = Path(); final Rect box = Offset.zero & size; for (double theta = 0.0; theta < math.pi * 2.0; theta += deltaTheta) { path.addArc(box, theta + startOffset, segmentArc); } canvas.drawPath(path, paint); } @override bool shouldRepaint(DashOutlineCirclePainter oldDelegate) => false; } class MovableBall extends StatelessWidget { const MovableBall(this.position, this.ballPosition, this.callback, {super.key}); final int position; final int ballPosition; final ValueChanged<int> callback; static final GlobalKey kBallKey = GlobalKey(); static const double kBallSize = 50.0; @override Widget build(BuildContext context) { final Widget ball = DefaultTextStyle( style: Theme.of(context).primaryTextTheme.bodyMedium!, textAlign: TextAlign.center, child: Dot( key: kBallKey, color: Colors.blue.shade700, size: kBallSize, tappable: true, child: const Center(child: Text('BALL')), ), ); const Widget dashedBall = SizedBox( width: kBallSize, height: kBallSize, child: CustomPaint( painter: DashOutlineCirclePainter() ), ); if (position == ballPosition) { return Draggable<bool>( data: true, childWhenDragging: dashedBall, feedback: ball, maxSimultaneousDrags: 1, child: ball, ); } else { return DragTarget<bool>( onAccept: (bool data) { callback(position); }, builder: (BuildContext context, List<bool?> accepted, List<dynamic> rejected) { return dashedBall; }, ); } } } class DragAndDropApp extends StatefulWidget { const DragAndDropApp({super.key}); @override DragAndDropAppState createState() => DragAndDropAppState(); } class DragAndDropAppState extends State<DragAndDropApp> { int position = 1; void moveBall(int newPosition) { setState(() { position = newPosition; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Drag and Drop Flutter Demo'), ), body: Column( children: <Widget>[ Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ ExampleDragSource( color: Colors.yellow.shade300, child: const Text('under'), ), ExampleDragSource( color: Colors.green.shade300, under: false, heavy: true, child: const Text('long-press above'), ), ExampleDragSource( color: Colors.indigo.shade300, under: false, child: const Text('above'), ), ], ), ), const Expanded( child: Row( children: <Widget>[ Expanded(child: ExampleDragTarget()), Expanded(child: ExampleDragTarget()), Expanded(child: ExampleDragTarget()), Expanded(child: ExampleDragTarget()), ], ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ MovableBall(1, position, moveBall), MovableBall(2, position, moveBall), MovableBall(3, position, moveBall), ], ), ), ], ), ); } } void main() { runApp(const MaterialApp( title: 'Drag and Drop Flutter Demo', home: DragAndDropApp(), )); }
flutter/dev/manual_tests/lib/drag_and_drop.dart/0
{'file_path': 'flutter/dev/manual_tests/lib/drag_and_drop.dart', 'repo_id': 'flutter', 'token_count': 3492}
// 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_test/flutter_test.dart'; import 'package:manual_tests/color_testing_demo.dart' as color_testing_demo; import 'mock_image_http.dart'; void main() { testWidgets('Color testing demo smoke test', (WidgetTester tester) async { HttpOverrides.runZoned<Future<void>>(() async { color_testing_demo.main(); // builds the app and schedules a frame but doesn't trigger one await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame await tester.dragFrom(const Offset(0.0, 500.0), Offset.zero); // scrolls down await tester.pump(); await tester.dragFrom(const Offset(0.0, 500.0), Offset.zero); // scrolls down await tester.pump(); }, createHttpClient: createMockImageHttpClient); }); }
flutter/dev/manual_tests/test/color_testing_demo_test.dart/0
{'file_path': 'flutter/dev/manual_tests/test/color_testing_demo_test.dart', 'repo_id': 'flutter', 'token_count': 352}
// 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 [CupertinoAlertDialog]. import 'package:flutter/cupertino.dart'; void main() => runApp(const AlertDialogApp()); class AlertDialogApp extends StatelessWidget { const AlertDialogApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: AlertDialogExample(), ); } } class AlertDialogExample extends StatelessWidget { const AlertDialogExample({super.key}); // This shows a CupertinoModalPopup which hosts a CupertinoAlertDialog. void _showAlertDialog(BuildContext context) { showCupertinoModalPopup<void>( context: context, builder: (BuildContext context) => CupertinoAlertDialog( title: const Text('Alert'), content: const Text('Proceed with destructive action?'), actions: <CupertinoDialogAction>[ CupertinoDialogAction( /// This parameter indicates this action is the default, /// and turns the action's text to bold text. isDefaultAction: true, onPressed: () { Navigator.pop(context); }, child: const Text('No'), ), CupertinoDialogAction( /// This parameter indicates the action would perform /// a destructive action such as deletion, and turns /// the action's text color to red. isDestructiveAction: true, onPressed: () { Navigator.pop(context); }, child: const Text('Yes'), ), ], ), ); } @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('CupertinoAlertDialog Sample'), ), child: Center( child: CupertinoButton( onPressed: () => _showAlertDialog(context), child: const Text('CupertinoAlertDialog'), ), ), ); } }
flutter/examples/api/lib/cupertino/dialog/cupertino_alert_dialog.0.dart/0
{'file_path': 'flutter/examples/api/lib/cupertino/dialog/cupertino_alert_dialog.0.dart', 'repo_id': 'flutter', 'token_count': 866}
// 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 [CupertinoSlidingSegmentedControl]. import 'package:flutter/cupertino.dart'; enum Sky { midnight, viridian, cerulean } Map<Sky, Color> skyColors = <Sky, Color> { Sky.midnight: const Color(0xff191970), Sky.viridian: const Color(0xff40826d), Sky.cerulean: const Color(0xff007ba7), }; void main() => runApp(const SegmentedControlApp()); class SegmentedControlApp extends StatelessWidget { const SegmentedControlApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: SegmentedControlExample(), ); } } class SegmentedControlExample extends StatefulWidget { const SegmentedControlExample({super.key}); @override State<SegmentedControlExample> createState() => _SegmentedControlExampleState(); } class _SegmentedControlExampleState extends State<SegmentedControlExample> { Sky _selectedSegment = Sky.midnight; @override Widget build(BuildContext context) { return CupertinoPageScaffold( backgroundColor: skyColors[_selectedSegment], navigationBar: CupertinoNavigationBar( // This Cupertino segmented control has the enum "Sky" as the type. middle: CupertinoSlidingSegmentedControl<Sky>( backgroundColor: CupertinoColors.systemGrey2, thumbColor: skyColors[_selectedSegment]!, // This represents the currently selected segmented control. groupValue: _selectedSegment, // Callback that sets the selected segmented control. onValueChanged: (Sky? value) { if (value != null) { setState(() { _selectedSegment = value; }); } }, children: const <Sky, Widget>{ Sky.midnight: Padding( padding: EdgeInsets.symmetric(horizontal: 20), child: Text( 'Midnight', style: TextStyle(color: CupertinoColors.white), ), ), Sky.viridian: Padding( padding: EdgeInsets.symmetric(horizontal: 20), child: Text( 'Viridian', style: TextStyle(color: CupertinoColors.white), ), ), Sky.cerulean: Padding( padding: EdgeInsets.symmetric(horizontal: 20), child: Text( 'Cerulean', style: TextStyle(color: CupertinoColors.white), ), ), }, ), ), child: Center( child: Text( 'Selected Segment: ${_selectedSegment.name}', style: const TextStyle(color: CupertinoColors.white), ), ), ); } }
flutter/examples/api/lib/cupertino/segmented_control/cupertino_sliding_segmented_control.0.dart/0
{'file_path': 'flutter/examples/api/lib/cupertino/segmented_control/cupertino_sliding_segmented_control.0.dart', 'repo_id': 'flutter', 'token_count': 1277}
// 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 [SliverAppBar]. import 'package:flutter/material.dart'; void main() => runApp(const AppBarApp()); class AppBarApp extends StatelessWidget { const AppBarApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: SliverAppBarExample(), ); } } class SliverAppBarExample extends StatefulWidget { const SliverAppBarExample({super.key}); @override State<SliverAppBarExample> createState() => _SliverAppBarExampleState(); } class _SliverAppBarExampleState extends State<SliverAppBarExample> { bool _pinned = true; bool _snap = false; bool _floating = false; // [SliverAppBar]s are typically used in [CustomScrollView.slivers], which in // turn can be placed in a [Scaffold.body]. @override Widget build(BuildContext context) { return Scaffold( body: CustomScrollView( slivers: <Widget>[ SliverAppBar( pinned: _pinned, snap: _snap, floating: _floating, expandedHeight: 160.0, flexibleSpace: const FlexibleSpaceBar( title: Text('SliverAppBar'), background: FlutterLogo(), ), ), const SliverToBoxAdapter( child: SizedBox( height: 20, child: Center( child: Text('Scroll to see the SliverAppBar in effect.'), ), ), ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Container( color: index.isOdd ? Colors.white : Colors.black12, height: 100.0, child: Center( child: Text('$index', textScaleFactor: 5), ), ); }, childCount: 20, ), ), ], ), bottomNavigationBar: BottomAppBar( child: Padding( padding: const EdgeInsets.all(8), child: OverflowBar( overflowAlignment: OverflowBarAlignment.center, children: <Widget>[ Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('pinned'), Switch( onChanged: (bool val) { setState(() { _pinned = val; }); }, value: _pinned, ), ], ), Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('snap'), Switch( onChanged: (bool val) { setState(() { _snap = val; // Snapping only applies when the app bar is floating. _floating = _floating || _snap; }); }, value: _snap, ), ], ), Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('floating'), Switch( onChanged: (bool val) { setState(() { _floating = val; _snap = _snap && _floating; }); }, value: _floating, ), ], ), ], ), ), ), ); } }
flutter/examples/api/lib/material/app_bar/sliver_app_bar.1.dart/0
{'file_path': 'flutter/examples/api/lib/material/app_bar/sliver_app_bar.1.dart', 'repo_id': 'flutter', 'token_count': 2167}
// 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 [DataTable]. 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 MyStatefulWidget(), ), ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({super.key}); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { static const int numItems = 10; List<bool> selected = List<bool>.generate(numItems, (int index) => false); @override Widget build(BuildContext context) { return SizedBox( width: double.infinity, child: DataTable( columns: const <DataColumn>[ DataColumn( label: Text('Number'), ), ], rows: List<DataRow>.generate( numItems, (int index) => DataRow( color: MaterialStateProperty.resolveWith<Color?>( (Set<MaterialState> states) { // All rows will have the same selected color. if (states.contains(MaterialState.selected)) { return Theme.of(context).colorScheme.primary.withOpacity(0.08); } // Even rows will have a grey color. if (index.isEven) { return Colors.grey.withOpacity(0.3); } return null; // Use default value for other states and odd rows. }), cells: <DataCell>[DataCell(Text('Row $index'))], selected: selected[index], onSelectChanged: (bool? value) { setState(() { selected[index] = value!; }); }, ), ), ), ); } }
flutter/examples/api/lib/material/data_table/data_table.1.dart/0
{'file_path': 'flutter/examples/api/lib/material/data_table/data_table.1.dart', 'repo_id': 'flutter', 'token_count': 944}
// 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 [MenuAnchor]. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(const MenuApp()); /// An enhanced enum to define the available menus and their shortcuts. /// /// Using an enum for menu definition is not required, but this illustrates how /// they could be used for simple menu systems. enum MenuEntry { about('About'), showMessage('Show Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)), hideMessage('Hide Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)), colorMenu('Color Menu'), colorRed('Red Background', SingleActivator(LogicalKeyboardKey.keyR, control: true)), colorGreen('Green Background', SingleActivator(LogicalKeyboardKey.keyG, control: true)), colorBlue('Blue Background', SingleActivator(LogicalKeyboardKey.keyB, control: true)); const MenuEntry(this.label, [this.shortcut]); final String label; final MenuSerializableShortcut? shortcut; } class MyCascadingMenu extends StatefulWidget { const MyCascadingMenu({super.key, required this.message}); final String message; @override State<MyCascadingMenu> createState() => _MyCascadingMenuState(); } class _MyCascadingMenuState extends State<MyCascadingMenu> { MenuEntry? _lastSelection; final FocusNode _buttonFocusNode = FocusNode(debugLabel: 'Menu Button'); ShortcutRegistryEntry? _shortcutsEntry; Color get backgroundColor => _backgroundColor; Color _backgroundColor = Colors.red; set backgroundColor(Color value) { if (_backgroundColor != value) { setState(() { _backgroundColor = value; }); } } bool get showingMessage => _showingMessage; bool _showingMessage = false; set showingMessage(bool value) { if (_showingMessage != value) { setState(() { _showingMessage = value; }); } } @override void didChangeDependencies() { super.didChangeDependencies(); // Dispose of any previously registered shortcuts, since they are about to // be replaced. _shortcutsEntry?.dispose(); // Collect the shortcuts from the different menu selections so that they can // be registered to apply to the entire app. Menus don't register their // shortcuts, they only display the shortcut hint text. final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{ for (final MenuEntry item in MenuEntry.values) if (item.shortcut != null) item.shortcut!: VoidCallbackIntent(() => _activate(item)), }; // Register the shortcuts with the ShortcutRegistry so that they are // available to the entire application. _shortcutsEntry = ShortcutRegistry.of(context).addAll(shortcuts); } @override void dispose() { _shortcutsEntry?.dispose(); _buttonFocusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ MenuAnchor( childFocusNode: _buttonFocusNode, menuChildren: <Widget>[ MenuItemButton( child: Text(MenuEntry.about.label), onPressed: () => _activate(MenuEntry.about), ), if (_showingMessage) MenuItemButton( onPressed: () => _activate(MenuEntry.hideMessage), shortcut: MenuEntry.hideMessage.shortcut, child: Text(MenuEntry.hideMessage.label), ), if (!_showingMessage) MenuItemButton( onPressed: () => _activate(MenuEntry.showMessage), shortcut: MenuEntry.showMessage.shortcut, child: Text(MenuEntry.showMessage.label), ), SubmenuButton( menuChildren: <Widget>[ MenuItemButton( onPressed: () => _activate(MenuEntry.colorRed), shortcut: MenuEntry.colorRed.shortcut, child: Text(MenuEntry.colorRed.label), ), MenuItemButton( onPressed: () => _activate(MenuEntry.colorGreen), shortcut: MenuEntry.colorGreen.shortcut, child: Text(MenuEntry.colorGreen.label), ), MenuItemButton( onPressed: () => _activate(MenuEntry.colorBlue), shortcut: MenuEntry.colorBlue.shortcut, child: Text(MenuEntry.colorBlue.label), ), ], child: const Text('Background Color'), ), ], builder: (BuildContext context, MenuController controller, Widget? child) { return TextButton( focusNode: _buttonFocusNode, onPressed: () { if (controller.isOpen) { controller.close(); } else { controller.open(); } }, child: const Text('OPEN MENU'), ); }, ), Expanded( child: Container( alignment: Alignment.center, color: backgroundColor, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(12.0), child: Text( showingMessage ? widget.message : '', style: Theme.of(context).textTheme.headlineSmall, ), ), Text(_lastSelection != null ? 'Last Selected: ${_lastSelection!.label}' : ''), ], ), ), ), ], ); } void _activate(MenuEntry selection) { setState(() { _lastSelection = selection; }); switch (selection) { case MenuEntry.about: showAboutDialog( context: context, applicationName: 'MenuBar Sample', applicationVersion: '1.0.0', ); break; case MenuEntry.hideMessage: case MenuEntry.showMessage: showingMessage = !showingMessage; break; case MenuEntry.colorMenu: break; case MenuEntry.colorRed: backgroundColor = Colors.red; break; case MenuEntry.colorGreen: backgroundColor = Colors.green; break; case MenuEntry.colorBlue: backgroundColor = Colors.blue; break; } } } class MenuApp extends StatelessWidget { const MenuApp({super.key}); static const String kMessage = '"Talk less. Smile more." - A. Burr'; @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold(body: MyCascadingMenu(message: kMessage)), ); } }
flutter/examples/api/lib/material/menu_anchor/menu_anchor.0.dart/0
{'file_path': 'flutter/examples/api/lib/material/menu_anchor/menu_anchor.0.dart', 'repo_id': 'flutter', 'token_count': 2922}
// 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 [CircularProgressIndicator]. import 'package:flutter/material.dart'; void main() => runApp(const ProgressIndicatorApp()); class ProgressIndicatorApp extends StatelessWidget { const ProgressIndicatorApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true, colorSchemeSeed: const Color(0xff6750a4)), home: const ProgressIndicatorExample(), ); } } class ProgressIndicatorExample extends StatefulWidget { const ProgressIndicatorExample({super.key}); @override State<ProgressIndicatorExample> createState() => _ProgressIndicatorExampleState(); } class _ProgressIndicatorExampleState extends State<ProgressIndicatorExample> with TickerProviderStateMixin { late AnimationController controller; bool determinate = false; @override void initState() { controller = AnimationController( /// [AnimationController]s can be created with `vsync: this` because of /// [TickerProviderStateMixin]. vsync: this, duration: const Duration(seconds: 2), )..addListener(() { setState(() {}); }); controller.repeat(reverse: true); super.initState(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(20.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Circular progress indicator', style: Theme.of(context).textTheme.titleLarge, ), const SizedBox(height: 30), CircularProgressIndicator( value: controller.value, semanticsLabel: 'Circular progress indicator', ), const SizedBox(height: 10), Row( children: <Widget>[ Expanded( child: Text( 'determinate Mode', style: Theme.of(context).textTheme.titleSmall, ), ), Switch( value: determinate, onChanged: (bool value) { setState(() { determinate = value; if (determinate) { controller.stop(); } else { controller..forward(from: controller.value)..repeat(); } }); }, ), ], ), ], ), ), ); } }
flutter/examples/api/lib/material/progress_indicator/circular_progress_indicator.1.dart/0
{'file_path': 'flutter/examples/api/lib/material/progress_indicator/circular_progress_indicator.1.dart', 'repo_id': 'flutter', 'token_count': 1311}
// 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 [Switch]. import 'package:flutter/material.dart'; void main() => runApp(const SwitchApp()); class SwitchApp extends StatelessWidget { const SwitchApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Switch Sample')), body: const Center( child: SwitchExample(), ), ), ); } } class SwitchExample extends StatefulWidget { const SwitchExample({super.key}); @override State<SwitchExample> createState() => _SwitchExampleState(); } class _SwitchExampleState extends State<SwitchExample> { bool light = true; @override Widget build(BuildContext context) { final MaterialStateProperty<Color?> trackColor = MaterialStateProperty.resolveWith<Color?>( (Set<MaterialState> states) { // Track color when the switch is selected. if (states.contains(MaterialState.selected)) { return Colors.amber; } // Otherwise return null to set default track color // for remaining states such as when the switch is // hovered, focused, or disabled. return null; }, ); final MaterialStateProperty<Color?> overlayColor = MaterialStateProperty.resolveWith<Color?>( (Set<MaterialState> states) { // Material color when switch is selected. if (states.contains(MaterialState.selected)) { return Colors.amber.withOpacity(0.54); } // Material color when switch is disabled. if (states.contains(MaterialState.disabled)) { return Colors.grey.shade400; } // Otherwise return null to set default material color // for remaining states such as when the switch is // hovered, or focused. return null; }, ); return Switch( // This bool value toggles the switch. value: light, overlayColor: overlayColor, trackColor: trackColor, thumbColor: const MaterialStatePropertyAll<Color>(Colors.black), onChanged: (bool value) { // This is called when the user toggles the switch. setState(() { light = value; }); }, ); } }
flutter/examples/api/lib/material/switch/switch.1.dart/0
{'file_path': 'flutter/examples/api/lib/material/switch/switch.1.dart', 'repo_id': 'flutter', 'token_count': 883}
// 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 [showTimePicker]. import 'package:flutter/material.dart'; void main() { runApp(const ShowTimePickerApp()); } class ShowTimePickerApp extends StatefulWidget { const ShowTimePickerApp({super.key}); @override State<ShowTimePickerApp> createState() => _ShowTimePickerAppState(); } class _ShowTimePickerAppState extends State<ShowTimePickerApp> { ThemeMode themeMode = ThemeMode.dark; bool useMaterial3 = true; void setThemeMode(ThemeMode mode) { setState(() { themeMode = mode; }); } void setUseMaterial3(bool? value) { setState(() { useMaterial3 = value!; }); } @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(useMaterial3: useMaterial3), darkTheme: ThemeData.dark(useMaterial3: useMaterial3), themeMode: themeMode, home: TimePickerOptions( themeMode: themeMode, useMaterial3: useMaterial3, setThemeMode: setThemeMode, setUseMaterial3: setUseMaterial3, ), ); } } class TimePickerOptions extends StatefulWidget { const TimePickerOptions({ super.key, required this.themeMode, required this.useMaterial3, required this.setThemeMode, required this.setUseMaterial3, }); final ThemeMode themeMode; final bool useMaterial3; final ValueChanged<ThemeMode> setThemeMode; final ValueChanged<bool?> setUseMaterial3; @override State<TimePickerOptions> createState() => _TimePickerOptionsState(); } class _TimePickerOptionsState extends State<TimePickerOptions> { TimeOfDay? selectedTime; TimePickerEntryMode entryMode = TimePickerEntryMode.dial; Orientation? orientation; TextDirection textDirection = TextDirection.ltr; MaterialTapTargetSize tapTargetSize = MaterialTapTargetSize.padded; bool use24HourTime = false; void _entryModeChanged(TimePickerEntryMode? value) { if (value != entryMode) { setState(() { entryMode = value!; }); } } void _orientationChanged(Orientation? value) { if (value != orientation) { setState(() { orientation = value; }); } } void _textDirectionChanged(TextDirection? value) { if (value != textDirection) { setState(() { textDirection = value!; }); } } void _tapTargetSizeChanged(MaterialTapTargetSize? value) { if (value != tapTargetSize) { setState(() { tapTargetSize = value!; }); } } void _use24HourTimeChanged(bool? value) { if (value != use24HourTime) { setState(() { use24HourTime = value!; }); } } void _themeModeChanged(ThemeMode? value) { widget.setThemeMode(value!); } @override Widget build(BuildContext context) { return Material( child: Column( children: <Widget>[ Expanded( child: GridView( gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 350, mainAxisSpacing: 4, mainAxisExtent: 200 * MediaQuery.textScaleFactorOf(context), crossAxisSpacing: 4, ), children: <Widget>[ EnumCard<TimePickerEntryMode>( choices: TimePickerEntryMode.values, value: entryMode, onChanged: _entryModeChanged, ), EnumCard<ThemeMode>( choices: ThemeMode.values, value: widget.themeMode, onChanged: _themeModeChanged, ), EnumCard<TextDirection>( choices: TextDirection.values, value: textDirection, onChanged: _textDirectionChanged, ), EnumCard<MaterialTapTargetSize>( choices: MaterialTapTargetSize.values, value: tapTargetSize, onChanged: _tapTargetSizeChanged, ), ChoiceCard<Orientation?>( choices: const <Orientation?>[...Orientation.values, null], value: orientation, title: '$Orientation', choiceLabels: <Orientation?, String>{ for (final Orientation choice in Orientation.values) choice: choice.name, null: 'from MediaQuery', }, onChanged: _orientationChanged, ), ChoiceCard<bool>( choices: const <bool>[false, true], value: use24HourTime, onChanged: _use24HourTimeChanged, title: 'Time Mode', choiceLabels: const <bool, String>{ false: '12-hour am/pm time', true: '24-hour time', }, ), ChoiceCard<bool>( choices: const <bool>[false, true], value: widget.useMaterial3, onChanged: widget.setUseMaterial3, title: 'Material Version', choiceLabels: const <bool, String>{ false: 'Material 2', true: 'Material 3', }, ), ], ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(12.0), child: ElevatedButton( child: const Text('Open time picker'), onPressed: () async { final TimeOfDay? time = await showTimePicker( context: context, initialTime: selectedTime ?? TimeOfDay.now(), initialEntryMode: entryMode, orientation: orientation, builder: (BuildContext context, Widget? child) { // We just wrap these environmental changes around the // child in this builder so that we can apply the // options selected above. In regular usage, this is // rarely necessary, because the default values are // usually used as-is. return Theme( data: Theme.of(context).copyWith( materialTapTargetSize: tapTargetSize, ), child: Directionality( textDirection: textDirection, child: MediaQuery( data: MediaQuery.of(context).copyWith( alwaysUse24HourFormat: use24HourTime, ), child: child!, ), ), ); }, ); setState(() { selectedTime = time; }); }, ), ), if (selectedTime != null) Text('Selected time: ${selectedTime!.format(context)}'), ], ), ), ], ), ); } } // This is a simple card that presents a set of radio buttons (inside of a // RadioSelection, defined below) for the user to select from. class ChoiceCard<T extends Object?> extends StatelessWidget { const ChoiceCard({ super.key, required this.value, required this.choices, required this.onChanged, required this.choiceLabels, required this.title, }); final T value; final Iterable<T> choices; final Map<T, String> choiceLabels; final String title; final ValueChanged<T?> onChanged; @override Widget build(BuildContext context) { return Card( // If the card gets too small, let it scroll both directions. child: SingleChildScrollView( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Text(title), ), for (final T choice in choices) RadioSelection<T>( value: choice, groupValue: value, onChanged: onChanged, child: Text(choiceLabels[choice]!), ), ], ), ), ), ), ); } } // This aggregates a ChoiceCard so that it presents a set of radio buttons for // the allowed enum values for the user to select from. class EnumCard<T extends Enum> extends StatelessWidget { const EnumCard({ super.key, required this.value, required this.choices, required this.onChanged, }); final T value; final Iterable<T> choices; final ValueChanged<T?> onChanged; @override Widget build(BuildContext context) { return ChoiceCard<T>( value: value, choices: choices, onChanged: onChanged, choiceLabels: <T, String>{ for (final T choice in choices) choice: choice.name, }, title: value.runtimeType.toString()); } } // A button that has a radio button on one side and a label child. Tapping on // the label or the radio button selects the item. class RadioSelection<T extends Object?> extends StatefulWidget { const RadioSelection({ super.key, required this.value, required this.groupValue, required this.onChanged, required this.child, }); final T value; final T? groupValue; final ValueChanged<T?> onChanged; final Widget child; @override State<RadioSelection<T>> createState() => _RadioSelectionState<T>(); } class _RadioSelectionState<T extends Object?> extends State<RadioSelection<T>> { @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Padding( padding: const EdgeInsetsDirectional.only(end: 8), child: Radio<T>( groupValue: widget.groupValue, value: widget.value, onChanged: widget.onChanged, ), ), GestureDetector(onTap: () => widget.onChanged(widget.value), child: widget.child), ], ); } }
flutter/examples/api/lib/material/time_picker/show_time_picker.0.dart/0
{'file_path': 'flutter/examples/api/lib/material/time_picker/show_time_picker.0.dart', 'repo_id': 'flutter', 'token_count': 5324}
// 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 [Actions]. 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 Center( child: MyStatefulWidget(), ), ), ); } } // A simple model class that notifies listeners when it changes. class Model { ValueNotifier<bool> isDirty = ValueNotifier<bool>(false); ValueNotifier<int> data = ValueNotifier<int>(0); int save() { if (isDirty.value) { debugPrint('Saved Data: ${data.value}'); isDirty.value = false; } return data.value; } void setValue(int newValue) { isDirty.value = data.value != newValue; data.value = newValue; } } class ModifyIntent extends Intent { const ModifyIntent(this.value); final int value; } // An Action that modifies the model by setting it to the value that it gets // from the Intent passed to it when invoked. class ModifyAction extends Action<ModifyIntent> { ModifyAction(this.model); final Model model; @override void invoke(covariant ModifyIntent intent) { model.setValue(intent.value); } } // An intent for saving data. class SaveIntent extends Intent { const SaveIntent(); } // An Action that saves the data in the model it is created with. class SaveAction extends Action<SaveIntent> { SaveAction(this.model); final Model model; @override int invoke(covariant SaveIntent intent) => model.save(); } class SaveButton extends StatefulWidget { const SaveButton(this.valueNotifier, {super.key}); final ValueNotifier<bool> valueNotifier; @override State<SaveButton> createState() => _SaveButtonState(); } class _SaveButtonState extends State<SaveButton> { int savedValue = 0; @override Widget build(BuildContext context) { return AnimatedBuilder( animation: widget.valueNotifier, builder: (BuildContext context, Widget? child) { return TextButton.icon( icon: const Icon(Icons.save), label: Text('$savedValue'), style: ButtonStyle( foregroundColor: MaterialStatePropertyAll<Color>( widget.valueNotifier.value ? Colors.red : Colors.green, ), ), onPressed: () { setState(() { savedValue = Actions.invoke(context, const SaveIntent())! as int; }); }, ); }, ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({super.key}); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { Model model = Model(); int count = 0; @override Widget build(BuildContext context) { return Actions( actions: <Type, Action<Intent>>{ ModifyIntent: ModifyAction(model), SaveIntent: SaveAction(model), }, child: Builder( builder: (BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ const Spacer(), Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ IconButton( icon: const Icon(Icons.exposure_plus_1), onPressed: () { Actions.invoke(context, ModifyIntent(++count)); }, ), AnimatedBuilder( animation: model.data, builder: (BuildContext context, Widget? child) { return Padding( padding: const EdgeInsets.all(8.0), child: Text('${model.data.value}', style: Theme.of(context).textTheme.headlineMedium), ); }), IconButton( icon: const Icon(Icons.exposure_minus_1), onPressed: () { Actions.invoke(context, ModifyIntent(--count)); }, ), ], ), SaveButton(model.isDirty), const Spacer(), ], ); }, ), ); } }
flutter/examples/api/lib/widgets/actions/actions.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/actions/actions.0.dart', 'repo_id': 'flutter', 'token_count': 2090}
// 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 [AbsorbPointer]. 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 Center( child: MyStatelessWidget(), ), ), ); } } class MyStatelessWidget extends StatelessWidget { const MyStatelessWidget({super.key}); @override Widget build(BuildContext context) { return Stack( alignment: AlignmentDirectional.center, children: <Widget>[ SizedBox( width: 200.0, height: 100.0, child: ElevatedButton( onPressed: () {}, child: null, ), ), SizedBox( width: 100.0, height: 200.0, child: AbsorbPointer( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.blue.shade200, ), onPressed: () {}, child: null, ), ), ), ], ); } }
flutter/examples/api/lib/widgets/basic/absorb_pointer.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/basic/absorb_pointer.0.dart', 'repo_id': 'flutter', 'token_count': 662}
// 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 [MouseRegion.onExit]. 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 Center( child: MyStatefulWidget(), ), ), ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({super.key}); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { bool hovered = false; @override Widget build(BuildContext context) { return Container( height: 100, width: 100, decoration: BoxDecoration(color: hovered ? Colors.yellow : Colors.blue), child: MouseRegion( onEnter: (_) { setState(() { hovered = true; }); }, onExit: (_) { setState(() { hovered = false; }); }, ), ); } }
flutter/examples/api/lib/widgets/basic/mouse_region.on_exit.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/basic/mouse_region.on_exit.0.dart', 'repo_id': 'flutter', 'token_count': 546}
// 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 [FocusScope]. 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(), ); } } /// A demonstration pane. /// /// This is just a separate widget to simplify the example. class Pane extends StatelessWidget { const Pane({ super.key, required this.focusNode, this.onPressed, required this.backgroundColor, required this.icon, this.child, }); final FocusNode focusNode; final VoidCallback? onPressed; final Color backgroundColor; final Widget icon; final Widget? child; @override Widget build(BuildContext context) { return Material( color: backgroundColor, child: Stack( fit: StackFit.expand, children: <Widget>[ Center( child: child, ), Align( alignment: Alignment.topLeft, child: IconButton( autofocus: true, focusNode: focusNode, onPressed: onPressed, icon: icon, ), ), ], ), ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({super.key}); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { bool backdropIsVisible = false; FocusNode backdropNode = FocusNode(debugLabel: 'Close Backdrop Button'); FocusNode foregroundNode = FocusNode(debugLabel: 'Option Button'); @override void dispose() { backdropNode.dispose(); foregroundNode.dispose(); super.dispose(); } Widget _buildStack(BuildContext context, BoxConstraints constraints) { final Size stackSize = constraints.biggest; return Stack( fit: StackFit.expand, // The backdrop is behind the front widget in the Stack, but the widgets // would still be active and traversable without the FocusScope. children: <Widget>[ // TRY THIS: Try removing this FocusScope entirely to see how it affects // the behavior. Without this FocusScope, the "ANOTHER BUTTON TO FOCUS" // button, and the IconButton in the backdrop Pane would be focusable // even when the backdrop wasn't visible. FocusScope( // TRY THIS: Try commenting out this line. Notice that the focus // starts on the backdrop and is stuck there? It seems like the app is // non-responsive, but it actually isn't. This line makes sure that // this focus scope and its children can't be focused when they're not // visible. It might help to make the background color of the // foreground pane semi-transparent to see it clearly. canRequestFocus: backdropIsVisible, child: Pane( icon: const Icon(Icons.close), focusNode: backdropNode, backgroundColor: Colors.lightBlue, onPressed: () => setState(() => backdropIsVisible = false), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ // This button would be not visible, but still focusable from // the foreground pane without the FocusScope. ElevatedButton( onPressed: () => debugPrint('You pressed the other button!'), child: const Text('ANOTHER BUTTON TO FOCUS'), ), DefaultTextStyle( style: Theme.of(context).textTheme.displayMedium!, child: const Text('BACKDROP')), ], ), ), ), AnimatedPositioned( curve: Curves.easeInOut, duration: const Duration(milliseconds: 300), top: backdropIsVisible ? stackSize.height * 0.9 : 0.0, width: stackSize.width, height: stackSize.height, onEnd: () { if (backdropIsVisible) { backdropNode.requestFocus(); } else { foregroundNode.requestFocus(); } }, child: Pane( icon: const Icon(Icons.menu), focusNode: foregroundNode, // TRY THIS: Try changing this to Colors.green.withOpacity(0.8) to see for // yourself that the hidden components do/don't get focus. backgroundColor: Colors.green, onPressed: backdropIsVisible ? null : () => setState(() => backdropIsVisible = true), child: DefaultTextStyle( style: Theme.of(context).textTheme.displayMedium!, child: const Text('FOREGROUND')), ), ), ], ); } @override Widget build(BuildContext context) { // Use a LayoutBuilder so that we can base the size of the stack on the size // of its parent. return LayoutBuilder(builder: _buildStack); } }
flutter/examples/api/lib/widgets/focus_scope/focus_scope.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/focus_scope/focus_scope.0.dart', 'repo_id': 'flutter', 'token_count': 2200}
// 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 [AnimatedContainer]. 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 MyStatefulWidget(), ), ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({super.key}); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { bool selected = false; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { setState(() { selected = !selected; }); }, child: Center( child: AnimatedContainer( width: selected ? 200.0 : 100.0, height: selected ? 100.0 : 200.0, color: selected ? Colors.red : Colors.blue, alignment: selected ? Alignment.center : AlignmentDirectional.topCenter, duration: const Duration(seconds: 2), curve: Curves.fastOutSlowIn, child: const FlutterLogo(size: 75), ), ), ); } }
flutter/examples/api/lib/widgets/implicit_animations/animated_container.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/implicit_animations/animated_container.0.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. // Flutter code sample for [Navigator]. 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( title: 'Flutter Code Sample for Navigator', // MaterialApp contains our top-level Navigator initialRoute: '/', routes: <String, WidgetBuilder>{ '/': (BuildContext context) => const HomePage(), '/signup': (BuildContext context) => const SignUpPage(), }, ); } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return DefaultTextStyle( style: Theme.of(context).textTheme.headlineMedium!, child: Container( color: Colors.white, alignment: Alignment.center, child: const Text('Home Page'), ), ); } } class CollectPersonalInfoPage extends StatelessWidget { const CollectPersonalInfoPage({super.key}); @override Widget build(BuildContext context) { return DefaultTextStyle( style: Theme.of(context).textTheme.headlineMedium!, child: GestureDetector( onTap: () { // This moves from the personal info page to the credentials page, // replacing this page with that one. Navigator.of(context) .pushReplacementNamed('signup/choose_credentials'); }, child: Container( color: Colors.lightBlue, alignment: Alignment.center, child: const Text('Collect Personal Info Page'), ), ), ); } } class ChooseCredentialsPage extends StatelessWidget { const ChooseCredentialsPage({ super.key, required this.onSignupComplete, }); final VoidCallback onSignupComplete; @override Widget build(BuildContext context) { return GestureDetector( onTap: onSignupComplete, child: DefaultTextStyle( style: Theme.of(context).textTheme.headlineMedium!, child: Container( color: Colors.pinkAccent, alignment: Alignment.center, child: const Text('Choose Credentials Page'), ), ), ); } } class SignUpPage extends StatelessWidget { const SignUpPage({super.key}); @override Widget build(BuildContext context) { // SignUpPage builds its own Navigator which ends up being a nested // Navigator in our app. return Navigator( initialRoute: 'signup/personal_info', onGenerateRoute: (RouteSettings settings) { WidgetBuilder builder; switch (settings.name) { case 'signup/personal_info': // Assume CollectPersonalInfoPage collects personal info and then // navigates to 'signup/choose_credentials'. builder = (BuildContext context) => const CollectPersonalInfoPage(); break; case 'signup/choose_credentials': // Assume ChooseCredentialsPage collects new credentials and then // invokes 'onSignupComplete()'. builder = (BuildContext _) => ChooseCredentialsPage( onSignupComplete: () { // Referencing Navigator.of(context) from here refers to the // top level Navigator because SignUpPage is above the // nested Navigator that it created. Therefore, this pop() // will pop the entire "sign up" journey and return to the // "/" route, AKA HomePage. Navigator.of(context).pop(); }, ); break; default: throw Exception('Invalid route: ${settings.name}'); } return MaterialPageRoute<void>(builder: builder, settings: settings); }, ); } }
flutter/examples/api/lib/widgets/navigator/navigator.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/navigator/navigator.0.dart', 'repo_id': 'flutter', 'token_count': 1590}
// 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 [TextFieldTapRegion]. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(const TapRegionApp()); class TapRegionApp extends StatelessWidget { const TapRegionApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('TextFieldTapRegion Example')), body: const TextFieldTapRegionExample(), ), ); } } class TextFieldTapRegionExample extends StatefulWidget { const TextFieldTapRegionExample({super.key}); @override State<TextFieldTapRegionExample> createState() => _TextFieldTapRegionExampleState(); } class _TextFieldTapRegionExampleState extends State<TextFieldTapRegionExample> { int value = 0; @override Widget build(BuildContext context) { return ListView( children: <Widget>[ Center( child: Padding( padding: const EdgeInsets.all(20.0), child: SizedBox( width: 150, height: 80, child: IntegerSpinnerField( value: value, autofocus: true, onChanged: (int newValue) { if (value == newValue) { // Avoid unnecessary redraws. return; } setState(() { // Update the value and redraw. value = newValue; }); }, ), ), ), ), ], ); } } /// An integer example of the generic [SpinnerField] that validates input and /// increments by a delta. class IntegerSpinnerField extends StatelessWidget { const IntegerSpinnerField({ super.key, required this.value, this.autofocus = false, this.delta = 1, this.onChanged, }); final int value; final bool autofocus; final int delta; final ValueChanged<int>? onChanged; @override Widget build(BuildContext context) { return SpinnerField<int>( value: value, onChanged: onChanged, autofocus: autofocus, fromString: (String stringValue) => int.tryParse(stringValue) ?? value, increment: (int i) => i + delta, decrement: (int i) => i - delta, // Add a text formatter that only allows integer values and a leading // minus sign. inputFormatters: <TextInputFormatter>[ TextInputFormatter.withFunction( (TextEditingValue oldValue, TextEditingValue newValue) { String newString; if (newValue.text.startsWith('-')) { newString = '-${newValue.text.replaceAll(RegExp(r'\D'), '')}'; } else { newString = newValue.text.replaceAll(RegExp(r'\D'), ''); } return newValue.copyWith( text: newString, selection: newValue.selection.copyWith( baseOffset: newValue.selection.baseOffset.clamp(0, newString.length), extentOffset: newValue.selection.extentOffset.clamp(0, newString.length), ), ); }, ) ], ); } } /// A generic "spinner" field example which adds extra buttons next to a /// [TextField] to increment and decrement the value. /// /// This widget uses [TextFieldTapRegion] to indicate that tapping on the /// spinner buttons should not cause the text field to lose focus. class SpinnerField<T> extends StatefulWidget { SpinnerField({ super.key, required this.value, required this.fromString, this.autofocus = false, String Function(T value)? asString, this.increment, this.decrement, this.onChanged, this.inputFormatters = const <TextInputFormatter>[], }) : asString = asString ?? ((T value) => value.toString()); final T value; final T Function(T value)? increment; final T Function(T value)? decrement; final String Function(T value) asString; final T Function(String value) fromString; final ValueChanged<T>? onChanged; final List<TextInputFormatter> inputFormatters; final bool autofocus; @override State<SpinnerField<T>> createState() => _SpinnerFieldState<T>(); } class _SpinnerFieldState<T> extends State<SpinnerField<T>> { TextEditingController controller = TextEditingController(); @override void initState() { super.initState(); _updateText(widget.asString(widget.value)); } @override void dispose() { controller.dispose(); super.dispose(); } @override void didUpdateWidget(covariant SpinnerField<T> oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.asString != widget.asString || oldWidget.value != widget.value) { final String newText = widget.asString(widget.value); _updateText(newText); } } void _updateText(String text, {bool collapsed = true}) { if (text != controller.text) { controller.value = TextEditingValue( text: text, selection: collapsed ? TextSelection.collapsed(offset: text.length) : TextSelection(baseOffset: 0, extentOffset: text.length), ); } } void _spin(T Function(T value)? spinFunction) { if (spinFunction == null) { return; } final T newValue = spinFunction(widget.value); widget.onChanged?.call(newValue); _updateText(widget.asString(newValue), collapsed: false); } void _increment() { _spin(widget.increment); } void _decrement() { _spin(widget.decrement); } @override Widget build(BuildContext context) { return CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const SingleActivator(LogicalKeyboardKey.arrowUp): _increment, const SingleActivator(LogicalKeyboardKey.arrowDown): _decrement, }, child: Row( children: <Widget>[ Expanded( child: TextField( autofocus: widget.autofocus, inputFormatters: widget.inputFormatters, decoration: const InputDecoration( border: OutlineInputBorder(), ), onChanged: (String value) => widget.onChanged?.call(widget.fromString(value)), controller: controller, textAlign: TextAlign.center, ), ), const SizedBox(width: 12), // Without this TextFieldTapRegion, tapping on the buttons below would // increment the value, but it would cause the text field to be // unfocused, since tapping outside of a text field should unfocus it // on non-mobile platforms. TextFieldTapRegion( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Expanded( child: OutlinedButton( onPressed: _increment, child: const Icon(Icons.add), ), ), Expanded( child: OutlinedButton( onPressed: _decrement, child: const Icon(Icons.remove), ), ), ], ), ) ], ), ); } }
flutter/examples/api/lib/widgets/tap_region/text_field_tap_region.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/tap_region/text_field_tap_region.0.dart', 'repo_id': 'flutter', 'token_count': 3190}
// 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 [SliverFadeTransition]. 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 Center( child: MyStatefulWidget(), ), ), ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({super.key}); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> with SingleTickerProviderStateMixin { late final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 1000), vsync: this, ); late final Animation<double> animation = CurvedAnimation( parent: controller, curve: Curves.easeIn, ); @override void initState() { super.initState(); animation.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { controller.reverse(); } else if (status == AnimationStatus.dismissed) { controller.forward(); } }); controller.forward(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return CustomScrollView(slivers: <Widget>[ SliverFadeTransition( opacity: animation, sliver: SliverFixedExtentList( itemExtent: 100.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Container( color: index.isEven ? Colors.indigo[200] : Colors.orange[200], ); }, childCount: 5, ), ), ), ]); } }
flutter/examples/api/lib/widgets/transitions/sliver_fade_transition.0.dart/0
{'file_path': 'flutter/examples/api/lib/widgets/transitions/sliver_fade_transition.0.dart', 'repo_id': 'flutter', 'token_count': 821}
// 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/dialog/cupertino_alert_dialog.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Perform an action on CupertinoAlertDialog', (WidgetTester tester) async { const String actionText = 'Yes'; await tester.pumpWidget( const example.AlertDialogApp(), ); // Launch the CupertinoAlertDialog. await tester.tap(find.byType(CupertinoButton)); await tester.pump(); await tester.pumpAndSettle(); expect(find.text(actionText), findsOneWidget); // Tap on an action to close the CupertinoAlertDialog. await tester.tap(find.text(actionText)); await tester.pumpAndSettle(); expect(find.text(actionText), findsNothing); }); }
flutter/examples/api/test/cupertino/dialog/cupertino_alert_dialog.0_test.dart/0
{'file_path': 'flutter/examples/api/test/cupertino/dialog/cupertino_alert_dialog.0_test.dart', 'repo_id': 'flutter', 'token_count': 332}
// 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/app_bar/app_bar.3.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( 'AppBar elevates when nested scroll view is scrolled underneath the AppBar', (WidgetTester tester) async { Material getMaterial() => tester.widget<Material>(find.descendant( of: find.byType(AppBar), matching: find.byType(Material), )); await tester.pumpWidget( const example.AppBarApp(), ); // Starts with the base elevation. expect(getMaterial().elevation, 0.0); await tester.fling(find.text('Beach 3'), const Offset(0.0, -600.0), 2000.0); await tester.pumpAndSettle(); // After scrolling it should be the scrolledUnderElevation. expect(getMaterial().elevation, 4.0); }); }
flutter/examples/api/test/material/appbar/app_bar.3_test.dart/0
{'file_path': 'flutter/examples/api/test/material/appbar/app_bar.3_test.dart', 'repo_id': 'flutter', 'token_count': 382}
// 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/dialog/alert_dialog.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Show Alert dialog', (WidgetTester tester) async { const String dialogTitle = 'AlertDialog Title'; await tester.pumpWidget( const MaterialApp( home: Scaffold( body: example.MyApp(), ), ), ); expect(find.text(dialogTitle), findsNothing); await tester.tap(find.widgetWithText(TextButton, 'Show Dialog')); await tester.pumpAndSettle(); expect(find.text(dialogTitle), findsOneWidget); await tester.tap(find.text('OK')); await tester.pumpAndSettle(); expect(find.text(dialogTitle), findsNothing); }); }
flutter/examples/api/test/material/dialog/alert_dialog.0_test.dart/0
{'file_path': 'flutter/examples/api/test/material/dialog/alert_dialog.0_test.dart', 'repo_id': 'flutter', 'token_count': 345}
// 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/list_tile/list_tile.selected.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('ListTile item can be selected', (WidgetTester tester) async { await tester.pumpWidget( const example.ListTileApp(), ); expect(find.byType(ListTile), findsNWidgets(10)); // The first item is selected by default. expect(tester.widget<ListTile>(find.byType(ListTile).at(0)).selected, true); // Tap a list item to select it. await tester.tap(find.byType(ListTile).at(5)); await tester.pump(); // The first item is no longer selected. expect(tester.widget<ListTile>(find.byType(ListTile).at(0)).selected, false); expect(tester.widget<ListTile>(find.byType(ListTile).at(5)).selected, true); }); }
flutter/examples/api/test/material/list_tile/list_tile.selected.0_test.dart/0
{'file_path': 'flutter/examples/api/test/material/list_tile/list_tile.selected.0_test.dart', 'repo_id': 'flutter', 'token_count': 353}
// 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_api_samples/material/progress_indicator/linear_progress_indicator.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Finds LinearProgressIndicator', (WidgetTester tester) async { await tester.pumpWidget( const example.ProgressIndicatorApp(), ); expect( find.bySemanticsLabel('Linear progress indicator'), findsOneWidget, ); // Test if LinearProgressIndicator is animating. await tester.pump(const Duration(seconds: 2)); expect(tester.hasRunningAnimations, isTrue); }); }
flutter/examples/api/test/material/progress_indicator/linear_progress_indicator.0_test.dart/0
{'file_path': 'flutter/examples/api/test/material/progress_indicator/linear_progress_indicator.0_test.dart', 'repo_id': 'flutter', 'token_count': 253}
// 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/heroes/hero.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Has Hero animation', (WidgetTester tester) async { await tester.pumpWidget( const example.HeroApp(), ); expect(find.text('Hero Sample'), findsOneWidget); await tester.tap(find.byType(Container)); await tester.pump(); Size heroSize = tester.getSize(find.byType(Container)); // Jump 25% into the transition (total length = 300ms) await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize.width.roundToDouble(), 103.0); expect(heroSize.height.roundToDouble(), 60.0); // Jump to 50% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize.width.roundToDouble(), 189.0); expect(heroSize.height.roundToDouble(), 146.0); // Jump to 75% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize.width.roundToDouble(), 199.0); expect(heroSize.height.roundToDouble(), 190.0); // Jump to 100% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize, const Size(200.0, 200.0)); expect(find.byIcon(Icons.arrow_back), findsOneWidget); await tester.tap(find.byIcon(Icons.arrow_back)); await tester.pump(); // Jump 25% into the transition (total length = 300ms) await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize.width.roundToDouble(), 199.0); expect(heroSize.height.roundToDouble(), 190.0); // Jump to 50% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize.width.roundToDouble(), 189.0); expect(heroSize.height.roundToDouble(), 146.0); // Jump to 75% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize.width.roundToDouble(), 103.0); expect(heroSize.height.roundToDouble(), 60.0); // Jump to 100% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byType(Container)); expect(heroSize, const Size(50.0, 50.0)); }); }
flutter/examples/api/test/widgets/heroes/hero.0_test.dart/0
{'file_path': 'flutter/examples/api/test/widgets/heroes/hero.0_test.dart', 'repo_id': 'flutter', 'token_count': 1033}
// 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 '../widgets/gestures.dart'; void main() { testWidgets('Tap on center change color', (WidgetTester tester) async { await tester.pumpWidget(const Directionality( textDirection: TextDirection.ltr, child: GestureDemo(), )); final Finder finder = find.byType(GestureDemo); MaterialColor getSwatch() => tester.state<GestureDemoState>(finder).swatch; Future<void> tap() async { final Offset topLeft = tester.getTopLeft(finder); await tester.tapAt(tester.getSize(finder).center(topLeft)); await tester.pump(const Duration(seconds: 1)); } // initial swatch expect(getSwatch(), GestureDemoState.kSwatches[0]); // every tap change swatch for (int i = 1; i < GestureDemoState.kSwatches.length; i++) { await tap(); expect(getSwatch(), GestureDemoState.kSwatches[i]); } // tap on last swatch display first swatch await tap(); expect(getSwatch(), GestureDemoState.kSwatches[0]); }); }
flutter/examples/layers/test/gestures_test.dart/0
{'file_path': 'flutter/examples/layers/test/gestures_test.dart', 'repo_id': 'flutter', 'token_count': 452}
include: ../analysis_options.yaml analyzer: exclude: - "test_fixes/**"
flutter/packages/flutter/analysis_options.yaml/0
{'file_path': 'flutter/packages/flutter/analysis_options.yaml', 'repo_id': 'flutter', 'token_count': 31}
// 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 Flutter semantics package. /// /// To use, import `package:flutter/semantics.dart`. /// /// The [SemanticsEvent] classes define the protocol for sending semantic events /// to the platform. /// /// The [SemanticsNode] hierarchy represents the semantic structure of the UI /// and is used by the platform-specific accessibility services. library semantics; export 'dart:ui' show LocaleStringAttribute, SpellOutStringAttribute; export 'src/semantics/binding.dart'; export 'src/semantics/debug.dart'; export 'src/semantics/semantics.dart'; export 'src/semantics/semantics_event.dart'; export 'src/semantics/semantics_service.dart';
flutter/packages/flutter/lib/semantics.dart/0
{'file_path': 'flutter/packages/flutter/lib/semantics.dart', '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. // Examples can assume: // class Cat { } /// A category with which to annotate a class, for documentation /// purposes. /// /// A category is usually represented as a section and a subsection, each /// of which is a string. The engineering team that owns the library to which /// the class belongs defines the categories used for classes in that library. /// For example, the Flutter engineering team has defined categories like /// "Basic/Buttons" and "Material Design/Buttons" for Flutter widgets. /// /// A class can have multiple categories. /// /// {@tool snippet} /// /// ```dart /// /// A copper coffee pot, as desired by Ben Turpin. /// /// ...documentation... /// @Category(<String>['Pots', 'Coffee']) /// @Category(<String>['Copper', 'Cookware']) /// @DocumentationIcon('https://example.com/images/coffee.png') /// @Summary('A proper cup of coffee is made in a proper copper coffee pot.') /// class CopperCoffeePot { /// // ...code... /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [DocumentationIcon], which is used to give the URL to an image that /// represents the class. /// * [Summary], which is used to provide a one-line description of a /// class that overrides the inline documentations' own description. class Category { /// Create an annotation to provide a categorization of a class. const Category(this.sections); /// The strings the correspond to the section and subsection of the /// category represented by this object. /// /// By convention, this list usually has two items. The allowed values /// are defined by the team that owns the library to which the annotated /// class belongs. final List<String> sections; } /// A class annotation to provide a URL to an image that represents the class. /// /// Each class should only have one [DocumentationIcon]. /// /// {@tool snippet} /// /// ```dart /// /// Utility class for beginning a dream-sharing sequence. /// /// ...documentation... /// @Category(<String>['Military Technology', 'Experimental']) /// @DocumentationIcon('https://docs.example.org/icons/top.png') /// class DreamSharing { /// // ...code... /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [Category], to help place the class in an index. /// * [Summary], which is used to provide a one-line description of a /// class that overrides the inline documentations' own description. class DocumentationIcon { /// Create an annotation to provide a URL to an image describing a class. const DocumentationIcon(this.url); /// The URL to an image that represents the annotated class. final String url; } /// An annotation that provides a short description of a class for use /// in an index. /// /// Usually the first paragraph of the documentation for a class can be used /// for this purpose, but on occasion the first paragraph is either too short /// or too long for use in isolation, without the remainder of the documentation. /// /// {@tool snippet} /// /// ```dart /// /// A famous cat. /// /// /// /// Instances of this class can hunt small animals. /// /// This cat has three legs. /// @Category(<String>['Animals', 'Cats']) /// @Category(<String>['Cute', 'Pets']) /// @DocumentationIcon('https://www.examples.net/docs/images/icons/pillar.jpeg') /// @Summary('A famous three-legged cat.') /// class Pillar extends Cat { /// // ...code... /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [Category], to help place the class in an index. /// * [DocumentationIcon], which is used to give the URL to an image that /// represents the class. class Summary { /// Create an annotation to provide a short description of a class. const Summary(this.text); /// The text of the summary of the annotated class. final String text; }
flutter/packages/flutter/lib/src/foundation/annotations.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/foundation/annotations.dart', 'repo_id': 'flutter', 'token_count': 1074}
// 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'; // Any changes to this file should be reflected in the debugAssertAllGesturesVarsUnset() // function below. /// Whether to print the results of each hit test to the console. /// /// When this is set, in debug mode, any time a hit test is triggered by the /// [GestureBinding] the results are dumped to the console. /// /// This has no effect in release builds. bool debugPrintHitTestResults = false; /// Whether to print the details of each mouse hover event to the console. /// /// When this is set, in debug mode, any time a mouse hover event is triggered /// by the [GestureBinding], the results are dumped to the console. /// /// This has no effect in release builds, and only applies to mouse hover /// events. bool debugPrintMouseHoverEvents = false; /// Prints information about gesture recognizers and gesture arenas. /// /// This flag only has an effect in debug mode. /// /// See also: /// /// * [GestureArenaManager], the class that manages gesture arenas. /// * [debugPrintRecognizerCallbacksTrace], for debugging issues with /// gesture recognizers. bool debugPrintGestureArenaDiagnostics = false; /// Logs a message every time a gesture recognizer callback is invoked. /// /// This flag only has an effect in debug mode. /// /// This is specifically used by [GestureRecognizer.invokeCallback]. Gesture /// recognizers that do not use this method to invoke callbacks may not honor /// the [debugPrintRecognizerCallbacksTrace] flag. /// /// See also: /// /// * [debugPrintGestureArenaDiagnostics], for debugging issues with gesture /// arenas. bool debugPrintRecognizerCallbacksTrace = false; /// Whether to print the resampling margin to the console. /// /// When this is set, in debug mode, any time resampling is triggered by the /// [GestureBinding] the resampling margin is dumped to the console. The /// resampling margin is the delta between the time of the last received /// touch event and the current sample time. Positive value indicates that /// resampling is effective and the resampling offset can potentially be /// reduced for improved latency. Negative value indicates that resampling /// is failing and resampling offset needs to be increased for smooth /// touch event processing. /// /// This has no effect in release builds. bool debugPrintResamplingMargin = false; /// Returns true if none of the gestures 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 gestures library](gestures/gestures-library.html) for a complete /// list. bool debugAssertAllGesturesVarsUnset(String reason) { assert(() { if (debugPrintHitTestResults || debugPrintGestureArenaDiagnostics || debugPrintRecognizerCallbacksTrace || debugPrintResamplingMargin) { throw FlutterError(reason); } return true; }()); return true; }
flutter/packages/flutter/lib/src/gestures/debug.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/gestures/debug.dart', 'repo_id': 'flutter', 'token_count': 846}
// 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:collection'; import 'events.dart'; export 'events.dart' show PointerEvent; /// A callback used by [PointerEventResampler.sample] and /// [PointerEventResampler.stop] to process a resampled `event`. typedef HandleEventCallback = void Function(PointerEvent event); /// Class for pointer event resampling. /// /// An instance of this class can be used to resample one sequence /// of pointer events. Multiple instances are expected to be used for /// multi-touch support. The sampling frequency and the sampling /// offset is determined by the caller. /// /// This can be used to get smooth touch event processing at the cost /// of adding some latency. Devices with low frequency sensors or when /// the frequency is not a multiple of the display frequency /// (e.g., 120Hz input and 90Hz display) benefit from this. /// /// The following pointer event types are supported: /// [PointerAddedEvent], [PointerHoverEvent], [PointerDownEvent], /// [PointerMoveEvent], [PointerCancelEvent], [PointerUpEvent], /// [PointerRemovedEvent]. /// /// Resampling is currently limited to event position and delta. All /// pointer event types except [PointerAddedEvent] will be resampled. /// [PointerHoverEvent] and [PointerMoveEvent] will only be generated /// when the position has changed. class PointerEventResampler { // Events queued for processing. final Queue<PointerEvent> _queuedEvents = Queue<PointerEvent>(); // Pointer state required for resampling. PointerEvent? _last; PointerEvent? _next; Offset _position = Offset.zero; bool _isTracked = false; bool _isDown = false; int _pointerIdentifier = 0; int _hasButtons = 0; PointerEvent _toHoverEvent( PointerEvent event, Offset position, Offset delta, Duration timeStamp, int buttons, ) { return PointerHoverEvent( timeStamp: timeStamp, kind: event.kind, device: event.device, position: position, delta: delta, buttons: event.buttons, obscured: event.obscured, pressureMin: event.pressureMin, pressureMax: event.pressureMax, distance: event.distance, distanceMax: event.distanceMax, size: event.size, radiusMajor: event.radiusMajor, radiusMinor: event.radiusMinor, radiusMin: event.radiusMin, radiusMax: event.radiusMax, orientation: event.orientation, tilt: event.tilt, synthesized: event.synthesized, embedderId: event.embedderId, ); } PointerEvent _toMoveEvent( PointerEvent event, Offset position, Offset delta, int pointerIdentifier, Duration timeStamp, int buttons, ) { return PointerMoveEvent( timeStamp: timeStamp, pointer: pointerIdentifier, kind: event.kind, device: event.device, position: position, delta: delta, buttons: buttons, obscured: event.obscured, pressure: event.pressure, pressureMin: event.pressureMin, pressureMax: event.pressureMax, distanceMax: event.distanceMax, size: event.size, radiusMajor: event.radiusMajor, radiusMinor: event.radiusMinor, radiusMin: event.radiusMin, radiusMax: event.radiusMax, orientation: event.orientation, tilt: event.tilt, platformData: event.platformData, synthesized: event.synthesized, embedderId: event.embedderId, ); } PointerEvent _toMoveOrHoverEvent( PointerEvent event, Offset position, Offset delta, int pointerIdentifier, Duration timeStamp, bool isDown, int buttons, ) { return isDown ? _toMoveEvent( event, position, delta, pointerIdentifier, timeStamp, buttons) : _toHoverEvent(event, position, delta, timeStamp, buttons); } Offset _positionAt(Duration sampleTime) { // Use `next` position by default. double x = _next?.position.dx ?? 0.0; double y = _next?.position.dy ?? 0.0; final Duration nextTimeStamp = _next?.timeStamp ?? Duration.zero; final Duration lastTimeStamp = _last?.timeStamp ?? Duration.zero; // Resample if `next` time stamp is past `sampleTime`. if (nextTimeStamp > sampleTime && nextTimeStamp > lastTimeStamp) { final double interval = (nextTimeStamp - lastTimeStamp).inMicroseconds.toDouble(); final double scalar = (sampleTime - lastTimeStamp).inMicroseconds.toDouble() / interval; final double lastX = _last?.position.dx ?? 0.0; final double lastY = _last?.position.dy ?? 0.0; x = lastX + (x - lastX) * scalar; y = lastY + (y - lastY) * scalar; } return Offset(x, y); } void _processPointerEvents(Duration sampleTime) { final Iterator<PointerEvent> it = _queuedEvents.iterator; while (it.moveNext()) { final PointerEvent event = it.current; // Update both `last` and `next` pointer event if time stamp is older // or equal to `sampleTime`. if (event.timeStamp <= sampleTime || _last == null) { _last = event; _next = event; continue; } // Update only `next` pointer event if time stamp is more recent than // `sampleTime` and next event is not already more recent. final Duration nextTimeStamp = _next?.timeStamp ?? Duration.zero; if (nextTimeStamp < sampleTime) { _next = event; break; } } } void _dequeueAndSampleNonHoverOrMovePointerEventsUntil( Duration sampleTime, Duration nextSampleTime, HandleEventCallback callback, ) { Duration endTime = sampleTime; // Scan queued events to determine end time. final Iterator<PointerEvent> it = _queuedEvents.iterator; while (it.moveNext()) { final PointerEvent event = it.current; // Potentially stop dispatching events if more recent than `sampleTime`. if (event.timeStamp > sampleTime) { // Definitely stop if more recent than `nextSampleTime`. if (event.timeStamp >= nextSampleTime) { break; } // Update `endTime` to allow early processing of up and removed // events as this improves resampling of these events, which is // important for fling animations. if (event is PointerUpEvent || event is PointerRemovedEvent) { endTime = event.timeStamp; continue; } // Stop if event is not move or hover. if (event is! PointerMoveEvent && event is! PointerHoverEvent) { break; } } } while (_queuedEvents.isNotEmpty) { final PointerEvent event = _queuedEvents.first; // Stop dispatching events if more recent than `endTime`. if (event.timeStamp > endTime) { break; } final bool wasTracked = _isTracked; final bool wasDown = _isDown; final int hadButtons = _hasButtons; // Update pointer state. _isTracked = event is! PointerRemovedEvent; _isDown = event.down; _hasButtons = event.buttons; // Position at `sampleTime`. final Offset position = _positionAt(sampleTime); // Initialize position if we are starting to track this pointer. if (_isTracked && !wasTracked) { _position = position; } // Current pointer identifier. final int pointerIdentifier = event.pointer; // Initialize pointer identifier for `move` events. // Identifier is expected to be the same while `down`. assert(!wasDown || _pointerIdentifier == pointerIdentifier); _pointerIdentifier = pointerIdentifier; // Skip `move` and `hover` events as they are automatically // generated when the position has changed. if (event is! PointerMoveEvent && event is! PointerHoverEvent) { // Add synthetics `move` or `hover` event if position has changed. // Note: Devices without `hover` events are expected to always have // `add` and `down` events with the same position and this logic will // therefore never produce `hover` events. if (position != _position) { final Offset delta = position - _position; callback(_toMoveOrHoverEvent(event, position, delta, _pointerIdentifier, sampleTime, wasDown, hadButtons)); _position = position; } callback(event.copyWith( position: position, delta: Offset.zero, pointer: pointerIdentifier, timeStamp: sampleTime, )); } _queuedEvents.removeFirst(); } } void _samplePointerPosition( Duration sampleTime, HandleEventCallback callback, ) { // Position at `sampleTime`. final Offset position = _positionAt(sampleTime); // Add `move` or `hover` events if position has changed. final PointerEvent? next = _next; if (position != _position && next != null) { final Offset delta = position - _position; callback(_toMoveOrHoverEvent(next, position, delta, _pointerIdentifier, sampleTime, _isDown, _hasButtons)); _position = position; } } /// Enqueue pointer `event` for resampling. void addEvent(PointerEvent event) { _queuedEvents.add(event); } /// Dispatch resampled pointer events for the specified `sampleTime` /// by calling [callback]. /// /// This may dispatch multiple events if position is not the only /// state that has changed since last sample. /// /// Calling [callback] must not add or sample events. /// /// Positive value for `nextSampleTime` allow early processing of /// up and removed events. This improves resampling of these events, /// which is important for fling animations. void sample( Duration sampleTime, Duration nextSampleTime, HandleEventCallback callback, ) { _processPointerEvents(sampleTime); // Dequeue and sample pointer events until `sampleTime`. _dequeueAndSampleNonHoverOrMovePointerEventsUntil(sampleTime, nextSampleTime, callback); // Dispatch resampled pointer location event if tracked. if (_isTracked) { _samplePointerPosition(sampleTime, callback); } } /// Stop resampling. /// /// This will dispatch pending events by calling [callback] and reset /// internal state. void stop(HandleEventCallback callback) { while (_queuedEvents.isNotEmpty) { callback(_queuedEvents.removeFirst()); } _pointerIdentifier = 0; _isDown = false; _isTracked = false; _position = Offset.zero; _next = null; _last = null; } /// Returns `true` if a call to [sample] can dispatch more events. bool get hasPendingEvents => _queuedEvents.isNotEmpty; /// Returns `true` if pointer is currently tracked. bool get isTracked => _isTracked; /// Returns `true` if pointer is currently down. bool get isDown => _isDown; }
flutter/packages/flutter/lib/src/gestures/resampler.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/gestures/resampler.dart', 'repo_id': 'flutter', 'token_count': 3883}
// 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 _$home_menu = _AnimatedIconData( Size(48.0, 48.0), <_PathFrames>[ _PathFrames( opacities: <double>[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.634146341463, 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(41.961602748986124, 36.01074618636323), Offset(41.61012274691143, 36.52041429443682), Offset(40.73074694162982, 37.67330625857439), Offset(38.95361640675702, 39.597004636313734), Offset(35.56126879040947, 42.254157368159426), Offset(29.45217770721976, 44.90815523939214), Offset(20.31425476555182, 45.290666483987), Offset(11.333081294378362, 41.505038353879655), Offset(5.639760014140567, 35.39204919789558), Offset(3.1052482171005202, 29.50332128779013), Offset(2.404116971035613, 24.703586146049652), Offset(2.598975684223376, 21.02118219738726), Offset(3.169562607312212, 18.258042555457294), Offset(3.8457725409130035, 16.209986341924132), Offset(4.491857018848872, 14.709706425920167), Offset(5.042760982134354, 13.631765527094924), Offset(5.471212748718976, 12.884189626374933), Offset(5.770140143051716, 12.400456609777674), Offset(5.943251827328922, 12.132774431470317), Offset(5.999943741061273, 12.046959719775653), Offset(5.9999999999999964, 12.046875000000004), ], ), _PathCubicTo( <Offset>[ Offset(41.961602748986124, 36.01074618636323), Offset(41.61012274691143, 36.52041429443682), Offset(40.73074694162982, 37.67330625857439), Offset(38.95361640675702, 39.597004636313734), Offset(35.56126879040947, 42.254157368159426), Offset(29.45217770721976, 44.90815523939214), Offset(20.31425476555182, 45.290666483987), Offset(11.333081294378362, 41.505038353879655), Offset(5.639760014140567, 35.39204919789558), Offset(3.1052482171005202, 29.50332128779013), Offset(2.404116971035613, 24.703586146049652), Offset(2.598975684223376, 21.02118219738726), Offset(3.169562607312212, 18.258042555457294), Offset(3.8457725409130035, 16.209986341924132), Offset(4.491857018848872, 14.709706425920167), Offset(5.042760982134354, 13.631765527094924), Offset(5.471212748718976, 12.884189626374933), Offset(5.770140143051716, 12.400456609777674), Offset(5.943251827328922, 12.132774431470317), Offset(5.999943741061273, 12.046959719775653), Offset(5.9999999999999964, 12.046875000000004), ], <Offset>[ Offset(41.97427088111201, 32.057641484479724), Offset(41.73604180244445, 32.56929525585058), Offset(41.121377806968006, 33.73952883824795), Offset(39.81729775857236, 35.739382079848234), Offset(37.1732602008072, 38.64463095068733), Offset(32.08695737071304, 41.96110020250069), Offset(23.93217304852415, 43.69759882586336), Offset(15.2830121061518, 41.66392148019527), Offset(9.234232376942689, 37.03733509970011), Offset(6.058741440847815, 32.130881951771805), Offset(4.6970485662914285, 27.923782097401467), Offset(4.310954600883996, 24.584372545170346), Offset(4.402665831815483, 22.013925101989418), Offset(4.698295162721713, 20.070090284168355), Offset(5.0503340012927325, 18.62318323378621), Offset(5.38119368862878, 17.57037702974403), Offset(5.652345022660288, 16.833162703639687), Offset(5.847293032367528, 16.35282864404965), Offset(5.962087095621268, 16.085854559458284), Offset(5.999962347024592, 16.000084719731866), Offset(5.9999999999999964, 16.000000000000004), ], <Offset>[ Offset(41.97427088111201, 32.057641484479724), Offset(41.73604180244445, 32.56929525585058), Offset(41.121377806968006, 33.73952883824795), Offset(39.81729775857236, 35.739382079848234), Offset(37.1732602008072, 38.64463095068733), Offset(32.08695737071304, 41.96110020250069), Offset(23.93217304852415, 43.69759882586336), Offset(15.2830121061518, 41.66392148019527), Offset(9.234232376942689, 37.03733509970011), Offset(6.058741440847815, 32.130881951771805), Offset(4.6970485662914285, 27.923782097401467), Offset(4.310954600883996, 24.584372545170346), Offset(4.402665831815483, 22.013925101989418), Offset(4.698295162721713, 20.070090284168355), Offset(5.0503340012927325, 18.62318323378621), Offset(5.38119368862878, 17.57037702974403), Offset(5.652345022660288, 16.833162703639687), Offset(5.847293032367528, 16.35282864404965), Offset(5.962087095621268, 16.085854559458284), Offset(5.999962347024592, 16.000084719731866), Offset(5.9999999999999964, 16.000000000000004), ], ), _PathCubicTo( <Offset>[ Offset(41.97427088111201, 32.057641484479724), Offset(41.73604180244445, 32.56929525585058), Offset(41.121377806968006, 33.73952883824795), Offset(39.81729775857236, 35.739382079848234), Offset(37.1732602008072, 38.64463095068733), Offset(32.08695737071304, 41.96110020250069), Offset(23.93217304852415, 43.69759882586336), Offset(15.2830121061518, 41.66392148019527), Offset(9.234232376942689, 37.03733509970011), Offset(6.058741440847815, 32.130881951771805), Offset(4.6970485662914285, 27.923782097401467), Offset(4.310954600883996, 24.584372545170346), Offset(4.402665831815483, 22.013925101989418), Offset(4.698295162721713, 20.070090284168355), Offset(5.0503340012927325, 18.62318323378621), Offset(5.38119368862878, 17.57037702974403), Offset(5.652345022660288, 16.833162703639687), Offset(5.847293032367528, 16.35282864404965), Offset(5.962087095621268, 16.085854559458284), Offset(5.999962347024592, 16.000084719731866), Offset(5.9999999999999964, 16.000000000000004), ], <Offset>[ Offset(5.9744557303626635, 31.942276360297758), Offset(5.75430953010175, 31.42258575407952), Offset(5.297570785497186, 30.182163171294633), Offset(4.687011710760039, 27.874078385846133), Offset(4.3023160669901515, 23.964677553231365), Offset(5.248954188903129, 17.96690121163705), Offset(9.424552952409986, 10.750232327965165), Offset(16.729916149753336, 5.693010055981826), Offset(24.217389364126984, 4.303484017106875), Offset(29.987199029044564, 5.234248009029647), Offset(34.02246940389847, 7.042697530328738), Offset(36.75992915144614, 8.993860987913147), Offset(38.606434160708815, 10.7844000851691), Offset(39.851178494463575, 12.30640601283526), Offset(40.68926904209655, 13.537290081412095), Offset(41.24902334121195, 14.488365346885672), Offset(41.61453462747447, 15.183641916442898), Offset(41.840435984789025, 15.650218932651905), Offset(41.96167845880022, 15.914327056906625), Offset(41.99996234662585, 15.999915280445354), Offset(42.0, 15.999999999999996), ], <Offset>[ Offset(5.9744557303626635, 31.942276360297758), Offset(5.75430953010175, 31.42258575407952), Offset(5.297570785497186, 30.182163171294633), Offset(4.687011710760039, 27.874078385846133), Offset(4.3023160669901515, 23.964677553231365), Offset(5.248954188903129, 17.96690121163705), Offset(9.424552952409986, 10.750232327965165), Offset(16.729916149753336, 5.693010055981826), Offset(24.217389364126984, 4.303484017106875), Offset(29.987199029044564, 5.234248009029647), Offset(34.02246940389847, 7.042697530328738), Offset(36.75992915144614, 8.993860987913147), Offset(38.606434160708815, 10.7844000851691), Offset(39.851178494463575, 12.30640601283526), Offset(40.68926904209655, 13.537290081412095), Offset(41.24902334121195, 14.488365346885672), Offset(41.61453462747447, 15.183641916442898), Offset(41.840435984789025, 15.650218932651905), Offset(41.96167845880022, 15.914327056906625), Offset(41.99996234662585, 15.999915280445354), Offset(42.0, 15.999999999999996), ], ), _PathCubicTo( <Offset>[ Offset(5.9744557303626635, 31.942276360297758), Offset(5.75430953010175, 31.42258575407952), Offset(5.297570785497186, 30.182163171294633), Offset(4.687011710760039, 27.874078385846133), Offset(4.3023160669901515, 23.964677553231365), Offset(5.248954188903129, 17.96690121163705), Offset(9.424552952409986, 10.750232327965165), Offset(16.729916149753336, 5.693010055981826), Offset(24.217389364126984, 4.303484017106875), Offset(29.987199029044564, 5.234248009029647), Offset(34.02246940389847, 7.042697530328738), Offset(36.75992915144614, 8.993860987913147), Offset(38.606434160708815, 10.7844000851691), Offset(39.851178494463575, 12.30640601283526), Offset(40.68926904209655, 13.537290081412095), Offset(41.24902334121195, 14.488365346885672), Offset(41.61453462747447, 15.183641916442898), Offset(41.840435984789025, 15.650218932651905), Offset(41.96167845880022, 15.914327056906625), Offset(41.99996234662585, 15.999915280445354), Offset(42.0, 15.999999999999996), ], <Offset>[ Offset(5.96181263407102, 35.88756860229611), Offset(5.628639326457137, 35.36589625701638), Offset(4.907711917916583, 34.10816632794454), Offset(3.825037239086633, 31.72407718231862), Offset(2.6935104103679173, 27.567070519285533), Offset(2.6193815998436385, 20.90813202908801), Offset(5.813784705570013, 12.34015163103323), Offset(12.787791525354942, 5.534440927939556), Offset(20.630020701646604, 2.66144966846797), Offset(27.039542748427206, 2.6118801526843), Offset(31.73406929400877, 3.8288656025961956), Offset(35.05133359232832, 5.4377125182877375), Offset(37.37576789909982, 7.035940231416685), Offset(39.00034069997069, 8.453930734508514), Offset(40.13189576910416, 9.631547417435115), Offset(40.91125947405842, 10.557537661435477), Offset(41.43376032245399, 11.242473133797246), Offset(41.76343557153906, 11.705657910305364), Offset(41.94288041435826, 11.969059340238793), Offset(41.9999437774332, 12.054602780489052), Offset(42.0, 12.054687499999996), ], <Offset>[ Offset(5.96181263407102, 35.88756860229611), Offset(5.628639326457137, 35.36589625701638), Offset(4.907711917916583, 34.10816632794454), Offset(3.825037239086633, 31.72407718231862), Offset(2.6935104103679173, 27.567070519285533), Offset(2.6193815998436385, 20.90813202908801), Offset(5.813784705570013, 12.34015163103323), Offset(12.787791525354942, 5.534440927939556), Offset(20.630020701646604, 2.66144966846797), Offset(27.039542748427206, 2.6118801526843), Offset(31.73406929400877, 3.8288656025961956), Offset(35.05133359232832, 5.4377125182877375), Offset(37.37576789909982, 7.035940231416685), Offset(39.00034069997069, 8.453930734508514), Offset(40.13189576910416, 9.631547417435115), Offset(40.91125947405842, 10.557537661435477), Offset(41.43376032245399, 11.242473133797246), Offset(41.76343557153906, 11.705657910305364), Offset(41.94288041435826, 11.969059340238793), Offset(41.9999437774332, 12.054602780489052), Offset(42.0, 12.054687499999996), ], ), _PathCubicTo( <Offset>[ Offset(5.96181263407102, 35.88756860229611), Offset(5.628639326457137, 35.36589625701638), Offset(4.907711917916583, 34.10816632794454), Offset(3.825037239086633, 31.72407718231862), Offset(2.6935104103679173, 27.567070519285533), Offset(2.6193815998436385, 20.90813202908801), Offset(5.813784705570013, 12.34015163103323), Offset(12.787791525354942, 5.534440927939556), Offset(20.630020701646604, 2.66144966846797), Offset(27.039542748427206, 2.6118801526843), Offset(31.73406929400877, 3.8288656025961956), Offset(35.05133359232832, 5.4377125182877375), Offset(37.37576789909982, 7.035940231416685), Offset(39.00034069997069, 8.453930734508514), Offset(40.13189576910416, 9.631547417435115), Offset(40.91125947405842, 10.557537661435477), Offset(41.43376032245399, 11.242473133797246), Offset(41.76343557153906, 11.705657910305364), Offset(41.94288041435826, 11.969059340238793), Offset(41.9999437774332, 12.054602780489052), Offset(42.0, 12.054687499999996), ], <Offset>[ Offset(41.961602748986124, 36.01074618636323), Offset(41.61012274691143, 36.52041429443682), Offset(40.73074694162982, 37.67330625857439), Offset(38.95361640675702, 39.597004636313734), Offset(35.56126879040947, 42.254157368159426), Offset(29.45217770721976, 44.90815523939214), Offset(20.31425476555182, 45.290666483987), Offset(11.333081294378362, 41.505038353879655), Offset(5.639760014140567, 35.39204919789558), Offset(3.1052482171005202, 29.50332128779013), Offset(2.404116971035613, 24.703586146049652), Offset(2.598975684223376, 21.02118219738726), Offset(3.169562607312212, 18.258042555457294), Offset(3.8457725409130035, 16.209986341924132), Offset(4.491857018848872, 14.709706425920167), Offset(5.042760982134354, 13.631765527094924), Offset(5.471212748718976, 12.884189626374933), Offset(5.770140143051716, 12.400456609777674), Offset(5.943251827328922, 12.132774431470317), Offset(5.999943741061273, 12.046959719775653), Offset(5.9999999999999964, 12.046875000000004), ], <Offset>[ Offset(41.961602748986124, 36.01074618636323), Offset(41.61012274691143, 36.52041429443682), Offset(40.73074694162982, 37.67330625857439), Offset(38.95361640675702, 39.597004636313734), Offset(35.56126879040947, 42.254157368159426), Offset(29.45217770721976, 44.90815523939214), Offset(20.31425476555182, 45.290666483987), Offset(11.333081294378362, 41.505038353879655), Offset(5.639760014140567, 35.39204919789558), Offset(3.1052482171005202, 29.50332128779013), Offset(2.404116971035613, 24.703586146049652), Offset(2.598975684223376, 21.02118219738726), Offset(3.169562607312212, 18.258042555457294), Offset(3.8457725409130035, 16.209986341924132), Offset(4.491857018848872, 14.709706425920167), Offset(5.042760982134354, 13.631765527094924), Offset(5.471212748718976, 12.884189626374933), Offset(5.770140143051716, 12.400456609777674), Offset(5.943251827328922, 12.132774431470317), Offset(5.999943741061273, 12.046959719775653), Offset(5.9999999999999964, 12.046875000000004), ], ), _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, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(38.005915505011714, 22.044873132716152), Offset(38.49527667048537, 22.460937675484836), Offset(39.29605291379161, 23.509087727219047), Offset(40.090934628235715, 25.55307837508503), Offset(40.245484311889584, 29.064745081245363), Offset(38.450753318138695, 34.23676198345152), Offset(33.0728907045072, 39.641976680762035), Offset(25.27493194621109, 42.06583927008458), Offset(18.326968788774145, 41.199323151695744), Offset(13.530028647165079, 38.7776757262709), Offset(10.497349834922744, 36.06973233007009), Offset(8.641652255677663, 33.59797658699316), Offset(7.521978336487795, 31.514971860015343), Offset(6.854874126980906, 29.834780098541096), Offset(6.463082099174432, 28.52288741178727), Offset(6.237308044978324, 27.533663044350465), Offset(6.1105452413260615, 26.82265981608807), Offset(6.04246239664468, 26.35092390861118), Offset(6.009733624107838, 26.085741049230215), Offset(6.000009413493068, 26.000084719621103), Offset(6.0, 26.000000000000004), ], ), _PathCubicTo( <Offset>[ Offset(38.005915505011714, 22.044873132716152), Offset(38.49527667048537, 22.460937675484836), Offset(39.29605291379161, 23.509087727219047), Offset(40.090934628235715, 25.55307837508503), Offset(40.245484311889584, 29.064745081245363), Offset(38.450753318138695, 34.23676198345152), Offset(33.0728907045072, 39.641976680762035), Offset(25.27493194621109, 42.06583927008458), Offset(18.326968788774145, 41.199323151695744), Offset(13.530028647165079, 38.7776757262709), Offset(10.497349834922744, 36.06973233007009), Offset(8.641652255677663, 33.59797658699316), Offset(7.521978336487795, 31.514971860015343), Offset(6.854874126980906, 29.834780098541096), Offset(6.463082099174432, 28.52288741178727), Offset(6.237308044978324, 27.533663044350465), Offset(6.1105452413260615, 26.82265981608807), Offset(6.04246239664468, 26.35092390861118), Offset(6.009733624107838, 26.085741049230215), Offset(6.000009413493068, 26.000084719621103), Offset(6.0, 26.000000000000004), ], <Offset>[ Offset(10.006902842119626, 21.955147406089473), Offset(9.632135496378087, 21.541092072032644), Offset(9.099209938092097, 20.510489270395304), Offset(8.782988004431196, 18.54355650849138), Offset(9.385621621161075, 15.282927792774965), Offset(12.215268791957268, 10.781237663014041), Offset(18.587927795299567, 6.746065530872357), Offset(26.721835989812625, 6.094927845871137), Offset(33.31012577595844, 8.46547206910251), Offset(37.45848623536183, 11.881041783528742), Offset(39.822770672529785, 15.188647762997359), Offset(41.090626806239804, 18.007465029735965), Offset(41.72574666538112, 20.285446843195025), Offset(42.007757458722764, 22.071095827208), Offset(42.102017139978244, 23.436994259413154), Offset(42.10513769756149, 24.451651361492107), Offset(42.07273484614025, 25.17313902889128), Offset(42.03560534906618, 25.64831419721343), Offset(42.00932498728679, 25.914213546678557), Offset(42.000009413094325, 25.99991528033459), Offset(42.0, 25.999999999999996), ], <Offset>[ Offset(10.006902842119626, 21.955147406089473), Offset(9.632135496378087, 21.541092072032644), Offset(9.099209938092097, 20.510489270395304), Offset(8.782988004431196, 18.54355650849138), Offset(9.385621621161075, 15.282927792774965), Offset(12.215268791957268, 10.781237663014041), Offset(18.587927795299567, 6.746065530872357), Offset(26.721835989812625, 6.094927845871137), Offset(33.31012577595844, 8.46547206910251), Offset(37.45848623536183, 11.881041783528742), Offset(39.822770672529785, 15.188647762997359), Offset(41.090626806239804, 18.007465029735965), Offset(41.72574666538112, 20.285446843195025), Offset(42.007757458722764, 22.071095827208), Offset(42.102017139978244, 23.436994259413154), Offset(42.10513769756149, 24.451651361492107), Offset(42.07273484614025, 25.17313902889128), Offset(42.03560534906618, 25.64831419721343), Offset(42.00932498728679, 25.914213546678557), Offset(42.000009413094325, 25.99991528033459), Offset(42.0, 25.999999999999996), ], ), _PathCubicTo( <Offset>[ Offset(10.006902842119626, 21.955147406089473), Offset(9.632135496378087, 21.541092072032644), Offset(9.099209938092097, 20.510489270395304), Offset(8.782988004431196, 18.54355650849138), Offset(9.385621621161075, 15.282927792774965), Offset(12.215268791957268, 10.781237663014041), Offset(18.587927795299567, 6.746065530872357), Offset(26.721835989812625, 6.094927845871137), Offset(33.31012577595844, 8.46547206910251), Offset(37.45848623536183, 11.881041783528742), Offset(39.822770672529785, 15.188647762997359), Offset(41.090626806239804, 18.007465029735965), Offset(41.72574666538112, 20.285446843195025), Offset(42.007757458722764, 22.071095827208), Offset(42.102017139978244, 23.436994259413154), Offset(42.10513769756149, 24.451651361492107), Offset(42.07273484614025, 25.17313902889128), Offset(42.03560534906618, 25.64831419721343), Offset(42.00932498728679, 25.914213546678557), Offset(42.000009413094325, 25.99991528033459), Offset(42.0, 25.999999999999996), ], <Offset>[ Offset(9.991126102962665, 26.878296385119686), Offset(9.478546725862362, 26.36043822046848), Offset(8.639473946578361, 25.14017735498227), Offset(7.81032131475563, 22.887960789223563), Offset(7.650884598609569, 19.167302777578165), Offset(9.48709191219624, 13.832759399890797), Offset(14.921172139995065, 8.360637610125773), Offset(22.72506805378891, 5.934160729915408), Offset(29.673031211225855, 6.800676848304256), Offset(34.46997135283492, 9.222324273729102), Offset(37.502650165077256, 11.930267669929911), Offset(39.35834774432234, 14.402023413006837), Offset(40.47802166351221, 16.485028139984657), Offset(41.1451258730191, 18.165219901458904), Offset(41.53691790082557, 19.47711258821273), Offset(41.76269195502168, 20.466336955649535), Offset(41.889454758673935, 21.17734018391193), Offset(41.95753760335532, 21.64907609138882), Offset(41.99026637589216, 21.914258950769785), Offset(41.99999058650693, 21.999915280378897), Offset(42.0, 21.999999999999996), ], <Offset>[ Offset(9.991126102962665, 26.878296385119686), Offset(9.478546725862362, 26.36043822046848), Offset(8.639473946578361, 25.14017735498227), Offset(7.81032131475563, 22.887960789223563), Offset(7.650884598609569, 19.167302777578165), Offset(9.48709191219624, 13.832759399890797), Offset(14.921172139995065, 8.360637610125773), Offset(22.72506805378891, 5.934160729915408), Offset(29.673031211225855, 6.800676848304256), Offset(34.46997135283492, 9.222324273729102), Offset(37.502650165077256, 11.930267669929911), Offset(39.35834774432234, 14.402023413006837), Offset(40.47802166351221, 16.485028139984657), Offset(41.1451258730191, 18.165219901458904), Offset(41.53691790082557, 19.47711258821273), Offset(41.76269195502168, 20.466336955649535), Offset(41.889454758673935, 21.17734018391193), Offset(41.95753760335532, 21.64907609138882), Offset(41.99026637589216, 21.914258950769785), Offset(41.99999058650693, 21.999915280378897), Offset(42.0, 21.999999999999996), ], ), _PathCubicTo( <Offset>[ Offset(9.991126102962665, 26.878296385119686), Offset(9.478546725862362, 26.36043822046848), Offset(8.639473946578361, 25.14017735498227), Offset(7.81032131475563, 22.887960789223563), Offset(7.650884598609569, 19.167302777578165), Offset(9.48709191219624, 13.832759399890797), Offset(14.921172139995065, 8.360637610125773), Offset(22.72506805378891, 5.934160729915408), Offset(29.673031211225855, 6.800676848304256), Offset(34.46997135283492, 9.222324273729102), Offset(37.502650165077256, 11.930267669929911), Offset(39.35834774432234, 14.402023413006837), Offset(40.47802166351221, 16.485028139984657), Offset(41.1451258730191, 18.165219901458904), Offset(41.53691790082557, 19.47711258821273), Offset(41.76269195502168, 20.466336955649535), Offset(41.889454758673935, 21.17734018391193), Offset(41.95753760335532, 21.64907609138882), Offset(41.99026637589216, 21.914258950769785), Offset(41.99999058650693, 21.999915280378897), Offset(42.0, 21.999999999999996), ], <Offset>[ Offset(37.99013876585475, 26.968022111746365), Offset(38.34168789996964, 27.280283823920673), Offset(38.83631692227788, 28.138775811806013), Offset(39.118267938560145, 29.897482655817214), Offset(38.51074728933807, 32.949120066048565), Offset(35.722576438377665, 37.28828372032828), Offset(29.406135049202696, 41.25654876001545), Offset(21.278164010187375, 41.90507215412886), Offset(14.689874224041562, 39.53452793089749), Offset(10.541513764638172, 36.118958216471256), Offset(8.177229327470219, 32.81135223700264), Offset(6.909373193760196, 29.992534970264035), Offset(6.274253334618873, 27.714553156804975), Offset(5.992242541277232, 25.928904172792), Offset(5.897982860021752, 24.563005740586846), Offset(5.894862302438508, 23.548348638507893), Offset(5.927265153859754, 22.82686097110872), Offset(5.964394650933819, 22.35168580278657), Offset(5.990675012713211, 22.085786453321443), Offset(5.999990586905675, 22.00008471966541), Offset(6.0, 22.000000000000004), ], <Offset>[ Offset(37.99013876585475, 26.968022111746365), Offset(38.34168789996964, 27.280283823920673), Offset(38.83631692227788, 28.138775811806013), Offset(39.118267938560145, 29.897482655817214), Offset(38.51074728933807, 32.949120066048565), Offset(35.722576438377665, 37.28828372032828), Offset(29.406135049202696, 41.25654876001545), Offset(21.278164010187375, 41.90507215412886), Offset(14.689874224041562, 39.53452793089749), Offset(10.541513764638172, 36.118958216471256), Offset(8.177229327470219, 32.81135223700264), Offset(6.909373193760196, 29.992534970264035), Offset(6.274253334618873, 27.714553156804975), Offset(5.992242541277232, 25.928904172792), Offset(5.897982860021752, 24.563005740586846), Offset(5.894862302438508, 23.548348638507893), Offset(5.927265153859754, 22.82686097110872), Offset(5.964394650933819, 22.35168580278657), Offset(5.990675012713211, 22.085786453321443), Offset(5.999990586905675, 22.00008471966541), Offset(6.0, 22.000000000000004), ], ), _PathCubicTo( <Offset>[ Offset(37.99013876585475, 26.968022111746365), Offset(38.34168789996964, 27.280283823920673), Offset(38.83631692227788, 28.138775811806013), Offset(39.118267938560145, 29.897482655817214), Offset(38.51074728933807, 32.949120066048565), Offset(35.722576438377665, 37.28828372032828), Offset(29.406135049202696, 41.25654876001545), Offset(21.278164010187375, 41.90507215412886), Offset(14.689874224041562, 39.53452793089749), Offset(10.541513764638172, 36.118958216471256), Offset(8.177229327470219, 32.81135223700264), Offset(6.909373193760196, 29.992534970264035), Offset(6.274253334618873, 27.714553156804975), Offset(5.992242541277232, 25.928904172792), Offset(5.897982860021752, 24.563005740586846), Offset(5.894862302438508, 23.548348638507893), Offset(5.927265153859754, 22.82686097110872), Offset(5.964394650933819, 22.35168580278657), Offset(5.990675012713211, 22.085786453321443), Offset(5.999990586905675, 22.00008471966541), Offset(6.0, 22.000000000000004), ], <Offset>[ Offset(38.005915505011714, 22.044873132716152), Offset(38.49527667048537, 22.460937675484836), Offset(39.29605291379161, 23.509087727219047), Offset(40.090934628235715, 25.55307837508503), Offset(40.245484311889584, 29.064745081245363), Offset(38.450753318138695, 34.23676198345152), Offset(33.0728907045072, 39.641976680762035), Offset(25.27493194621109, 42.06583927008458), Offset(18.326968788774145, 41.199323151695744), Offset(13.530028647165079, 38.7776757262709), Offset(10.497349834922744, 36.06973233007009), Offset(8.641652255677663, 33.59797658699316), Offset(7.521978336487795, 31.514971860015343), Offset(6.854874126980906, 29.834780098541096), Offset(6.463082099174432, 28.52288741178727), Offset(6.237308044978324, 27.533663044350465), Offset(6.1105452413260615, 26.82265981608807), Offset(6.04246239664468, 26.35092390861118), Offset(6.009733624107838, 26.085741049230215), Offset(6.000009413493068, 26.000084719621103), Offset(6.0, 26.000000000000004), ], <Offset>[ Offset(38.005915505011714, 22.044873132716152), Offset(38.49527667048537, 22.460937675484836), Offset(39.29605291379161, 23.509087727219047), Offset(40.090934628235715, 25.55307837508503), Offset(40.245484311889584, 29.064745081245363), Offset(38.450753318138695, 34.23676198345152), Offset(33.0728907045072, 39.641976680762035), Offset(25.27493194621109, 42.06583927008458), Offset(18.326968788774145, 41.199323151695744), Offset(13.530028647165079, 38.7776757262709), Offset(10.497349834922744, 36.06973233007009), Offset(8.641652255677663, 33.59797658699316), Offset(7.521978336487795, 31.514971860015343), Offset(6.854874126980906, 29.834780098541096), Offset(6.463082099174432, 28.52288741178727), Offset(6.237308044978324, 27.533663044350465), Offset(6.1105452413260615, 26.82265981608807), Offset(6.04246239664468, 26.35092390861118), Offset(6.009733624107838, 26.085741049230215), Offset(6.000009413493068, 26.000084719621103), Offset(6.0, 26.000000000000004), ], ), _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, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(20.176179763180997, 21.987735903833876), Offset(20.55193618727129, 21.88909752977205), Offset(21.227655124257208, 21.71486474263169), Offset(22.13567600845661, 21.53308372554798), Offset(23.226514419921436, 21.464181986077985), Offset(24.4102783754196, 21.684041595886637), Offset(25.440842849032627, 22.309300738195095), Offset(26.03642252837242, 23.134721894037483), Offset(26.21244881576038, 23.97183703919535), Offset(26.123327546035636, 24.622256415770117), Offset(25.931014482213666, 25.0802342265462), Offset(25.71921080582189, 25.392852152910002), Offset(25.5230666408985, 25.604989383797584), Offset(25.3554718074648, 25.748833638139686), Offset(25.21948374988762, 25.846234627148135), Offset(25.114174554400172, 25.911632280813432), Offset(25.037072414338468, 25.95453414453137), Offset(24.98527999526863, 25.9811477091939), Offset(24.955944954391757, 25.995467904751596), Offset(24.946435804885212, 25.999995545483056), Offset(24.946426391602, 26.0), ], ), _PathCubicTo( <Offset>[ Offset(20.176179763180997, 21.987735903833876), Offset(20.55193618727129, 21.88909752977205), Offset(21.227655124257208, 21.71486474263169), Offset(22.13567600845661, 21.53308372554798), Offset(23.226514419921436, 21.464181986077985), Offset(24.4102783754196, 21.684041595886637), Offset(25.440842849032627, 22.309300738195095), Offset(26.03642252837242, 23.134721894037483), Offset(26.21244881576038, 23.97183703919535), Offset(26.123327546035636, 24.622256415770117), Offset(25.931014482213666, 25.0802342265462), Offset(25.71921080582189, 25.392852152910002), Offset(25.5230666408985, 25.604989383797584), Offset(25.3554718074648, 25.748833638139686), Offset(25.21948374988762, 25.846234627148135), Offset(25.114174554400172, 25.911632280813432), Offset(25.037072414338468, 25.95453414453137), Offset(24.98527999526863, 25.9811477091939), Offset(24.955944954391757, 25.995467904751596), Offset(24.946435804885212, 25.999995545483056), Offset(24.946426391602, 26.0), ], <Offset>[ Offset(10.006902842149625, 21.95514740608957), Offset(9.632135496348102, 21.541092072031688), Offset(9.099209938111999, 20.510489270397283), Offset(8.78298800447023, 18.543556508500117), Offset(9.385621621133684, 15.282927792762731), Offset(12.215268791942359, 10.781237663000711), Offset(18.58792779526773, 6.746065530800053), Offset(26.721835989812707, 6.094927845869137), Offset(33.31012577595927, 8.465472069100691), Offset(37.458486235363154, 11.881041783527248), Offset(39.82277067253141, 15.1886477629962), Offset(41.09062680624161, 18.007465029735098), Offset(41.72574666538303, 20.2854468431944), Offset(42.007757458724726, 22.07109582720757), Offset(42.10201713998023, 23.43699425941287), Offset(42.105137697563485, 24.451651361491937), Offset(42.07273484614225, 25.173139028891192), Offset(42.03560534906818, 25.64831419721339), Offset(42.00932498728879, 25.91421354667855), Offset(42.00000941309632, 25.99991528033459), Offset(42.000000000002004, 25.999999999999996), ], <Offset>[ Offset(10.006902842149625, 21.95514740608957), Offset(9.632135496348102, 21.541092072031688), Offset(9.099209938111999, 20.510489270397283), Offset(8.78298800447023, 18.543556508500117), Offset(9.385621621133684, 15.282927792762731), Offset(12.215268791942359, 10.781237663000711), Offset(18.58792779526773, 6.746065530800053), Offset(26.721835989812707, 6.094927845869137), Offset(33.31012577595927, 8.465472069100691), Offset(37.458486235363154, 11.881041783527248), Offset(39.82277067253141, 15.1886477629962), Offset(41.09062680624161, 18.007465029735098), Offset(41.72574666538303, 20.2854468431944), Offset(42.007757458724726, 22.07109582720757), Offset(42.10201713998023, 23.43699425941287), Offset(42.105137697563485, 24.451651361491937), Offset(42.07273484614225, 25.173139028891192), Offset(42.03560534906818, 25.64831419721339), Offset(42.00932498728879, 25.91421354667855), Offset(42.00000941309632, 25.99991528033459), Offset(42.000000000002004, 25.999999999999996), ], ), _PathCubicTo( <Offset>[ Offset(10.006902842149625, 21.95514740608957), Offset(9.632135496348102, 21.541092072031688), Offset(9.099209938111999, 20.510489270397283), Offset(8.78298800447023, 18.543556508500117), Offset(9.385621621133684, 15.282927792762731), Offset(12.215268791942359, 10.781237663000711), Offset(18.58792779526773, 6.746065530800053), Offset(26.721835989812707, 6.094927845869137), Offset(33.31012577595927, 8.465472069100691), Offset(37.458486235363154, 11.881041783527248), Offset(39.82277067253141, 15.1886477629962), Offset(41.09062680624161, 18.007465029735098), Offset(41.72574666538303, 20.2854468431944), Offset(42.007757458724726, 22.07109582720757), Offset(42.10201713998023, 23.43699425941287), Offset(42.105137697563485, 24.451651361491937), Offset(42.07273484614225, 25.173139028891192), Offset(42.03560534906818, 25.64831419721339), Offset(42.00932498728879, 25.91421354667855), Offset(42.00000941309632, 25.99991528033459), Offset(42.000000000002004, 25.999999999999996), ], <Offset>[ Offset(9.950103066904006, 39.679580365751406), Offset(9.115564488520917, 37.75018397768418), Offset(7.7454464103988485, 34.143319828138715), Offset(6.441070390954248, 29.003703867586243), Offset(6.213866824197122, 22.385033086525855), Offset(8.625212439492824, 14.796789248890494), Offset(14.838843583186215, 8.396889109087798), Offset(22.72506805378899, 5.934160729913408), Offset(29.67303121122669, 6.800676848302437), Offset(34.469971352836254, 9.222324273727608), Offset(37.50265016507888, 11.930267669928751), Offset(39.35834774432414, 14.40202341300597), Offset(40.478021663514106, 16.48502813998403), Offset(41.145125873021044, 18.165219901458475), Offset(41.53691790082755, 19.47711258821245), Offset(41.76269195502367, 20.46633695564936), Offset(41.88945475867594, 21.177340183911838), Offset(41.95753760335732, 21.649076091388782), Offset(41.990266375894166, 21.914258950769778), Offset(41.99999058650893, 21.999915280378897), Offset(42.000000000002004, 21.999999999999996), ], <Offset>[ Offset(9.950103066904006, 39.679580365751406), Offset(9.115564488520917, 37.75018397768418), Offset(7.7454464103988485, 34.143319828138715), Offset(6.441070390954248, 29.003703867586243), Offset(6.213866824197122, 22.385033086525855), Offset(8.625212439492824, 14.796789248890494), Offset(14.838843583186215, 8.396889109087798), Offset(22.72506805378899, 5.934160729913408), Offset(29.67303121122669, 6.800676848302437), Offset(34.469971352836254, 9.222324273727608), Offset(37.50265016507888, 11.930267669928751), Offset(39.35834774432414, 14.40202341300597), Offset(40.478021663514106, 16.48502813998403), Offset(41.145125873021044, 18.165219901458475), Offset(41.53691790082755, 19.47711258821245), Offset(41.76269195502367, 20.46633695564936), Offset(41.88945475867594, 21.177340183911838), Offset(41.95753760335732, 21.649076091388782), Offset(41.990266375894166, 21.914258950769778), Offset(41.99999058650893, 21.999915280378897), Offset(42.000000000002004, 21.999999999999996), ], ), _PathCubicTo( <Offset>[ Offset(9.950103066904006, 39.679580365751406), Offset(9.115564488520917, 37.75018397768418), Offset(7.7454464103988485, 34.143319828138715), Offset(6.441070390954248, 29.003703867586243), Offset(6.213866824197122, 22.385033086525855), Offset(8.625212439492824, 14.796789248890494), Offset(14.838843583186215, 8.396889109087798), Offset(22.72506805378899, 5.934160729913408), Offset(29.67303121122669, 6.800676848302437), Offset(34.469971352836254, 9.222324273727608), Offset(37.50265016507888, 11.930267669928751), Offset(39.35834774432414, 14.40202341300597), Offset(40.478021663514106, 16.48502813998403), Offset(41.145125873021044, 18.165219901458475), Offset(41.53691790082755, 19.47711258821245), Offset(41.76269195502367, 20.46633695564936), Offset(41.88945475867594, 21.177340183911838), Offset(41.95753760335732, 21.649076091388782), Offset(41.990266375894166, 21.914258950769778), Offset(41.99999058650893, 21.999915280378897), Offset(42.000000000002004, 21.999999999999996), ], <Offset>[ Offset(20.119379987935375, 39.71216886349571), Offset(20.035365179444106, 38.098189435424544), Offset(19.873891596544055, 35.347695300373125), Offset(19.793758394940628, 31.993231084634104), Offset(20.054759622984875, 28.566287279841106), Offset(20.820222022970064, 25.699593181776418), Offset(21.69175863695111, 23.96012431648284), Offset(22.0396545923487, 22.973954778081758), Offset(22.575354251027797, 22.307041818397096), Offset(23.13481266350873, 21.963538905970477), Offset(23.61089397476114, 21.82185413347875), Offset(23.986931743904425, 21.787410536180875), Offset(24.275341639029573, 21.804570680587215), Offset(24.49284022176112, 21.842957712390593), Offset(24.65438451073494, 21.88635295594771), Offset(24.771728811860356, 21.926317874970856), Offset(24.853792326872156, 21.958735299552014), Offset(24.90721224955777, 21.981909603369285), Offset(24.93688634299713, 21.995513308842824), Offset(24.946416978297822, 21.99999554552736), Offset(24.946426391602, 22.0), ], <Offset>[ Offset(20.119379987935375, 39.71216886349571), Offset(20.035365179444106, 38.098189435424544), Offset(19.873891596544055, 35.347695300373125), Offset(19.793758394940628, 31.993231084634104), Offset(20.054759622984875, 28.566287279841106), Offset(20.820222022970064, 25.699593181776418), Offset(21.69175863695111, 23.96012431648284), Offset(22.0396545923487, 22.973954778081758), Offset(22.575354251027797, 22.307041818397096), Offset(23.13481266350873, 21.963538905970477), Offset(23.61089397476114, 21.82185413347875), Offset(23.986931743904425, 21.787410536180875), Offset(24.275341639029573, 21.804570680587215), Offset(24.49284022176112, 21.842957712390593), Offset(24.65438451073494, 21.88635295594771), Offset(24.771728811860356, 21.926317874970856), Offset(24.853792326872156, 21.958735299552014), Offset(24.90721224955777, 21.981909603369285), Offset(24.93688634299713, 21.995513308842824), Offset(24.946416978297822, 21.99999554552736), Offset(24.946426391602, 22.0), ], ), _PathCubicTo( <Offset>[ Offset(20.119379987935375, 39.71216886349571), Offset(20.035365179444106, 38.098189435424544), Offset(19.873891596544055, 35.347695300373125), Offset(19.793758394940628, 31.993231084634104), Offset(20.054759622984875, 28.566287279841106), Offset(20.820222022970064, 25.699593181776418), Offset(21.69175863695111, 23.96012431648284), Offset(22.0396545923487, 22.973954778081758), Offset(22.575354251027797, 22.307041818397096), Offset(23.13481266350873, 21.963538905970477), Offset(23.61089397476114, 21.82185413347875), Offset(23.986931743904425, 21.787410536180875), Offset(24.275341639029573, 21.804570680587215), Offset(24.49284022176112, 21.842957712390593), Offset(24.65438451073494, 21.88635295594771), Offset(24.771728811860356, 21.926317874970856), Offset(24.853792326872156, 21.958735299552014), Offset(24.90721224955777, 21.981909603369285), Offset(24.93688634299713, 21.995513308842824), Offset(24.946416978297822, 21.99999554552736), Offset(24.946426391602, 22.0), ], <Offset>[ Offset(20.176179763180997, 21.987735903833876), Offset(20.55193618727129, 21.88909752977205), Offset(21.227655124257208, 21.71486474263169), Offset(22.13567600845661, 21.53308372554798), Offset(23.226514419921436, 21.464181986077985), Offset(24.410278375419598, 21.684041595886633), Offset(25.440842849032627, 22.309300738195095), Offset(26.03642252837242, 23.134721894037487), Offset(26.21244881576038, 23.971837039195353), Offset(26.123327546035632, 24.622256415770117), Offset(25.931014482213666, 25.0802342265462), Offset(25.71921080582189, 25.392852152910002), Offset(25.5230666408985, 25.604989383797584), Offset(25.3554718074648, 25.748833638139686), Offset(25.21948374988762, 25.846234627148135), Offset(25.114174554400172, 25.911632280813432), Offset(25.037072414338468, 25.95453414453137), Offset(24.98527999526863, 25.9811477091939), Offset(24.955944954391757, 25.995467904751596), Offset(24.946435804885212, 25.999995545483056), Offset(24.946426391602, 26.0), ], <Offset>[ Offset(20.176179763180997, 21.987735903833876), Offset(20.55193618727129, 21.88909752977205), Offset(21.227655124257208, 21.71486474263169), Offset(22.13567600845661, 21.53308372554798), Offset(23.226514419921436, 21.464181986077985), Offset(24.410278375419598, 21.684041595886633), Offset(25.440842849032627, 22.309300738195095), Offset(26.03642252837242, 23.134721894037487), Offset(26.21244881576038, 23.971837039195353), Offset(26.123327546035632, 24.622256415770117), Offset(25.931014482213666, 25.0802342265462), Offset(25.71921080582189, 25.392852152910002), Offset(25.5230666408985, 25.604989383797584), Offset(25.3554718074648, 25.748833638139686), Offset(25.21948374988762, 25.846234627148135), Offset(25.114174554400172, 25.911632280813432), Offset(25.037072414338468, 25.95453414453137), Offset(24.98527999526863, 25.9811477091939), Offset(24.955944954391757, 25.995467904751596), Offset(24.946435804885212, 25.999995545483056), Offset(24.946426391602, 26.0), ], ), _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, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(27.83663858395034, 22.012284634971753), Offset(27.57547597959216, 22.112932217745428), Offset(27.1676077276265, 22.304712254982665), Offset(26.73824662421029, 22.56355115802843), Offset(26.404591513129226, 22.883490887942344), Offset(26.255743734676358, 23.33395805057893), Offset(26.21997565073384, 24.078741473347776), Offset(25.9603454076513, 25.02604522191824), Offset(25.424645748972203, 25.692958181602904), Offset(24.865187336491275, 26.036461094029523), Offset(24.38910602523886, 26.17814586652125), Offset(24.013068256095575, 26.212589463819125), Offset(23.724658360970427, 26.195429319412785), Offset(23.50715977823888, 26.157042287609407), Offset(23.34561548926506, 26.11364704405229), Offset(23.228271188139644, 26.073682125029144), Offset(23.14620767312784, 26.041264700447986), Offset(23.092787750442234, 26.018090396630715), Offset(23.063113657002866, 26.004486691157176), Offset(23.053583021702178, 26.00000445447264), Offset(23.053573608398, 26.0), ], ), _PathCubicTo( <Offset>[ Offset(27.83663858395034, 22.012284634971753), Offset(27.57547597959216, 22.112932217745428), Offset(27.1676077276265, 22.304712254982665), Offset(26.73824662421029, 22.56355115802843), Offset(26.404591513129226, 22.883490887942344), Offset(26.255743734676358, 23.33395805057893), Offset(26.21997565073384, 24.078741473347776), Offset(25.9603454076513, 25.02604522191824), Offset(25.424645748972203, 25.692958181602904), Offset(24.865187336491275, 26.036461094029523), Offset(24.38910602523886, 26.17814586652125), Offset(24.013068256095575, 26.212589463819125), Offset(23.724658360970427, 26.195429319412785), Offset(23.50715977823888, 26.157042287609407), Offset(23.34561548926506, 26.11364704405229), Offset(23.228271188139644, 26.073682125029144), Offset(23.14620767312784, 26.041264700447986), Offset(23.092787750442234, 26.018090396630715), Offset(23.063113657002866, 26.004486691157176), Offset(23.053583021702178, 26.00000445447264), Offset(23.053573608398, 26.0), ], <Offset>[ Offset(38.00591550498171, 22.044873132716056), Offset(38.49527667051535, 22.460937675485788), Offset(39.29605291377171, 23.50908772721707), Offset(40.09093462819668, 25.55307837507629), Offset(40.245484311916975, 29.0647450812576), Offset(38.4507533181536, 34.23676198346485), Offset(33.07289070449873, 39.64197668074282), Offset(25.27493194621101, 42.065839270086585), Offset(18.32696878877331, 41.19932315169756), Offset(13.530028647163753, 38.77767572627239), Offset(10.497349834921115, 36.06973233007125), Offset(8.641652255675858, 33.59797658699403), Offset(7.521978336485894, 31.51497186001597), Offset(6.854874126978952, 29.834780098541525), Offset(6.463082099172453, 28.52288741178755), Offset(6.237308044976331, 27.53366304435064), Offset(6.110545241324058, 26.822659816088162), Offset(6.042462396642684, 26.350923908611218), Offset(6.009733624105834, 26.085741049230222), Offset(6.0000094134910675, 26.000084719621103), Offset(5.999999999998, 26.000000000000004), ], <Offset>[ Offset(38.00591550498171, 22.044873132716056), Offset(38.49527667051535, 22.460937675485788), Offset(39.29605291377171, 23.50908772721707), Offset(40.09093462819668, 25.55307837507629), Offset(40.245484311916975, 29.0647450812576), Offset(38.4507533181536, 34.23676198346485), Offset(33.07289070449873, 39.64197668074282), Offset(25.27493194621101, 42.065839270086585), Offset(18.32696878877331, 41.19932315169756), Offset(13.530028647163753, 38.77767572627239), Offset(10.497349834921115, 36.06973233007125), Offset(8.641652255675858, 33.59797658699403), Offset(7.521978336485894, 31.51497186001597), Offset(6.854874126978952, 29.834780098541525), Offset(6.463082099172453, 28.52288741178755), Offset(6.237308044976331, 27.53366304435064), Offset(6.110545241324058, 26.822659816088162), Offset(6.042462396642684, 26.350923908611218), Offset(6.009733624105834, 26.085741049230222), Offset(6.0000094134910675, 26.000084719621103), Offset(5.999999999998, 26.000000000000004), ], ), _PathCubicTo( <Offset>[ Offset(38.00591550498171, 22.044873132716056), Offset(38.49527667051535, 22.460937675485788), Offset(39.29605291377171, 23.50908772721707), Offset(40.09093462819668, 25.55307837507629), Offset(40.245484311916975, 29.0647450812576), Offset(38.4507533181536, 34.23676198346485), Offset(33.07289070449873, 39.64197668074282), Offset(25.27493194621101, 42.065839270086585), Offset(18.32696878877331, 41.19932315169756), Offset(13.530028647163753, 38.77767572627239), Offset(10.497349834921115, 36.06973233007125), Offset(8.641652255675858, 33.59797658699403), Offset(7.521978336485894, 31.51497186001597), Offset(6.854874126978952, 29.834780098541525), Offset(6.463082099172453, 28.52288741178755), Offset(6.237308044976331, 27.53366304435064), Offset(6.110545241324058, 26.822659816088162), Offset(6.042462396642684, 26.350923908611218), Offset(6.009733624105834, 26.085741049230222), Offset(6.0000094134910675, 26.000084719621103), Offset(5.999999999998, 26.000000000000004), ], <Offset>[ Offset(37.94911572973609, 39.76930609237789), Offset(37.978705662688164, 38.67002958113828), Offset(37.94228938605856, 37.14191828495851), Offset(37.74901701468069, 36.01322573416242), Offset(37.073729514980414, 36.166850375020715), Offset(34.860696965704065, 38.25231356935464), Offset(29.32380649241722, 41.29280025903057), Offset(21.278164010187293, 41.90507215413086), Offset(14.689874224040729, 39.53452793089931), Offset(10.541513764636846, 36.11895821647275), Offset(8.17722932746859, 32.8113522370038), Offset(6.909373193758391, 29.992534970264902), Offset(6.274253334616972, 27.7145531568056), Offset(5.992242541275278, 25.92890417279243), Offset(5.8979828600197735, 24.56300574058713), Offset(5.894862302436515, 23.548348638508063), Offset(5.92726515385775, 22.826860971108808), Offset(5.964394650931823, 22.35168580278661), Offset(5.990675012711208, 22.08578645332145), Offset(5.9999905869036745, 22.00008471966541), Offset(5.999999999998, 22.000000000000004), ], <Offset>[ Offset(37.94911572973609, 39.76930609237789), Offset(37.978705662688164, 38.67002958113828), Offset(37.94228938605856, 37.14191828495851), Offset(37.74901701468069, 36.01322573416242), Offset(37.073729514980414, 36.166850375020715), Offset(34.860696965704065, 38.25231356935464), Offset(29.32380649241722, 41.29280025903057), Offset(21.278164010187293, 41.90507215413086), Offset(14.689874224040729, 39.53452793089931), Offset(10.541513764636846, 36.11895821647275), Offset(8.17722932746859, 32.8113522370038), Offset(6.909373193758391, 29.992534970264902), Offset(6.274253334616972, 27.7145531568056), Offset(5.992242541275278, 25.92890417279243), Offset(5.8979828600197735, 24.56300574058713), Offset(5.894862302436515, 23.548348638508063), Offset(5.92726515385775, 22.826860971108808), Offset(5.964394650931823, 22.35168580278661), Offset(5.990675012711208, 22.08578645332145), Offset(5.9999905869036745, 22.00008471966541), Offset(5.999999999998, 22.000000000000004), ], ), _PathCubicTo( <Offset>[ Offset(37.94911572973609, 39.76930609237789), Offset(37.978705662688164, 38.67002958113828), Offset(37.94228938605856, 37.14191828495851), Offset(37.74901701468069, 36.01322573416242), Offset(37.073729514980414, 36.166850375020715), Offset(34.860696965704065, 38.25231356935464), Offset(29.32380649241722, 41.29280025903057), Offset(21.278164010187293, 41.90507215413086), Offset(14.689874224040729, 39.53452793089931), Offset(10.541513764636846, 36.11895821647275), Offset(8.17722932746859, 32.8113522370038), Offset(6.909373193758391, 29.992534970264902), Offset(6.274253334616972, 27.7145531568056), Offset(5.992242541275278, 25.92890417279243), Offset(5.8979828600197735, 24.56300574058713), Offset(5.894862302436515, 23.548348638508063), Offset(5.92726515385775, 22.826860971108808), Offset(5.964394650931823, 22.35168580278661), Offset(5.990675012711208, 22.08578645332145), Offset(5.9999905869036745, 22.00008471966541), Offset(5.999999999998, 22.000000000000004), ], <Offset>[ Offset(27.779838808704717, 39.73671759463359), Offset(27.058904971764974, 38.322024123397924), Offset(25.813844199913348, 35.937542812724104), Offset(24.396329010694313, 33.02369851711455), Offset(23.23283671619266, 29.985596181705468), Offset(22.665687382226825, 27.349509636468714), Offset(22.470891438652323, 25.72956505163552), Offset(21.96357747162758, 24.86527810596251), Offset(21.78755118423962, 24.028162960804647), Offset(21.876672453964368, 23.377743584229883), Offset(22.068985517786334, 22.9197657734538), Offset(22.28078919417811, 22.607147847089998), Offset(22.4769333591015, 22.395010616202416), Offset(22.6445281925352, 22.251166361860314), Offset(22.78051625011238, 22.153765372851865), Offset(22.885825445599828, 22.088367719186568), Offset(22.96292758566153, 22.04546585546863), Offset(23.014720004731373, 22.0188522908061), Offset(23.04405504560824, 22.004532095248404), Offset(23.053564195114788, 22.000004454516944), Offset(23.053573608398, 22.0), ], <Offset>[ Offset(27.779838808704717, 39.73671759463359), Offset(27.058904971764974, 38.322024123397924), Offset(25.813844199913348, 35.937542812724104), Offset(24.396329010694313, 33.02369851711455), Offset(23.23283671619266, 29.985596181705468), Offset(22.665687382226825, 27.349509636468714), Offset(22.470891438652323, 25.72956505163552), Offset(21.96357747162758, 24.86527810596251), Offset(21.78755118423962, 24.028162960804647), Offset(21.876672453964368, 23.377743584229883), Offset(22.068985517786334, 22.9197657734538), Offset(22.28078919417811, 22.607147847089998), Offset(22.4769333591015, 22.395010616202416), Offset(22.6445281925352, 22.251166361860314), Offset(22.78051625011238, 22.153765372851865), Offset(22.885825445599828, 22.088367719186568), Offset(22.96292758566153, 22.04546585546863), Offset(23.014720004731373, 22.0188522908061), Offset(23.04405504560824, 22.004532095248404), Offset(23.053564195114788, 22.000004454516944), Offset(23.053573608398, 22.0), ], ), _PathCubicTo( <Offset>[ Offset(27.779838808704717, 39.73671759463359), Offset(27.058904971764974, 38.322024123397924), Offset(25.813844199913348, 35.937542812724104), Offset(24.396329010694313, 33.02369851711455), Offset(23.23283671619266, 29.985596181705468), Offset(22.665687382226825, 27.349509636468714), Offset(22.470891438652323, 25.72956505163552), Offset(21.96357747162758, 24.86527810596251), Offset(21.78755118423962, 24.028162960804647), Offset(21.876672453964368, 23.377743584229883), Offset(22.068985517786334, 22.9197657734538), Offset(22.28078919417811, 22.607147847089998), Offset(22.4769333591015, 22.395010616202416), Offset(22.6445281925352, 22.251166361860314), Offset(22.78051625011238, 22.153765372851865), Offset(22.885825445599828, 22.088367719186568), Offset(22.96292758566153, 22.04546585546863), Offset(23.014720004731373, 22.0188522908061), Offset(23.04405504560824, 22.004532095248404), Offset(23.053564195114788, 22.000004454516944), Offset(23.053573608398, 22.0), ], <Offset>[ Offset(27.83663858395034, 22.012284634971753), Offset(27.57547597959216, 22.112932217745428), Offset(27.1676077276265, 22.304712254982665), Offset(26.738246624210294, 22.56355115802843), Offset(26.404591513129223, 22.883490887942344), Offset(26.25574373467636, 23.333958050578932), Offset(26.21997565073384, 24.078741473347776), Offset(25.9603454076513, 25.02604522191824), Offset(25.424645748972203, 25.692958181602904), Offset(24.865187336491275, 26.036461094029523), Offset(24.38910602523886, 26.17814586652125), Offset(24.013068256095575, 26.212589463819125), Offset(23.724658360970427, 26.195429319412785), Offset(23.50715977823888, 26.157042287609407), Offset(23.34561548926506, 26.11364704405229), Offset(23.228271188139644, 26.073682125029144), Offset(23.14620767312784, 26.041264700447986), Offset(23.092787750442234, 26.018090396630715), Offset(23.063113657002866, 26.004486691157176), Offset(23.053583021702178, 26.00000445447264), Offset(23.053573608398, 26.0), ], <Offset>[ Offset(27.83663858395034, 22.012284634971753), Offset(27.57547597959216, 22.112932217745428), Offset(27.1676077276265, 22.304712254982665), Offset(26.738246624210294, 22.56355115802843), Offset(26.404591513129223, 22.883490887942344), Offset(26.25574373467636, 23.333958050578932), Offset(26.21997565073384, 24.078741473347776), Offset(25.9603454076513, 25.02604522191824), Offset(25.424645748972203, 25.692958181602904), Offset(24.865187336491275, 26.036461094029523), Offset(24.38910602523886, 26.17814586652125), Offset(24.013068256095575, 26.212589463819125), Offset(23.724658360970427, 26.195429319412785), Offset(23.50715977823888, 26.157042287609407), Offset(23.34561548926506, 26.11364704405229), Offset(23.228271188139644, 26.073682125029144), Offset(23.14620767312784, 26.041264700447986), Offset(23.092787750442234, 26.018090396630715), Offset(23.063113657002866, 26.004486691157176), Offset(23.053583021702178, 26.00000445447264), Offset(23.053573608398, 26.0), ], ), _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, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(23.684125337085877, 6.32904503029285), Offset(24.757855588582725, 6.522328815913423), Offset(27.574407323116677, 7.305175651642309), Offset(34.29718691345236, 10.565460438397327), Offset(42.96465562696383, 18.312204872266342), Offset(45.05615687407709, 26.45166424954756), Offset(42.23233332042143, 35.60390079418309), Offset(35.26685178627038, 42.467757059973906), Offset(27.4197052006056, 45.36131120369138), Offset(21.001315853482343, 45.424469500769995), Offset(16.29765110355406, 44.215682562738714), Offset(12.97234991047133, 42.61158062881598), Offset(10.641290841160107, 41.016018618041265), Offset(9.0114530912401, 39.59946991291384), Offset(7.875830197056132, 38.422591589788325), Offset(7.093422401327867, 37.49694905895691), Offset(6.568745459991835, 36.81215692853645), Offset(6.237631760921833, 36.34901917317271), Offset(6.057380152594408, 36.08562753900215), Offset(6.000056479961543, 36.00008471951035), Offset(6.0000000000000036, 36.00000000000001), ], ), _PathCubicTo( <Offset>[ Offset(23.684125337085877, 6.32904503029285), Offset(24.757855588582725, 6.522328815913423), Offset(27.574407323116677, 7.305175651642309), Offset(34.29718691345236, 10.565460438397327), Offset(42.96465562696383, 18.312204872266342), Offset(45.05615687407709, 26.45166424954756), Offset(42.23233332042143, 35.60390079418309), Offset(35.26685178627038, 42.467757059973906), Offset(27.4197052006056, 45.36131120369138), Offset(21.001315853482343, 45.424469500769995), Offset(16.29765110355406, 44.215682562738714), Offset(12.97234991047133, 42.61158062881598), Offset(10.641290841160107, 41.016018618041265), Offset(9.0114530912401, 39.59946991291384), Offset(7.875830197056132, 38.422591589788325), Offset(7.093422401327867, 37.49694905895691), Offset(6.568745459991835, 36.81215692853645), Offset(6.237631760921833, 36.34901917317271), Offset(6.057380152594408, 36.08562753900215), Offset(6.000056479961543, 36.00008471951035), Offset(6.0000000000000036, 36.00000000000001), ], <Offset>[ Offset(23.689243079011977, 6.329061430625194), Offset(23.64011618905085, 6.48670734054237), Offset(23.133765296901146, 6.8642122589514845), Offset(19.98658162330333, 7.361465557774245), Offset(15.467378257263233, 6.032096680033179), Offset(19.194942220379907, 3.3307514773626146), Offset(27.75047360634506, 2.715037120490525), Offset(36.713755829871914, 6.4968456357604545), Offset(42.40286218778989, 12.627460121098146), Offset(44.92977344167909, 18.52783555802784), Offset(45.6230719411611, 23.334597995665984), Offset(45.42132446103347, 27.02106907155878), Offset(44.84505917005344, 29.786493601220947), Offset(44.16433642298196, 31.835785641580745), Offset(43.51476523785995, 33.33669843741421), Offset(42.96125205391104, 34.41493737609855), Offset(42.530935064806016, 35.16263614133967), Offset(42.23077471334334, 35.64640946177496), Offset(42.056971515773355, 35.91410003645049), Offset(42.0000564795628, 35.99991528022383), Offset(42.0, 35.99999999999999), ], <Offset>[ Offset(23.689243079011977, 6.329061430625194), Offset(23.64011618905085, 6.48670734054237), Offset(23.133765296901146, 6.8642122589514845), Offset(19.98658162330333, 7.361465557774245), Offset(15.467378257263233, 6.032096680033179), Offset(19.194942220379907, 3.3307514773626146), Offset(27.75047360634506, 2.715037120490525), Offset(36.713755829871914, 6.4968456357604545), Offset(42.40286218778989, 12.627460121098146), Offset(44.92977344167909, 18.52783555802784), Offset(45.6230719411611, 23.334597995665984), Offset(45.42132446103347, 27.02106907155878), Offset(44.84505917005344, 29.786493601220947), Offset(44.16433642298196, 31.835785641580745), Offset(43.51476523785995, 33.33669843741421), Offset(42.96125205391104, 34.41493737609855), Offset(42.530935064806016, 35.16263614133967), Offset(42.23077471334334, 35.64640946177496), Offset(42.056971515773355, 35.91410003645049), Offset(42.0000564795628, 35.99991528022383), Offset(42.0, 35.99999999999999), ], ), _PathCubicTo( <Offset>[ Offset(23.689243079011977, 6.329061430625194), Offset(23.64011618905085, 6.48670734054237), Offset(23.133765296901146, 6.8642122589514845), Offset(19.98658162330333, 7.361465557774245), Offset(15.467378257263233, 6.032096680033179), Offset(19.194942220379907, 3.3307514773626146), Offset(27.75047360634506, 2.715037120490525), Offset(36.713755829871914, 6.4968456357604545), Offset(42.40286218778989, 12.627460121098146), Offset(44.92977344167909, 18.52783555802784), Offset(45.6230719411611, 23.334597995665984), Offset(45.42132446103347, 27.02106907155878), Offset(44.84505917005344, 29.786493601220947), Offset(44.16433642298196, 31.835785641580745), Offset(43.51476523785995, 33.33669843741421), Offset(42.96125205391104, 34.41493737609855), Offset(42.530935064806016, 35.16263614133967), Offset(42.23077471334334, 35.64640946177496), Offset(42.056971515773355, 35.91410003645049), Offset(42.0000564795628, 35.99991528022383), Offset(42.0, 35.99999999999999), ], <Offset>[ Offset(4.256210085244433, 23.724986123422013), Offset(4.334340540250139, 22.918290544448126), Offset(4.683893395049303, 20.897955670871653), Offset(6.165631658910659, 16.538261784200643), Offset(10.04725752347015, 10.401464969282092), Offset(15.676813589860602, 6.207875011618711), Offset(24.053924042171055, 4.3051387362291464), Offset(32.7169878938482, 6.336078519804726), Offset(38.76576762305731, 10.962664900299892), Offset(41.94125855915219, 15.869118048228197), Offset(43.30295143370857, 20.076217902598536), Offset(43.689045399116004, 23.415627454829654), Offset(43.59733416818452, 25.98607489801058), Offset(43.30170483727829, 27.92990971583165), Offset(42.94966599870727, 29.37681676621379), Offset(42.618806311371216, 30.429622970255974), Offset(42.347654977339715, 31.166837296360313), Offset(42.15270696763247, 31.64717135595035), Offset(42.03791290437873, 31.914145440541716), Offset(42.00003765297541, 31.999915280268137), Offset(42.0, 31.999999999999996), ], <Offset>[ Offset(4.256210085244433, 23.724986123422013), Offset(4.334340540250139, 22.918290544448126), Offset(4.683893395049303, 20.897955670871653), Offset(6.165631658910659, 16.538261784200643), Offset(10.04725752347015, 10.401464969282092), Offset(15.676813589860602, 6.207875011618711), Offset(24.053924042171055, 4.3051387362291464), Offset(32.7169878938482, 6.336078519804726), Offset(38.76576762305731, 10.962664900299892), Offset(41.94125855915219, 15.869118048228197), Offset(43.30295143370857, 20.076217902598536), Offset(43.689045399116004, 23.415627454829654), Offset(43.59733416818452, 25.98607489801058), Offset(43.30170483727829, 27.92990971583165), Offset(42.94966599870727, 29.37681676621379), Offset(42.618806311371216, 30.429622970255974), Offset(42.347654977339715, 31.166837296360313), Offset(42.15270696763247, 31.64717135595035), Offset(42.03791290437873, 31.914145440541716), Offset(42.00003765297541, 31.999915280268137), Offset(42.0, 31.999999999999996), ], ), _PathCubicTo( <Offset>[ Offset(4.256210085244433, 23.724986123422013), Offset(4.334340540250139, 22.918290544448126), Offset(4.683893395049303, 20.897955670871653), Offset(6.165631658910659, 16.538261784200643), Offset(10.04725752347015, 10.401464969282092), Offset(15.676813589860602, 6.207875011618711), Offset(24.053924042171055, 4.3051387362291464), Offset(32.7169878938482, 6.336078519804726), Offset(38.76576762305731, 10.962664900299892), Offset(41.94125855915219, 15.869118048228197), Offset(43.30295143370857, 20.076217902598536), Offset(43.689045399116004, 23.415627454829654), Offset(43.59733416818452, 25.98607489801058), Offset(43.30170483727829, 27.92990971583165), Offset(42.94966599870727, 29.37681676621379), Offset(42.618806311371216, 30.429622970255974), Offset(42.347654977339715, 31.166837296360313), Offset(42.15270696763247, 31.64717135595035), Offset(42.03791290437873, 31.914145440541716), Offset(42.00003765297541, 31.999915280268137), Offset(42.0, 31.999999999999996), ], <Offset>[ Offset(43.99436998801117, 23.85233115929924), Offset(43.935955265272696, 24.180362852333243), Offset(43.76617309606209, 24.778893280638325), Offset(43.45759773349659, 24.887543031835328), Offset(43.476142398493316, 25.33059113299948), Offset(42.61623543783426, 30.292746160199744), Offset(38.56421880483555, 37.258579505338574), Offset(31.270083850246664, 42.30698994401817), Offset(23.782610635873013, 43.696515982893125), Offset(18.012800970955436, 42.76575199097035), Offset(13.977530596101534, 40.95730246967126), Offset(11.240070848553863, 39.00613901208685), Offset(9.393565839291185, 37.2155999148309), Offset(8.148821505536425, 35.693593987164746), Offset(7.310730957903452, 34.462709918587905), Offset(6.750976658788051, 33.51163465311433), Offset(6.385465372525527, 32.8163580835571), Offset(6.159564015210972, 32.3497810673481), Offset(6.038321541199782, 32.08567294309337), Offset(6.00003765337415, 32.00008471955465), Offset(6.0000000000000036, 32.00000000000001), ], <Offset>[ Offset(43.99436998801117, 23.85233115929924), Offset(43.935955265272696, 24.180362852333243), Offset(43.76617309606209, 24.778893280638325), Offset(43.45759773349659, 24.887543031835328), Offset(43.476142398493316, 25.33059113299948), Offset(42.61623543783426, 30.292746160199744), Offset(38.56421880483555, 37.258579505338574), Offset(31.270083850246664, 42.30698994401817), Offset(23.782610635873013, 43.696515982893125), Offset(18.012800970955436, 42.76575199097035), Offset(13.977530596101534, 40.95730246967126), Offset(11.240070848553863, 39.00613901208685), Offset(9.393565839291185, 37.2155999148309), Offset(8.148821505536425, 35.693593987164746), Offset(7.310730957903452, 34.462709918587905), Offset(6.750976658788051, 33.51163465311433), Offset(6.385465372525527, 32.8163580835571), Offset(6.159564015210972, 32.3497810673481), Offset(6.038321541199782, 32.08567294309337), Offset(6.00003765337415, 32.00008471955465), Offset(6.0000000000000036, 32.00000000000001), ], ), _PathCubicTo( <Offset>[ Offset(43.99436998801117, 23.85233115929924), Offset(43.935955265272696, 24.180362852333243), Offset(43.76617309606209, 24.778893280638325), Offset(43.45759773349659, 24.887543031835328), Offset(43.476142398493316, 25.33059113299948), Offset(42.61623543783426, 30.292746160199744), Offset(38.56421880483555, 37.258579505338574), Offset(31.270083850246664, 42.30698994401817), Offset(23.782610635873013, 43.696515982893125), Offset(18.012800970955436, 42.76575199097035), Offset(13.977530596101534, 40.95730246967126), Offset(11.240070848553863, 39.00613901208685), Offset(9.393565839291185, 37.2155999148309), Offset(8.148821505536425, 35.693593987164746), Offset(7.310730957903452, 34.462709918587905), Offset(6.750976658788051, 33.51163465311433), Offset(6.385465372525527, 32.8163580835571), Offset(6.159564015210972, 32.3497810673481), Offset(6.038321541199782, 32.08567294309337), Offset(6.00003765337415, 32.00008471955465), Offset(6.0000000000000036, 32.00000000000001), ], <Offset>[ Offset(23.684125337090187, 6.329045030292864), Offset(24.757855588602716, 6.52232881591406), Offset(27.574407323047023, 7.305175651635392), Offset(34.29718691345236, 10.565460438397327), Offset(42.96465562689078, 18.312204872233718), Offset(45.05615687408604, 26.45166424955556), Offset(42.232333320435735, 35.60390079421558), Offset(35.26685178627038, 42.467757059973906), Offset(27.4197052006056, 45.36131120369138), Offset(21.001315853482343, 45.424469500769995), Offset(16.29765110355406, 44.215682562738714), Offset(12.97234991047133, 42.61158062881598), Offset(10.641290841160107, 41.016018618041265), Offset(9.0114530912401, 39.59946991291384), Offset(7.875830197056132, 38.422591589788325), Offset(7.093422401327867, 37.49694905895691), Offset(6.568745459991835, 36.81215692853645), Offset(6.237631760921833, 36.34901917317271), Offset(6.057380152594408, 36.08562753900215), Offset(6.000056479961543, 36.00008471951035), Offset(6.0000000000000036, 36.00000000000001), ], <Offset>[ Offset(23.684125337090187, 6.329045030292864), Offset(24.757855588602716, 6.52232881591406), Offset(27.574407323047023, 7.305175651635392), Offset(34.29718691345236, 10.565460438397327), Offset(42.96465562689078, 18.312204872233718), Offset(45.05615687408604, 26.45166424955556), Offset(42.232333320435735, 35.60390079421558), Offset(35.26685178627038, 42.467757059973906), Offset(27.4197052006056, 45.36131120369138), Offset(21.001315853482343, 45.424469500769995), Offset(16.29765110355406, 44.215682562738714), Offset(12.97234991047133, 42.61158062881598), Offset(10.641290841160107, 41.016018618041265), Offset(9.0114530912401, 39.59946991291384), Offset(7.875830197056132, 38.422591589788325), Offset(7.093422401327867, 37.49694905895691), Offset(6.568745459991835, 36.81215692853645), Offset(6.237631760921833, 36.34901917317271), Offset(6.057380152594408, 36.08562753900215), Offset(6.000056479961543, 36.00008471951035), Offset(6.0000000000000036, 36.00000000000001), ], ), _PathClose( ), ], ), ], );
flutter/packages/flutter/lib/src/material/animated_icons/data/home_menu.g.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/material/animated_icons/data/home_menu.g.dart', 'repo_id': 'flutter', 'token_count': 49507}
// 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 'material_localizations.dart'; /// Utility functions for working with dates. class DateUtils { // This class is not meant to be instantiated or extended; this constructor // prevents instantiation and extension. DateUtils._(); /// Returns a [DateTime] with the date of the original, but time set to /// midnight. static DateTime dateOnly(DateTime date) { return DateTime(date.year, date.month, date.day); } /// Returns a [DateTimeRange] with the dates of the original, but with times /// set to midnight. /// /// See also: /// * [dateOnly], which does the same thing for a single date. static DateTimeRange datesOnly(DateTimeRange range) { return DateTimeRange(start: dateOnly(range.start), end: dateOnly(range.end)); } /// Returns true if the two [DateTime] objects have the same day, month, and /// year, or are both null. static bool isSameDay(DateTime? dateA, DateTime? dateB) { return dateA?.year == dateB?.year && dateA?.month == dateB?.month && dateA?.day == dateB?.day; } /// Returns true if the two [DateTime] objects have the same month and /// year, or are both null. static bool isSameMonth(DateTime? dateA, DateTime? dateB) { return dateA?.year == dateB?.year && dateA?.month == dateB?.month; } /// Determines the number of months between two [DateTime] objects. /// /// For example: /// /// ```dart /// DateTime date1 = DateTime(2019, 6, 15); /// DateTime date2 = DateTime(2020, 1, 15); /// int delta = DateUtils.monthDelta(date1, date2); /// ``` /// /// The value for `delta` would be `7`. static int monthDelta(DateTime startDate, DateTime endDate) { return (endDate.year - startDate.year) * 12 + endDate.month - startDate.month; } /// Returns a [DateTime] that is [monthDate] with the added number /// of months and the day set to 1 and time set to midnight. /// /// For example: /// /// ```dart /// DateTime date = DateTime(2019, 1, 15); /// DateTime futureDate = DateUtils.addMonthsToMonthDate(date, 3); /// ``` /// /// `date` would be January 15, 2019. /// `futureDate` would be April 1, 2019 since it adds 3 months. static DateTime addMonthsToMonthDate(DateTime monthDate, int monthsToAdd) { return DateTime(monthDate.year, monthDate.month + monthsToAdd); } /// Returns a [DateTime] with the added number of days and time set to /// midnight. static DateTime addDaysToDate(DateTime date, int days) { return DateTime(date.year, date.month, date.day + days); } /// Computes the offset from the first day of the week that the first day of /// the [month] falls on. /// /// For example, September 1, 2017 falls on a Friday, which in the calendar /// localized for United States English appears as: /// /// S M T W T F S /// _ _ _ _ _ 1 2 /// /// The offset for the first day of the months is the number of leading blanks /// in the calendar, i.e. 5. /// /// The same date localized for the Russian calendar has a different offset, /// because the first day of week is Monday rather than Sunday: /// /// M T W T F S S /// _ _ _ _ 1 2 3 /// /// So the offset is 4, rather than 5. /// /// This code consolidates the following: /// /// - [DateTime.weekday] provides a 1-based index into days of week, with 1 /// falling on Monday. /// - [MaterialLocalizations.firstDayOfWeekIndex] provides a 0-based index /// into the [MaterialLocalizations.narrowWeekdays] list. /// - [MaterialLocalizations.narrowWeekdays] list provides localized names of /// days of week, always starting with Sunday and ending with Saturday. static int firstDayOffset(int year, int month, MaterialLocalizations localizations) { // 0-based day of week for the month and year, with 0 representing Monday. final int weekdayFromMonday = DateTime(year, month).weekday - 1; // 0-based start of week depending on the locale, with 0 representing Sunday. int firstDayOfWeekIndex = localizations.firstDayOfWeekIndex; // firstDayOfWeekIndex recomputed to be Monday-based, in order to compare with // weekdayFromMonday. firstDayOfWeekIndex = (firstDayOfWeekIndex - 1) % 7; // Number of days between the first day of week appearing on the calendar, // and the day corresponding to the first of the month. return (weekdayFromMonday - firstDayOfWeekIndex) % 7; } /// Returns the number of days in a month, according to the proleptic /// Gregorian calendar. /// /// This applies the leap year logic introduced by the Gregorian reforms of /// 1582. It will not give valid results for dates prior to that time. static int getDaysInMonth(int year, int month) { if (month == DateTime.february) { final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0); return isLeapYear ? 29 : 28; } const List<int> daysInMonth = <int>[31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return daysInMonth[month - 1]; } } /// Mode of date entry method for the date picker dialog. /// /// In [calendar] mode, a calendar grid is displayed and the user taps the /// day they wish to select. In [input] mode a TextField] is displayed and /// the user types in the date they wish to select. /// /// [calendarOnly] and [inputOnly] are variants of the above that don't /// allow the user to change to the mode. /// /// See also: /// /// * [showDatePicker] and [showDateRangePicker], which use this to control /// the initial entry mode of their dialogs. enum DatePickerEntryMode { /// User picks a date from calendar grid. Can switch to [input] by activating /// a mode button in the dialog. calendar, /// User can input the date by typing it into a text field. /// /// Can switch to [calendar] by activating a mode button in the dialog. input, /// User can only pick a date from calendar grid. /// /// There is no user interface to switch to another mode. calendarOnly, /// User can only input the date by typing it into a text field. /// /// There is no user interface to switch to another mode. inputOnly, } /// Initial display of a calendar date picker. /// /// Either a grid of available years or a monthly calendar. /// /// See also: /// /// * [showDatePicker], which shows a dialog that contains a Material Design /// date picker. /// * [CalendarDatePicker], widget which implements the Material Design date picker. enum DatePickerMode { /// Choosing a month and day. day, /// Choosing a year. year, } /// Signature for predicating dates for enabled date selections. /// /// See [showDatePicker], which has a [SelectableDayPredicate] parameter used /// to specify allowable days in the date picker. typedef SelectableDayPredicate = bool Function(DateTime day); /// Encapsulates a start and end [DateTime] that represent the range of dates. /// /// The range includes the [start] and [end] dates. The [start] and [end] dates /// may be equal to indicate a date range of a single day. The [start] date must /// not be after the [end] date. /// /// See also: /// * [showDateRangePicker], which displays a dialog that allows the user to /// select a date range. @immutable class DateTimeRange { /// Creates a date range for the given start and end [DateTime]. DateTimeRange({ required this.start, required this.end, }) : assert(!start.isAfter(end)); /// The start of the range of dates. final DateTime start; /// The end of the range of dates. final DateTime end; /// Returns a [Duration] of the time between [start] and [end]. /// /// See [DateTime.difference] for more details. Duration get duration => end.difference(start); @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is DateTimeRange && other.start == start && other.end == end; } @override int get hashCode => Object.hash(start, end); @override String toString() => '$start - $end'; }
flutter/packages/flutter/lib/src/material/date.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/material/date.dart', 'repo_id': 'flutter', 'token_count': 2545}
// 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'; /// The Flutter logo, in widget form. This widget respects the [IconTheme]. /// For guidelines on using the Flutter logo, visit https://flutter.dev/brand. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=aAmP-WcI6dg} /// /// See also: /// /// * [IconTheme], which provides ambient configuration for icons. /// * [Icon], for showing icons the Material design icon library. /// * [ImageIcon], for showing icons from [AssetImage]s or other [ImageProvider]s. class FlutterLogo extends StatelessWidget { /// Creates a widget that paints the Flutter logo. /// /// The [size] defaults to the value given by the current [IconTheme]. /// /// The [textColor], [style], [duration], and [curve] arguments must not be /// null. const FlutterLogo({ super.key, this.size, this.textColor = const Color(0xFF757575), this.style = FlutterLogoStyle.markOnly, this.duration = const Duration(milliseconds: 750), this.curve = Curves.fastOutSlowIn, }); /// The size of the logo in logical pixels. /// /// The logo will be fit into a square this size. /// /// Defaults to the current [IconTheme] size, if any. If there is no /// [IconTheme], or it does not specify an explicit size, then it defaults to /// 24.0. final double? size; /// The color used to paint the "Flutter" text on the logo, if [style] is /// [FlutterLogoStyle.horizontal] or [FlutterLogoStyle.stacked]. /// /// If possible, the default (a medium grey) should be used against a white /// background. final Color textColor; /// Whether and where to draw the "Flutter" text. By default, only the logo /// itself is drawn. final FlutterLogoStyle style; /// The length of time for the animation if the [style] or [textColor] /// properties are changed. final Duration duration; /// The curve for the logo animation if the [style] or [textColor] change. final Curve curve; @override Widget build(BuildContext context) { final IconThemeData iconTheme = IconTheme.of(context); final double? iconSize = size ?? iconTheme.size; return AnimatedContainer( width: iconSize, height: iconSize, duration: duration, curve: curve, decoration: FlutterLogoDecoration( style: style, textColor: textColor, ), ); } }
flutter/packages/flutter/lib/src/material/flutter_logo.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/material/flutter_logo.dart', 'repo_id': 'flutter', 'token_count': 794}
// 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/animation.dart'; import 'package:flutter/foundation.dart'; /// The direction of a scroll, relative to the positive scroll offset axis given /// by an [AxisDirection] and a [GrowthDirection]. /// /// This contrasts to [GrowthDirection] in that it has a third value, [idle], /// for the case where no scroll is occurring. /// /// This is used by [RenderSliverFloatingPersistentHeader] to only expand when /// the user is scrolling in the same direction as the detected scroll offset /// change. enum ScrollDirection { /// No scrolling is underway. idle, /// Scrolling is happening in the positive scroll offset direction. /// /// For example, for the [GrowthDirection.forward] part of a vertical /// [AxisDirection.down] list, this means the content is moving up, exposing /// lower content. forward, /// Scrolling is happening in the negative scroll offset direction. /// /// For example, for the [GrowthDirection.forward] part of a vertical /// [AxisDirection.down] list, this means the content is moving down, exposing /// earlier content. reverse, } /// Returns the opposite of the given [ScrollDirection]. /// /// Specifically, returns [ScrollDirection.reverse] for [ScrollDirection.forward] /// (and vice versa) and returns [ScrollDirection.idle] for /// [ScrollDirection.idle]. ScrollDirection flipScrollDirection(ScrollDirection direction) { switch (direction) { case ScrollDirection.idle: return ScrollDirection.idle; case ScrollDirection.forward: return ScrollDirection.reverse; case ScrollDirection.reverse: return ScrollDirection.forward; } } /// Which part of the content inside the viewport should be visible. /// /// The [pixels] value determines the scroll offset that the viewport uses to /// select which part of its content to display. As the user scrolls the /// viewport, this value changes, which changes the content that is displayed. /// /// This object is a [Listenable] that notifies its listeners when [pixels] /// changes. /// /// See also: /// /// * [ScrollPosition], which is a commonly used concrete subclass. /// * [RenderViewportBase], which is a render object that uses viewport /// offsets. abstract class ViewportOffset extends ChangeNotifier { /// Default constructor. /// /// Allows subclasses to construct this object directly. ViewportOffset(); /// Creates a viewport offset with the given [pixels] value. /// /// The [pixels] value does not change unless the viewport issues a /// correction. factory ViewportOffset.fixed(double value) = _FixedViewportOffset; /// Creates a viewport offset with a [pixels] value of 0.0. /// /// The [pixels] value does not change unless the viewport issues a /// correction. factory ViewportOffset.zero() = _FixedViewportOffset.zero; /// The number of pixels to offset the children in the opposite of the axis direction. /// /// For example, if the axis direction is down, then the pixel value /// represents the number of logical pixels to move the children _up_ the /// screen. Similarly, if the axis direction is left, then the pixels value /// represents the number of logical pixels to move the children to _right_. /// /// This object notifies its listeners when this value changes (except when /// the value changes due to [correctBy]). double get pixels; /// Whether the [pixels] property is available. bool get hasPixels; /// Called when the viewport's extents are established. /// /// The argument is the dimension of the [RenderViewport] in the main axis /// (e.g. the height, for a vertical viewport). /// /// This may be called redundantly, with the same value, each frame. This is /// called during layout for the [RenderViewport]. If the viewport is /// configured to shrink-wrap its contents, it may be called several times, /// since the layout is repeated each time the scroll offset is corrected. /// /// If this is called, it is called before [applyContentDimensions]. If this /// is called, [applyContentDimensions] will be called soon afterwards in the /// same layout phase. If the viewport is not configured to shrink-wrap its /// contents, then this will only be called when the viewport recomputes its /// size (i.e. when its parent lays out), and not during normal scrolling. /// /// If applying the viewport dimensions changes the scroll offset, return /// false. Otherwise, return true. If you return false, the [RenderViewport] /// will be laid out again with the new scroll offset. This is expensive. (The /// return value is answering the question "did you accept these viewport /// dimensions unconditionally?"; if the new dimensions change the /// [ViewportOffset]'s actual [pixels] value, then the viewport will need to /// be laid out again.) bool applyViewportDimension(double viewportDimension); /// Called when the viewport's content extents are established. /// /// The arguments are the minimum and maximum scroll extents respectively. The /// minimum will be equal to or less than the maximum. In the case of slivers, /// the minimum will be equal to or less than zero, the maximum will be equal /// to or greater than zero. /// /// The maximum scroll extent has the viewport dimension subtracted from it. /// For instance, if there is 100.0 pixels of scrollable content, and the /// viewport is 80.0 pixels high, then the minimum scroll extent will /// typically be 0.0 and the maximum scroll extent will typically be 20.0, /// because there's only 20.0 pixels of actual scroll slack. /// /// If applying the content dimensions changes the scroll offset, return /// false. Otherwise, return true. If you return false, the [RenderViewport] /// will be laid out again with the new scroll offset. This is expensive. (The /// return value is answering the question "did you accept these content /// dimensions unconditionally?"; if the new dimensions change the /// [ViewportOffset]'s actual [pixels] value, then the viewport will need to /// be laid out again.) /// /// This is called at least once each time the [RenderViewport] is laid out, /// even if the values have not changed. It may be called many times if the /// scroll offset is corrected (if this returns false). This is always called /// after [applyViewportDimension], if that method is called. bool applyContentDimensions(double minScrollExtent, double maxScrollExtent); /// Apply a layout-time correction to the scroll offset. /// /// This method should change the [pixels] value by `correction`, but without /// calling [notifyListeners]. It is called during layout by the /// [RenderViewport], before [applyContentDimensions]. After this method is /// called, the layout will be recomputed and that may result in this method /// being called again, though this should be very rare. /// /// See also: /// /// * [jumpTo], for also changing the scroll position when not in layout. /// [jumpTo] applies the change immediately and notifies its listeners. void correctBy(double correction); /// Jumps [pixels] from its current value to the given value, /// without animation, and without checking if the new value is in range. /// /// See also: /// /// * [correctBy], for changing the current offset in the middle of layout /// and that defers the notification of its listeners until after layout. void jumpTo(double pixels); /// Animates [pixels] from its current value to the given value. /// /// The returned [Future] will complete when the animation ends, whether it /// completed successfully or whether it was interrupted prematurely. /// /// The duration must not be zero. To jump to a particular value without an /// animation, use [jumpTo]. Future<void> animateTo( double to, { required Duration duration, required Curve curve, }); /// Calls [jumpTo] if duration is null or [Duration.zero], otherwise /// [animateTo] is called. /// /// If [animateTo] is called then [curve] defaults to [Curves.ease]. The /// [clamp] parameter is ignored by this stub implementation but subclasses /// like [ScrollPosition] handle it by adjusting [to] to prevent over or /// underscroll. Future<void> moveTo( double to, { Duration? duration, Curve? curve, bool? clamp, }) { if (duration == null || duration == Duration.zero) { jumpTo(to); return Future<void>.value(); } else { return animateTo(to, duration: duration, curve: curve ?? Curves.ease); } } /// The direction in which the user is trying to change [pixels], relative to /// the viewport's [RenderViewportBase.axisDirection]. /// /// If the _user_ is not scrolling, this will return [ScrollDirection.idle] /// even if there is (for example) a [ScrollActivity] currently animating the /// position. /// /// This is exposed in [SliverConstraints.userScrollDirection], which is used /// by some slivers to determine how to react to a change in scroll offset. /// For example, [RenderSliverFloatingPersistentHeader] will only expand a /// floating app bar when the [userScrollDirection] is in the positive scroll /// offset direction. ScrollDirection get userScrollDirection; /// Whether a viewport is allowed to change [pixels] implicitly to respond to /// a call to [RenderObject.showOnScreen]. /// /// [RenderObject.showOnScreen] is for example used to bring a text field /// fully on screen after it has received focus. This property controls /// whether the viewport associated with this offset is allowed to change the /// offset's [pixels] value to fulfill such a request. bool get allowImplicitScrolling; @override String toString() { final List<String> description = <String>[]; debugFillDescription(description); return '${describeIdentity(this)}(${description.join(", ")})'; } /// Add additional information to the given description for use by [toString]. /// /// This method makes it easier for subclasses to coordinate to provide a /// high-quality [toString] implementation. The [toString] implementation on /// the [State] base class calls [debugFillDescription] to collect useful /// information from subclasses to incorporate into its return value. /// /// Implementations of this method should start with a call to the inherited /// method, as in `super.debugFillDescription(description)`. @mustCallSuper void debugFillDescription(List<String> description) { if (hasPixels) { description.add('offset: ${pixels.toStringAsFixed(1)}'); } } } class _FixedViewportOffset extends ViewportOffset { _FixedViewportOffset(this._pixels); _FixedViewportOffset.zero() : _pixels = 0.0; double _pixels; @override double get pixels => _pixels; @override bool get hasPixels => true; @override bool applyViewportDimension(double viewportDimension) => true; @override bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) => true; @override void correctBy(double correction) { _pixels += correction; } @override void jumpTo(double pixels) { // Do nothing, viewport is fixed. } @override Future<void> animateTo( double to, { required Duration duration, required Curve curve, }) async { } @override ScrollDirection get userScrollDirection => ScrollDirection.idle; @override bool get allowImplicitScrolling => false; }
flutter/packages/flutter/lib/src/rendering/viewport_offset.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/rendering/viewport_offset.dart', 'repo_id': 'flutter', 'token_count': 3156}
// 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/rendering.dart'; import 'framework.dart'; /// Annotates a region of the layer tree with a value. /// /// See also: /// /// * [Layer.find], for an example of how this value is retrieved. /// * [AnnotatedRegionLayer], the layer pushed into the layer tree. class AnnotatedRegion<T extends Object> extends SingleChildRenderObjectWidget { /// Creates a new annotated region to insert [value] into the layer tree. /// /// Neither [child] nor [value] may be null. /// /// [sized] defaults to true and controls whether the annotated region will /// clip its child. const AnnotatedRegion({ super.key, required Widget super.child, required this.value, this.sized = true, }); /// A value which can be retrieved using [Layer.find]. final T value; /// If false, the layer pushed into the tree will not be provided with a size. /// /// An [AnnotatedRegionLayer] with a size checks that the offset provided in /// [Layer.find] is within the bounds, returning null otherwise. /// /// See also: /// /// * [AnnotatedRegionLayer], for a description of this behavior. final bool sized; @override RenderObject createRenderObject(BuildContext context) { return RenderAnnotatedRegion<T>(value: value, sized: sized); } @override void updateRenderObject(BuildContext context, RenderAnnotatedRegion<T> renderObject) { renderObject ..value = value ..sized = sized; } }
flutter/packages/flutter/lib/src/widgets/annotated_region.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/widgets/annotated_region.dart', 'repo_id': 'flutter', 'token_count': 480}
// 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 'basic.dart'; import 'framework.dart'; /// A widget that rebuilds when the given animation changes status. abstract class StatusTransitionWidget extends StatefulWidget { /// Initializes fields for subclasses. /// /// The [animation] argument must not be null. const StatusTransitionWidget({ super.key, required this.animation, }); /// The animation to which this widget is listening. final Animation<double> animation; /// Override this method to build widgets that depend on the current status /// of the animation. Widget build(BuildContext context); @override State<StatusTransitionWidget> createState() => _StatusTransitionState(); } class _StatusTransitionState extends State<StatusTransitionWidget> { @override void initState() { super.initState(); widget.animation.addStatusListener(_animationStatusChanged); } @override void didUpdateWidget(StatusTransitionWidget oldWidget) { super.didUpdateWidget(oldWidget); if (widget.animation != oldWidget.animation) { oldWidget.animation.removeStatusListener(_animationStatusChanged); widget.animation.addStatusListener(_animationStatusChanged); } } @override void dispose() { widget.animation.removeStatusListener(_animationStatusChanged); super.dispose(); } void _animationStatusChanged(AnimationStatus status) { setState(() { // The animation's state is our build state, and it changed already. }); } @override Widget build(BuildContext context) { return widget.build(context); } }
flutter/packages/flutter/lib/src/widgets/status_transitions.dart/0
{'file_path': 'flutter/packages/flutter/lib/src/widgets/status_transitions.dart', 'repo_id': 'flutter', 'token_count': 506}
// 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_test/flutter_test.dart'; // based on the sample code in foundation/binding.dart mixin FooBinding on BindingBase { @override void initInstances() { super.initInstances(); _instance = this; } static FooBinding get instance => BindingBase.checkInstance(_instance); static FooBinding? _instance; } class FooLibraryBinding extends BindingBase with FooBinding { static FooBinding ensureInitialized() { if (FooBinding._instance == null) { FooLibraryBinding(); } return FooBinding.instance; } } void main() { test('BindingBase.debugBindingType', () async { expect(BindingBase.debugBindingType(), isNull); FooLibraryBinding.ensureInitialized(); expect(BindingBase.debugBindingType(), FooLibraryBinding); }); }
flutter/packages/flutter/test/foundation/binding_test.dart/0
{'file_path': 'flutter/packages/flutter/test/foundation/binding_test.dart', 'repo_id': 'flutter', 'token_count': 314}
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('DividerThemeData copyWith, ==, hashCode basics', () { expect(const DividerThemeData(), const DividerThemeData().copyWith()); expect(const DividerThemeData().hashCode, const DividerThemeData().copyWith().hashCode); }); test('DividerThemeData null fields by default', () { const DividerThemeData dividerTheme = DividerThemeData(); expect(dividerTheme.color, null); expect(dividerTheme.space, null); expect(dividerTheme.thickness, null); expect(dividerTheme.indent, null); expect(dividerTheme.endIndent, null); }); testWidgets('Default DividerThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const DividerThemeData().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[]); }); testWidgets('DividerThemeData implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const DividerThemeData( color: Color(0xFFFFFFFF), space: 5.0, thickness: 4.0, indent: 3.0, endIndent: 2.0, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[ 'color: Color(0xffffffff)', 'space: 5.0', 'thickness: 4.0', 'indent: 3.0', 'endIndent: 2.0', ]); }); group('Horizontal Divider', () { testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget(MaterialApp( theme: theme, home: const Scaffold( body: Divider(), ), )); final RenderBox box = tester.firstRenderObject(find.byType(Divider)); expect(box.size.height, 16.0); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; expect(decoration.border!.bottom.width, 1.0); expect(decoration.border!.bottom.color, theme.colorScheme.outlineVariant); final Rect dividerRect = tester.getRect(find.byType(Divider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.left, dividerRect.left); expect(lineRect.right, dividerRect.right); }); testWidgets('Uses values from DividerThemeData', (WidgetTester tester) async { final DividerThemeData dividerTheme = _dividerTheme(); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: true, dividerTheme: dividerTheme), home: const Scaffold( body: Divider(), ), )); final RenderBox box = tester.firstRenderObject(find.byType(Divider)); expect(box.size.height, dividerTheme.space); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; expect(decoration.border!.bottom.width, dividerTheme.thickness); expect(decoration.border!.bottom.color, dividerTheme.color); final Rect dividerRect = tester.getRect(find.byType(Divider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.left, dividerRect.left + dividerTheme.indent!); expect(lineRect.right, dividerRect.right - dividerTheme.endIndent!); }); testWidgets('DividerTheme overrides defaults', (WidgetTester tester) async { final DividerThemeData dividerTheme = _dividerTheme(); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( body: DividerTheme( data: dividerTheme, child: const Divider(), ), ), )); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; expect(decoration.border!.bottom.width, dividerTheme.thickness); expect(decoration.border!.bottom.color, dividerTheme.color); }); testWidgets('Widget properties take priority over theme', (WidgetTester tester) async { const Color color = Colors.purple; const double height = 10.0; const double thickness = 5.0; const double indent = 8.0; const double endIndent = 9.0; final DividerThemeData dividerTheme = _dividerTheme(); await tester.pumpWidget(MaterialApp( theme: ThemeData(dividerTheme: dividerTheme), home: const Scaffold( body: Divider( color: color, height: height, thickness: thickness, indent: indent, endIndent: endIndent, ), ), )); final RenderBox box = tester.firstRenderObject(find.byType(Divider)); expect(box.size.height, height); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; expect(decoration.border!.bottom.width, thickness); expect(decoration.border!.bottom.color, color); final Rect dividerRect = tester.getRect(find.byType(Divider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.left, dividerRect.left + indent); expect(lineRect.right, dividerRect.right - endIndent); }); }); group('Vertical Divider', () { testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget(MaterialApp( theme: theme, home: const Scaffold( body: VerticalDivider(), ), )); final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider)); expect(box.size.width, 16.0); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; final Border border = decoration.border! as Border; expect(border.left.width, 1.0); expect(border.left.color, theme.colorScheme.outlineVariant); final Rect dividerRect = tester.getRect(find.byType(VerticalDivider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.top, dividerRect.top); expect(lineRect.bottom, dividerRect.bottom); }); testWidgets('Uses values from DividerThemeData', (WidgetTester tester) async { final DividerThemeData dividerTheme = _dividerTheme(); await tester.pumpWidget(MaterialApp( theme: ThemeData(dividerTheme: dividerTheme), home: const Scaffold( body: VerticalDivider(), ), )); final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider)); expect(box.size.width, dividerTheme.space); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; final Border border = decoration.border! as Border; expect(border.left.width, dividerTheme.thickness); expect(border.left.color, dividerTheme.color); final Rect dividerRect = tester.getRect(find.byType(VerticalDivider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.top, dividerRect.top + dividerTheme.indent!); expect(lineRect.bottom, dividerRect.bottom - dividerTheme.endIndent!); }); testWidgets('DividerTheme overrides defaults', (WidgetTester tester) async { final DividerThemeData dividerTheme = _dividerTheme(); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( body: DividerTheme( data: dividerTheme, child: const VerticalDivider(), ), ), )); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; final Border border = decoration.border! as Border; expect(border.left.width, dividerTheme.thickness); expect(border.left.color, dividerTheme.color); }); testWidgets('Widget properties take priority over theme', (WidgetTester tester) async { const Color color = Colors.purple; const double width = 10.0; const double thickness = 5.0; const double indent = 8.0; const double endIndent = 9.0; final DividerThemeData dividerTheme = _dividerTheme(); await tester.pumpWidget(MaterialApp( theme: ThemeData(dividerTheme: dividerTheme), home: const Scaffold( body: VerticalDivider( color: color, width: width, thickness: thickness, indent: indent, endIndent: endIndent, ), ), )); final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider)); expect(box.size.width, width); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; final Border border = decoration.border! as Border; expect(border.left.width, thickness); expect(border.left.color, color); final Rect dividerRect = tester.getRect(find.byType(VerticalDivider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.top, dividerRect.top + indent); expect(lineRect.bottom, dividerRect.bottom - endIndent); }); }); group('Material 2', () { // Tests that are only relevant for Material 2. Once ThemeData.useMaterial3 // is turned on by default, these tests can be removed. group('Horizontal Divider', () { testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Scaffold( body: Divider(), ), )); final RenderBox box = tester.firstRenderObject(find.byType(Divider)); expect(box.size.height, 16.0); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; expect(decoration.border!.bottom.width, 0.0); final ThemeData theme = ThemeData(); expect(decoration.border!.bottom.color, theme.dividerColor); final Rect dividerRect = tester.getRect(find.byType(Divider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.left, dividerRect.left); expect(lineRect.right, dividerRect.right); }); testWidgets('DividerTheme overrides defaults', (WidgetTester tester) async { final DividerThemeData theme = _dividerTheme(); await tester.pumpWidget(MaterialApp( home: Scaffold( body: DividerTheme( data: theme, child: const Divider(), ), ), )); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; expect(decoration.border!.bottom.width, theme.thickness); expect(decoration.border!.bottom.color, theme.color); }); }); group('Vertical Divider', () { testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Scaffold( body: VerticalDivider(), ), )); final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider)); expect(box.size.width, 16.0); final Container container = tester.widget(find.byType(Container)); final BoxDecoration decoration = container.decoration! as BoxDecoration; final Border border = decoration.border! as Border; expect(border.left.width, 0.0); final ThemeData theme = ThemeData(); expect(border.left.color, theme.dividerColor); final Rect dividerRect = tester.getRect(find.byType(VerticalDivider)); final Rect lineRect = tester.getRect(find.byType(DecoratedBox)); expect(lineRect.top, dividerRect.top); expect(lineRect.bottom, dividerRect.bottom); }); }); }); } DividerThemeData _dividerTheme() { return const DividerThemeData( color: Colors.orange, space: 12.0, thickness: 2.0, indent: 7.0, endIndent: 5.0, ); }
flutter/packages/flutter/test/material/divider_theme_test.dart/0
{'file_path': 'flutter/packages/flutter/test/material/divider_theme_test.dart', 'repo_id': 'flutter', 'token_count': 5092}
// 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' as ui show Codec; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; /// An image provider implementation for testing that is using a [ui.Codec] /// that it was given at construction time (typically the job of real image /// providers is to resolve some data and instantiate a [ui.Codec] from it). class FakeImageProvider extends ImageProvider<FakeImageProvider> { const FakeImageProvider(this._codec, { this.scale = 1.0 }); final ui.Codec _codec; /// The scale to place in the [ImageInfo] object of the image. final double scale; @override Future<FakeImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<FakeImageProvider>(this); } @override ImageStreamCompleter load(FakeImageProvider key, DecoderCallback decode) { assert(key == this); return MultiFrameImageStreamCompleter( codec: SynchronousFuture<ui.Codec>(_codec), scale: scale, ); } }
flutter/packages/flutter/test/painting/fake_image_provider.dart/0
{'file_path': 'flutter/packages/flutter/test/painting/fake_image_provider.dart', 'repo_id': 'flutter', 'token_count': 340}
// 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 'package:flutter_test/flutter_test.dart'; void main() { test('StrutStyle diagnostics test', () { const StrutStyle s0 = StrutStyle( fontFamily: 'Serif', fontSize: 14, ); expect( s0.toString(), equals('StrutStyle(family: Serif, size: 14.0)'), ); const StrutStyle s1 = StrutStyle( fontFamily: 'Serif', fontSize: 14, forceStrutHeight: true, ); expect(s1.fontFamily, 'Serif'); expect(s1.fontSize, 14.0); expect(s1, equals(s1)); expect( s1.toString(), equals('StrutStyle(family: Serif, size: 14.0, <strut height forced>)'), ); const StrutStyle s2 = StrutStyle( fontFamily: 'Serif', fontSize: 14, forceStrutHeight: false, ); expect( s2.toString(), equals('StrutStyle(family: Serif, size: 14.0, <strut height normal>)'), ); const StrutStyle s3 = StrutStyle(); expect( s3.toString(), equals('StrutStyle'), ); const StrutStyle s4 = StrutStyle( forceStrutHeight: false, ); expect( s4.toString(), equals('StrutStyle(<strut height normal>)'), ); const StrutStyle s5 = StrutStyle( forceStrutHeight: true, ); expect( s5.toString(), equals('StrutStyle(<strut height forced>)'), ); }); }
flutter/packages/flutter/test/painting/strut_style_test.dart/0
{'file_path': 'flutter/packages/flutter/test/painting/strut_style_test.dart', 'repo_id': 'flutter', 'token_count': 659}
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('RenderBaseline', () { RenderBaseline parent; RenderSizedBox child; final RenderBox root = RenderPositionedBox( alignment: Alignment.topLeft, child: parent = RenderBaseline( baseline: 0.0, baselineType: TextBaseline.alphabetic, child: child = RenderSizedBox(const Size(100.0, 100.0)), ), ); final BoxParentData childParentData = child.parentData! as BoxParentData; layout(root); expect(childParentData.offset.dx, equals(0.0)); expect(childParentData.offset.dy, equals(-100.0)); expect(parent.size, equals(const Size(100.0, 0.0))); parent.baseline = 25.0; pumpFrame(); expect(childParentData.offset.dx, equals(0.0)); expect(childParentData.offset.dy, equals(-75.0)); expect(parent.size, equals(const Size(100.0, 25.0))); parent.baseline = 90.0; pumpFrame(); expect(childParentData.offset.dx, equals(0.0)); expect(childParentData.offset.dy, equals(-10.0)); expect(parent.size, equals(const Size(100.0, 90.0))); parent.baseline = 100.0; pumpFrame(); expect(childParentData.offset.dx, equals(0.0)); expect(childParentData.offset.dy, equals(0.0)); expect(parent.size, equals(const Size(100.0, 100.0))); parent.baseline = 110.0; pumpFrame(); expect(childParentData.offset.dx, equals(0.0)); expect(childParentData.offset.dy, equals(10.0)); expect(parent.size, equals(const Size(100.0, 110.0))); }); }
flutter/packages/flutter/test/rendering/baseline_test.dart/0
{'file_path': 'flutter/packages/flutter/test/rendering/baseline_test.dart', 'repo_id': 'flutter', 'token_count': 686}
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('offstage', () { RenderBox child; bool painted = false; // incoming constraints are tight 800x600 final RenderBox root = RenderPositionedBox( child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(width: 800.0), child: RenderOffstage( child: RenderCustomPaint( painter: TestCallbackPainter( onPaint: () { painted = true; }, ), child: child = RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(height: 10.0, width: 10.0), ), ), ), ), ); expect(child.hasSize, isFalse); expect(painted, isFalse); layout(root, phase: EnginePhase.paint); expect(child.hasSize, isTrue); expect(painted, isFalse); expect(child.size, equals(const Size(800.0, 10.0))); }); }
flutter/packages/flutter/test/rendering/offstage_test.dart/0
{'file_path': 'flutter/packages/flutter/test/rendering/offstage_test.dart', 'repo_id': 'flutter', 'token_count': 492}
// 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_test/flutter_test.dart'; void main() { // We need a separate test file for this test case (instead of including it // in platform_channel_test.dart) since we rely on the WidgetsFlutterBinding // not being initialized and we call ensureInitialized() in the other test // file. test('throws assertion error iff WidgetsFlutterBinding is not yet initialized', () { const MethodChannel methodChannel = MethodChannel('mock'); // Verify an assertion error is thrown before the binary messenger is // accessed (which would result in a _CastError due to the non-null // assertion). This way we can hint the caller towards how to fix the error. expect(() => methodChannel.setMethodCallHandler(null), throwsAssertionError); // Verify the assertion is not thrown once the binding has been initialized. // This cannot be a separate test case since the execution order is random. TestWidgetsFlutterBinding.ensureInitialized(); expect(() => methodChannel.setMethodCallHandler(null), returnsNormally); }); }
flutter/packages/flutter/test/services/set_method_call_handler_test.dart/0
{'file_path': 'flutter/packages/flutter/test/services/set_method_call_handler_test.dart', 'repo_id': 'flutter', 'token_count': 343}
// 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'; void main() { testWidgets('StatefulWidget BuildContext.mounted', (WidgetTester tester) async { late BuildContext capturedContext; await tester.pumpWidget(TestStatefulWidget( onBuild: (BuildContext context) { capturedContext = context; } )); expect(capturedContext.mounted, isTrue); await tester.pumpWidget(Container()); expect(capturedContext.mounted, isFalse); }); testWidgets('StatelessWidget BuildContext.mounted', (WidgetTester tester) async { late BuildContext capturedContext; await tester.pumpWidget(TestStatelessWidget( onBuild: (BuildContext context) { capturedContext = context; } )); expect(capturedContext.mounted, isTrue); await tester.pumpWidget(Container()); expect(capturedContext.mounted, isFalse); }); } typedef BuildCallback = void Function(BuildContext); class TestStatelessWidget extends StatelessWidget { const TestStatelessWidget({super.key, required this.onBuild}); final BuildCallback onBuild; @override Widget build(BuildContext context) { onBuild(context); return Container(); } } class TestStatefulWidget extends StatefulWidget { const TestStatefulWidget({super.key, required this.onBuild}); final BuildCallback onBuild; @override State<TestStatefulWidget> createState() => _TestStatefulWidgetState(); } class _TestStatefulWidgetState extends State<TestStatefulWidget> { @override Widget build(BuildContext context) { widget.onBuild(context); return Container(); } }
flutter/packages/flutter/test/widgets/build_context_test.dart/0
{'file_path': 'flutter/packages/flutter/test/widgets/build_context_test.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. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; Size pageSize = const Size(600.0, 300.0); const List<int> defaultPages = <int>[0, 1, 2, 3, 4, 5]; final List<GlobalKey> globalKeys = defaultPages.map<GlobalKey>((_) => GlobalKey()).toList(); int? currentPage; Widget buildPage(int page) { return SizedBox( key: globalKeys[page], width: pageSize.width, height: pageSize.height, child: Text(page.toString()), ); } Widget buildFrame({ bool reverse = false, List<int> pages = defaultPages, required TextDirection textDirection, }) { final PageView child = PageView( reverse: reverse, onPageChanged: (int page) { currentPage = page; }, children: pages.map<Widget>(buildPage).toList(), ); // The test framework forces the frame to be 800x600, so we need to create // an outer container where we can change the size. return Directionality( textDirection: textDirection, child: Center( child: SizedBox( width: pageSize.width, height: pageSize.height, child: child, ), ), ); } Future<void> page(WidgetTester tester, Offset offset) { return TestAsyncUtils.guard(() async { final String itemText = currentPage != null ? currentPage.toString() : '0'; await tester.drag(find.text(itemText), offset); await tester.pumpAndSettle(); }); } Future<void> pageLeft(WidgetTester tester) { return page(tester, Offset(-pageSize.width, 0.0)); } Future<void> pageRight(WidgetTester tester) { return page(tester, Offset(pageSize.width, 0.0)); } void main() { testWidgets('PageView default control', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: PageView(), ), ), ); }); testWidgets('PageView control test (LTR)', (WidgetTester tester) async { currentPage = null; await tester.pumpWidget(buildFrame(textDirection: TextDirection.ltr)); expect(currentPage, isNull); await pageLeft(tester); expect(currentPage, equals(1)); expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageRight(tester); expect(currentPage, equals(0)); expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageRight(tester); expect(currentPage, equals(0)); }); testWidgets('PageView with reverse (LTR)', (WidgetTester tester) async { currentPage = null; await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.ltr)); await pageRight(tester); expect(currentPage, equals(1)); expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageLeft(tester); expect(currentPage, equals(0)); expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageLeft(tester); expect(currentPage, equals(0)); expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); }); testWidgets('PageView control test (RTL)', (WidgetTester tester) async { currentPage = null; await tester.pumpWidget(buildFrame(textDirection: TextDirection.rtl)); await pageRight(tester); expect(currentPage, equals(1)); expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageLeft(tester); expect(currentPage, equals(0)); expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageLeft(tester); expect(currentPage, equals(0)); expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); }); testWidgets('PageView with reverse (RTL)', (WidgetTester tester) async { currentPage = null; await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.rtl)); expect(currentPage, isNull); await pageLeft(tester); expect(currentPage, equals(1)); expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageRight(tester); expect(currentPage, equals(0)); expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); await pageRight(tester); expect(currentPage, equals(0)); }); }
flutter/packages/flutter/test/widgets/pageable_list_test.dart/0
{'file_path': 'flutter/packages/flutter/test/widgets/pageable_list_test.dart', 'repo_id': 'flutter', 'token_count': 2201}
// 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'; // This is a regression test for https://github.com/flutter/flutter/issues/5840. class Bar extends StatefulWidget { const Bar({ super.key }); @override BarState createState() => BarState(); } class BarState extends State<Bar> { final GlobalKey _fooKey = GlobalKey(); bool _mode = false; void trigger() { setState(() { _mode = !_mode; }); } @override Widget build(BuildContext context) { if (_mode) { return SizedBox( child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return StatefulCreationCounter(key: _fooKey); }, ), ); } else { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return StatefulCreationCounter(key: _fooKey); }, ); } } } class StatefulCreationCounter extends StatefulWidget { const StatefulCreationCounter({ super.key }); @override StatefulCreationCounterState createState() => StatefulCreationCounterState(); } class StatefulCreationCounterState extends State<StatefulCreationCounter> { static int creationCount = 0; @override void initState() { super.initState(); creationCount += 1; } @override Widget build(BuildContext context) => Container(); } void main() { testWidgets('reparent state with layout builder', (WidgetTester tester) async { expect(StatefulCreationCounterState.creationCount, 0); await tester.pumpWidget(const Bar()); expect(StatefulCreationCounterState.creationCount, 1); final BarState s = tester.state<BarState>(find.byType(Bar)); s.trigger(); await tester.pump(); expect(StatefulCreationCounterState.creationCount, 1); }); testWidgets('Clean then reparent with dependencies', (WidgetTester tester) async { int layoutBuilderBuildCount = 0; late StateSetter keyedSetState; late StateSetter layoutBuilderSetState; late StateSetter childSetState; final GlobalKey key = GlobalKey(); final Widget keyedWidget = StatefulBuilder( key: key, builder: (BuildContext context, StateSetter setState) { keyedSetState = setState; MediaQuery.of(context); return Container(); }, ); Widget layoutBuilderChild = keyedWidget; Widget deepChild = Container(); await tester.pumpWidget(MediaQuery( data: MediaQueryData.fromView(tester.binding.window), child: Column( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { layoutBuilderSetState = setState; return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { layoutBuilderBuildCount += 1; return layoutBuilderChild; // initially keyedWidget above, but then a new Container }, ); }), ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { childSetState = setState; return deepChild; // initially a Container, but then the keyedWidget above }, ), ), ), ), ), ), ), ], ), )); expect(layoutBuilderBuildCount, 1); keyedSetState(() { /* Change nothing but add the element to the dirty list. */ }); childSetState(() { // The deep child builds in the initial build phase. It takes the child // from the LayoutBuilder before the LayoutBuilder has a chance to build. deepChild = keyedWidget; }); layoutBuilderSetState(() { // The layout builder will build in a separate build scope. This delays // the removal of the keyed child until this build scope. layoutBuilderChild = Container(); }); // The essential part of this test is that this call to pump doesn't throw. await tester.pump(); expect(layoutBuilderBuildCount, 2); }); }
flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart/0
{'file_path': 'flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart', 'repo_id': 'flutter', 'token_count': 1942}
// 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('runApp inside onPressed does not throw', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Material( child: ElevatedButton( onPressed: () { runApp(const Center(child: Text('Done', textDirection: TextDirection.ltr))); }, child: const Text('GO'), ), ), ), ); await tester.tap(find.text('GO')); expect(find.text('Done'), findsOneWidget); }); }
flutter/packages/flutter/test/widgets/run_app_test.dart/0
{'file_path': 'flutter/packages/flutter/test/widgets/run_app_test.dart', 'repo_id': 'flutter', 'token_count': 331}
// 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('Semantics 1', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); // smoketest await tester.pumpWidget( Semantics( container: true, child: Semantics( label: 'test1', textDirection: TextDirection.ltr, selected: true, child: Container(), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'test1', rect: TestSemantics.fullScreen, flags: SemanticsFlag.isSelected.index, ), ], ))); // control for forking await tester.pumpWidget( Semantics( container: true, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SizedBox( height: 10.0, child: Semantics( label: 'child1', textDirection: TextDirection.ltr, selected: true, ), ), SizedBox( height: 10.0, child: IgnorePointer( child: Semantics( label: 'child1', textDirection: TextDirection.ltr, selected: true, ), ), ), ], ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'child1', rect: TestSemantics.fullScreen, flags: SemanticsFlag.isSelected.index, ), ], ))); // forking semantics await tester.pumpWidget( Semantics( container: true, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SizedBox( height: 10.0, child: Semantics( label: 'child1', textDirection: TextDirection.ltr, selected: true, ), ), SizedBox( height: 10.0, child: IgnorePointer( ignoring: false, child: Semantics( label: 'child2', textDirection: TextDirection.ltr, selected: true, ), ), ), ], ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( id: 2, label: 'child1', rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), flags: SemanticsFlag.isSelected.index, ), TestSemantics( id: 3, label: 'child2', rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), flags: SemanticsFlag.isSelected.index, ), ], ), ], ), ignoreTransform: true)); // toggle a branch off await tester.pumpWidget( Semantics( container: true, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SizedBox( height: 10.0, child: Semantics( label: 'child1', textDirection: TextDirection.ltr, selected: true, ), ), SizedBox( height: 10.0, child: IgnorePointer( child: Semantics( label: 'child2', textDirection: TextDirection.ltr, selected: true, ), ), ), ], ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'child1', rect: TestSemantics.fullScreen, flags: SemanticsFlag.isSelected.index, ), ], ))); // toggle a branch back on await tester.pumpWidget( Semantics( container: true, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SizedBox( height: 10.0, child: Semantics( label: 'child1', textDirection: TextDirection.ltr, selected: true, ), ), SizedBox( height: 10.0, child: IgnorePointer( ignoring: false, child: Semantics( label: 'child2', textDirection: TextDirection.ltr, selected: true, ), ), ), ], ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( id: 4, label: 'child1', rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), flags: SemanticsFlag.isSelected.index, ), TestSemantics( id: 3, label: 'child2', rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), flags: SemanticsFlag.isSelected.index, ), ], ), ], ), ignoreTransform: true)); semantics.dispose(); }); }
flutter/packages/flutter/test/widgets/semantics_1_test.dart/0
{'file_path': 'flutter/packages/flutter/test/widgets/semantics_1_test.dart', 'repo_id': 'flutter', 'token_count': 3460}
// 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'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('Simple tree is simple', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const Center( child: Text('Hello!', textDirection: TextDirection.ltr), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'Hello!', textDirection: TextDirection.ltr, rect: const Rect.fromLTRB(0.0, 0.0, 84.0, 14.0), transform: Matrix4.translationValues(358.0, 293.0, 0.0), ), ], ))); semantics.dispose(); }); testWidgets('Simple tree is simple - material', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); // Not using Text widget because of https://github.com/flutter/flutter/issues/12357. await tester.pumpWidget(MaterialApp( home: Center( child: Semantics( label: 'Hello!', child: const SizedBox( width: 10.0, height: 10.0, ), ), ), )); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0), children: <TestSemantics>[ TestSemantics( id: 2, rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0), children: <TestSemantics>[ TestSemantics( id: 3, rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0), flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 4, label: 'Hello!', textDirection: TextDirection.ltr, rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0), transform: Matrix4.translationValues(395.0, 295.0, 0.0), ), ], ), ], ), ], ), ], ))); semantics.dispose(); }); }
flutter/packages/flutter/test/widgets/simple_semantics_test.dart/0
{'file_path': 'flutter/packages/flutter/test/widgets/simple_semantics_test.dart', 'repo_id': 'flutter', 'token_count': 1292}
// 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 InnerWidget extends StatefulWidget { const InnerWidget({ super.key }); @override InnerWidgetState createState() => InnerWidgetState(); } class InnerWidgetState extends State<InnerWidget> { bool _didInitState = false; @override void initState() { super.initState(); _didInitState = true; } @override Widget build(BuildContext context) { return Container(); } } class OuterContainer extends StatefulWidget { const OuterContainer({ super.key, required this.child }); final InnerWidget child; @override OuterContainerState createState() => OuterContainerState(); } class OuterContainerState extends State<OuterContainer> { @override Widget build(BuildContext context) { return widget.child; } } void main() { testWidgets('resync stateful widget', (WidgetTester tester) async { const Key innerKey = Key('inner'); const Key outerKey = Key('outer'); const InnerWidget inner1 = InnerWidget(key: innerKey); InnerWidget inner2; const OuterContainer outer1 = OuterContainer(key: outerKey, child: inner1); OuterContainer outer2; await tester.pumpWidget(outer1); final StatefulElement innerElement = tester.element(find.byKey(innerKey)); final InnerWidgetState innerElementState = innerElement.state as InnerWidgetState; expect(innerElementState.widget, equals(inner1)); expect(innerElementState._didInitState, isTrue); expect(innerElement.renderObject!.attached, isTrue); inner2 = const InnerWidget(key: innerKey); outer2 = OuterContainer(key: outerKey, child: inner2); await tester.pumpWidget(outer2); expect(tester.element(find.byKey(innerKey)), equals(innerElement)); expect(innerElement.state, equals(innerElementState)); expect(innerElementState.widget, equals(inner2)); expect(innerElementState._didInitState, isTrue); expect(innerElement.renderObject!.attached, isTrue); final StatefulElement outerElement = tester.element(find.byKey(outerKey)); expect(outerElement.state.widget, equals(outer2)); outerElement.markNeedsBuild(); await tester.pump(); expect(tester.element(find.byKey(innerKey)), equals(innerElement)); expect(innerElement.state, equals(innerElementState)); expect(innerElementState.widget, equals(inner2)); expect(innerElement.renderObject!.attached, isTrue); }); }
flutter/packages/flutter/test/widgets/stateful_components_test.dart/0
{'file_path': 'flutter/packages/flutter/test/widgets/stateful_components_test.dart', 'repo_id': 'flutter', 'token_count': 812}
// 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'; void main() { // Changes made in https://github.com/flutter/flutter/pull/48547 var TextTheme textTheme = TextTheme( display4: displayStyle4, display3: displayStyle3, display2: displayStyle2, display1: displayStyle1, headline: headlineStyle, title: titleStyle, subhead: subheadStyle, body2: body2Style, body1: body1Style, caption: captionStyle, button: buttonStyle, subtitle: subtitleStyle, overline: overlineStyle, ); var TextTheme textTheme = TextTheme(error: ''); // Changes made in https://github.com/flutter/flutter/pull/48547 var TextTheme copiedTextTheme = TextTheme.copyWith( display4: displayStyle4, display3: displayStyle3, display2: displayStyle2, display1: displayStyle1, headline: headlineStyle, title: titleStyle, subhead: subheadStyle, body2: body2Style, body1: body1Style, caption: captionStyle, button: buttonStyle, subtitle: subtitleStyle, overline: overlineStyle, ); var TextTheme copiedTextTheme = TextTheme.copyWith(error: ''); // Changes made in https://github.com/flutter/flutter/pull/48547 var style; style = textTheme.display4; style = textTheme.display3; style = textTheme.display2; style = textTheme.display1; style = textTheme.headline; style = textTheme.title; style = textTheme.subhead; style = textTheme.body2; style = textTheme.body1; style = textTheme.caption; style = textTheme.button; style = textTheme.subtitle; style = textTheme.overline; // Changes made in https://github.com/flutter/flutter/pull/109817 var TextTheme textTheme = TextTheme( headline1: headline1Style, headline2: headline2Style, headline3: headline3Style, headline4: headline4Style, headline5: headline5Style, headline6: headline6Style, subtitle1: subtitle1Style, subtitle2: subtitle2Style, bodyText1: bodyText1Style, bodyText2: bodyText2Style, caption: captionStyle, button: buttonStyle, overline: overlineStyle, ); var TextTheme textTheme = TextTheme(error: ''); // Changes made in https://github.com/flutter/flutter/pull/109817 var TextTheme copiedTextTheme = TextTheme.copyWith( headline1: headline1Style, headline2: headline2Style, headline3: headline3Style, headline4: headline4Style, headline5: headline5Style, headline6: headline6Style, subtitle1: subtitle1Style, subtitle2: subtitle2Style, bodyText1: bodyText1Style, bodyText2: bodyText2Style, caption: captionStyle, button: buttonStyle, overline: overlineStyle, ); var TextTheme copiedTextTheme = TextTheme.copyWith(error: ''); // Changes made in https://github.com/flutter/flutter/pull/109817 var style; style = textTheme.headline1; style = textTheme.headline2; style = textTheme.headline3; style = textTheme.headline4; style = textTheme.headline5; style = textTheme.headline6; style = textTheme.subtitle1; style = textTheme.subtitle2; style = textTheme.bodyText1; style = textTheme.bodyText2; style = textTheme.caption; style = textTheme.button; style = textTheme.overline; }
flutter/packages/flutter/test_fixes/material/text_theme.dart/0
{'file_path': 'flutter/packages/flutter/test_fixes/material/text_theme.dart', 'repo_id': 'flutter', 'token_count': 1159}
// 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final MemoryAllocations ma = MemoryAllocations.instance; setUp(() { assert(!ma.hasListeners); }); testWidgets( '$MemoryAllocations is noop when kFlutterMemoryAllocationsEnabled is false.', (WidgetTester tester) async { ObjectEvent? recievedEvent; ObjectEvent listener(ObjectEvent event) => recievedEvent = event; ma.addListener(listener); expect(ma.hasListeners, isFalse); await _activateFlutterObjects(tester); expect(recievedEvent, isNull); expect(ma.hasListeners, isFalse); ma.removeListener(listener); }, ); } class _TestLeafRenderObjectWidget extends LeafRenderObjectWidget { @override RenderObject createRenderObject(BuildContext context) { return _TestRenderObject(); } } class _TestRenderObject extends RenderObject { @override void debugAssertDoesMeetConstraints() {} @override Rect get paintBounds => throw UnimplementedError(); @override void performLayout() {} @override void performResize() {} @override Rect get semanticBounds => throw UnimplementedError(); } class _TestElement extends RootRenderObjectElement{ _TestElement(): super(_TestLeafRenderObjectWidget()); void makeInactive() { assignOwner(BuildOwner(focusManager: FocusManager())); mount(null, null); deactivate(); } } class _MyStatefulWidget extends StatefulWidget { const _MyStatefulWidget(); @override State<_MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<_MyStatefulWidget> { @override Widget build(BuildContext context) { return Container(); } } /// Create and dispose Flutter objects to fire memory allocation events. Future<void> _activateFlutterObjects(WidgetTester tester) async { final _TestElement element = _TestElement(); element.makeInactive(); element.unmount(); // Create and dispose State: await tester.pumpWidget(const _MyStatefulWidget()); await tester.pumpWidget(const SizedBox.shrink()); }
flutter/packages/flutter/test_release/widgets/memory_allocations_test.dart/0
{'file_path': 'flutter/packages/flutter/test_release/widgets/memory_allocations_test.dart', 'repo_id': 'flutter', 'token_count': 733}
// 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'; /// An object sent from the Flutter Driver to a Flutter application to instruct /// the application to perform a task. abstract class Command { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const Command({ this.timeout }); /// Deserializes this command from the value generated by [serialize]. Command.deserialize(Map<String, String> json) : timeout = _parseTimeout(json); static Duration? _parseTimeout(Map<String, String> json) { final String? timeout = json['timeout']; if (timeout == null) { return null; } return Duration(milliseconds: int.parse(timeout)); } /// The maximum amount of time to wait for the command to complete. /// /// Defaults to no timeout, because it is common for operations to take oddly /// long in test environments (e.g. because the test host is overloaded), and /// having timeouts essentially means having race conditions. final Duration? timeout; /// Identifies the type of the command object and of the handler. String get kind; /// Whether this command requires the widget tree to be initialized before /// the command may be run. /// /// This defaults to true to force the application under test to call [runApp] /// before attempting to remotely drive the application. Subclasses may /// override this to return false if they allow invocation before the /// application has started. /// /// See also: /// /// * [WidgetsBinding.isRootWidgetAttached], which indicates whether the /// widget tree has been initialized. bool get requiresRootWidgetAttached => true; /// Serializes this command to parameter name/value pairs. @mustCallSuper Map<String, String> serialize() { final Map<String, String> result = <String, String>{ 'command': kind, }; if (timeout != null) { result['timeout'] = '${timeout!.inMilliseconds}'; } return result; } } /// An object sent from a Flutter application back to the Flutter Driver in /// response to a command. abstract class Result { /// A const constructor to allow subclasses to be const. const Result(); /// An empty responds that does not include any result data. /// /// Consider using this object as a result for [Command]s that do not return /// any data. static const Result empty = _EmptyResult(); /// Serializes this message to a JSON map. Map<String, dynamic> toJson(); } class _EmptyResult extends Result { const _EmptyResult(); @override Map<String, dynamic> toJson() => <String, dynamic>{}; }
flutter/packages/flutter_driver/lib/src/common/message.dart/0
{'file_path': 'flutter/packages/flutter_driver/lib/src/common/message.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. import 'dart:ui' as ui; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:test_api/src/expect/async_matcher.dart'; // ignore: implementation_imports import 'package:test_api/test_api.dart'; // ignore: deprecated_member_use import 'binding.dart'; import 'finders.dart'; import 'goldens.dart'; /// An unsupported method that exists for API compatibility. Future<ui.Image> captureImage(Element element) { throw UnsupportedError('captureImage is not supported on the web.'); } /// Whether or not [captureImage] is supported. /// /// This can be used to skip tests on platforms that don't support /// capturing images. /// /// Currently this is true except when tests are running in the context of a web /// browser (`flutter test --platform chrome`). const bool canCaptureImage = false; /// The matcher created by [matchesGoldenFile]. This class is enabled when the /// test is running in a web browser using conditional import. class MatchesGoldenFile extends AsyncMatcher { /// Creates an instance of [MatchesGoldenFile]. Called by [matchesGoldenFile]. const MatchesGoldenFile(this.key, this.version); /// Creates an instance of [MatchesGoldenFile]. Called by [matchesGoldenFile]. MatchesGoldenFile.forStringPath(String path, this.version) : key = Uri.parse(path); /// The [key] to the golden image. final Uri key; /// The [version] of the golden image. final int? version; @override Future<String?> matchAsync(dynamic item) async { if (item is! Finder) { return 'web goldens only supports matching finders.'; } final Iterable<Element> elements = item.evaluate(); if (elements.isEmpty) { return 'could not be rendered because no widget was found'; } else if (elements.length > 1) { return 'matched too many widgets'; } final Element element = elements.single; final RenderObject renderObject = _findRepaintBoundary(element); final Size size = renderObject.paintBounds.size; final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance; final Element e = binding.renderViewElement!; // Unlike `flutter_tester`, we don't have the ability to render an element // to an image directly. Instead, we will use `window.render()` to render // only the element being requested, and send a request to the test server // requesting it to take a screenshot through the browser's debug interface. _renderElement(binding.window, renderObject); final String? result = await binding.runAsync<String?>(() async { if (autoUpdateGoldenFiles) { await webGoldenComparator.update(size.width, size.height, key); return null; } try { final bool success = await webGoldenComparator.compare(size.width, size.height, key); return success ? null : 'does not match'; } on TestFailure catch (ex) { return ex.message; } }, additionalTime: const Duration(seconds: 22)); _renderElement(binding.window, _findRepaintBoundary(e)); return result; } @override Description describe(Description description) { final Uri testNameUri = webGoldenComparator.getTestUri(key, version); return description.add('one widget whose rasterized image matches golden image "$testNameUri"'); } } RenderObject _findRepaintBoundary(Element element) { assert(element.renderObject != null); RenderObject renderObject = element.renderObject!; while (!renderObject.isRepaintBoundary) { renderObject = renderObject.parent! as RenderObject; } return renderObject; } void _renderElement(ui.FlutterView window, RenderObject renderObject) { assert(renderObject.debugLayer != null); final Layer layer = renderObject.debugLayer!; final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); if (layer is OffsetLayer) { sceneBuilder.pushOffset(-layer.offset.dx, -layer.offset.dy); } // ignore: invalid_use_of_visible_for_testing_member, invalid_use_of_protected_member layer.updateSubtreeNeedsAddToScene(); // ignore: invalid_use_of_protected_member layer.addToScene(sceneBuilder); sceneBuilder.pop(); window.render(sceneBuilder.build()); }
flutter/packages/flutter_test/lib/src/_matchers_web.dart/0
{'file_path': 'flutter/packages/flutter_test/lib/src/_matchers_web.dart', 'repo_id': 'flutter', 'token_count': 1333}
// 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/services.dart'; /// The [RestorationManager] used for tests. /// /// Unlike the real [RestorationManager], this one just keeps the restoration /// data in memory and does not make it available to the engine. class TestRestorationManager extends RestorationManager { /// Creates a [TestRestorationManager]. TestRestorationManager() { // Ensures that [rootBucket] always returns a synchronous future to avoid // extra pumps in tests. restoreFrom(TestRestorationData.empty); } @override Future<RestorationBucket?> get rootBucket { _debugRootBucketAccessed = true; return super.rootBucket; } /// The current restoration data from which the current state can be restored. /// /// To restore the state to the one described by this data, pass the /// [TestRestorationData] obtained from this getter back to [restoreFrom]. /// /// See also: /// /// * [WidgetTester.getRestorationData], which makes this data available /// in a widget test. TestRestorationData get restorationData => _restorationData; late TestRestorationData _restorationData; /// Whether the [rootBucket] has been obtained. bool get debugRootBucketAccessed => _debugRootBucketAccessed; bool _debugRootBucketAccessed = false; /// Restores the state from the provided [TestRestorationData]. /// /// The restoration data obtained form [restorationData] can be passed into /// this method to restore the state to what it was when the restoration data /// was originally retrieved. /// /// See also: /// /// * [WidgetTester.restoreFrom], which exposes this method to a widget test. void restoreFrom(TestRestorationData data) { _restorationData = data; handleRestorationUpdateFromEngine(enabled: true, data: data.binary); } /// Disabled state restoration. /// /// To turn restoration back on call [restoreFrom]. void disableRestoration() { _restorationData = TestRestorationData.empty; handleRestorationUpdateFromEngine(enabled: false, data: null); } @override Future<void> sendToEngine(Uint8List encodedData) async { _restorationData = TestRestorationData._(encodedData); } } /// Restoration data that can be used to restore the state to the one described /// by this data. /// /// See also: /// /// * [WidgetTester.getRestorationData], which retrieves the restoration data /// from the widget under test. /// * [WidgetTester.restoreFrom], which takes a [TestRestorationData] to /// restore the state of the widget under test from the provided data. class TestRestorationData { const TestRestorationData._(this.binary); /// Empty restoration data indicating that no data is available to restore /// state from. static const TestRestorationData empty = TestRestorationData._(null); /// The serialized representation of the restoration data. /// /// Should only be accessed by the test framework. @protected final Uint8List? binary; }
flutter/packages/flutter_test/lib/src/restoration.dart/0
{'file_path': 'flutter/packages/flutter_test/lib/src/restoration.dart', 'repo_id': 'flutter', 'token_count': 879}
include: ../../analysis_options.yaml linter: rules: # Tests try to catch errors all the time, so we don't worry about these lints for tests: avoid_catches_without_on_clauses: false avoid_catching_errors: false
flutter/packages/flutter_test/test/analysis_options.yaml/0
{'file_path': 'flutter/packages/flutter_test/test/analysis_options.yaml', 'repo_id': 'flutter', 'token_count': 76}
// 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:meta/meta.dart'; import 'package:process/process.dart'; import '../convert.dart'; import 'io.dart'; import 'logger.dart'; typedef StringConverter = String? Function(String string); /// A function that will be run before the VM exits. typedef ShutdownHook = FutureOr<void> Function(); // TODO(ianh): We have way too many ways to run subprocesses in this project. // Convert most of these into one or more lightweight wrappers around the // [ProcessManager] API using named parameters for the various options. // See [here](https://github.com/flutter/flutter/pull/14535#discussion_r167041161) // for more details. abstract class ShutdownHooks { factory ShutdownHooks() => _DefaultShutdownHooks(); /// Registers a [ShutdownHook] to be executed before the VM exits. void addShutdownHook( ShutdownHook shutdownHook ); @visibleForTesting List<ShutdownHook> get registeredHooks; /// Runs all registered shutdown hooks and returns a future that completes when /// all such hooks have finished. /// /// Shutdown hooks will be run in groups by their [ShutdownStage]. All shutdown /// hooks within a given stage will be started in parallel and will be /// guaranteed to run to completion before shutdown hooks in the next stage are /// started. /// /// This class is constructed before the [Logger], so it cannot be direct /// injected in the constructor. Future<void> runShutdownHooks(Logger logger); } class _DefaultShutdownHooks implements ShutdownHooks { _DefaultShutdownHooks(); @override final List<ShutdownHook> registeredHooks = <ShutdownHook>[]; bool _shutdownHooksRunning = false; @override void addShutdownHook( ShutdownHook shutdownHook ) { assert(!_shutdownHooksRunning); registeredHooks.add(shutdownHook); } @override Future<void> runShutdownHooks(Logger logger) async { logger.printTrace( 'Running ${registeredHooks.length} shutdown hook${registeredHooks.length == 1 ? '' : 's'}', ); _shutdownHooksRunning = true; try { final List<Future<dynamic>> futures = <Future<dynamic>>[]; for (final ShutdownHook shutdownHook in registeredHooks) { final FutureOr<dynamic> result = shutdownHook(); if (result is Future<dynamic>) { futures.add(result); } } await Future.wait<dynamic>(futures); } finally { _shutdownHooksRunning = false; } logger.printTrace('Shutdown hooks complete'); } } class ProcessExit implements Exception { ProcessExit(this.exitCode, {this.immediate = false}); final bool immediate; final int exitCode; String get message => 'ProcessExit: $exitCode'; @override String toString() => message; } class RunResult { RunResult(this.processResult, this._command) : assert(_command.isNotEmpty); final ProcessResult processResult; final List<String> _command; int get exitCode => processResult.exitCode; String get stdout => processResult.stdout as String; String get stderr => processResult.stderr as String; @override String toString() { final StringBuffer out = StringBuffer(); if (stdout.isNotEmpty) { out.writeln(stdout); } if (stderr.isNotEmpty) { out.writeln(stderr); } return out.toString().trimRight(); } /// Throws a [ProcessException] with the given `message`. void throwException(String message) { throw ProcessException( _command.first, _command.skip(1).toList(), message, exitCode, ); } } typedef RunResultChecker = bool Function(int); abstract class ProcessUtils { factory ProcessUtils({ required ProcessManager processManager, required Logger logger, }) => _DefaultProcessUtils( processManager: processManager, logger: logger, ); /// Spawns a child process to run the command [cmd]. /// /// When [throwOnError] is `true`, if the child process finishes with a non-zero /// exit code, a [ProcessException] is thrown. /// /// If [throwOnError] is `true`, and [allowedFailures] is supplied, /// a [ProcessException] is only thrown on a non-zero exit code if /// [allowedFailures] returns false when passed the exit code. /// /// When [workingDirectory] is set, it is the working directory of the child /// process. /// /// When [allowReentrantFlutter] is set to `true`, the child process is /// permitted to call the Flutter tool. By default it is not. /// /// When [environment] is supplied, it is used as the environment for the child /// process. /// /// When [timeout] is supplied, [runAsync] will kill the child process and /// throw a [ProcessException] when it doesn't finish in time. /// /// If [timeout] is supplied, the command will be retried [timeoutRetries] times /// if it times out. Future<RunResult> run( List<String> cmd, { bool throwOnError = false, RunResultChecker? allowedFailures, String? workingDirectory, bool allowReentrantFlutter = false, Map<String, String>? environment, Duration? timeout, int timeoutRetries = 0, }); /// Run the command and block waiting for its result. RunResult runSync( List<String> cmd, { bool throwOnError = false, bool verboseExceptions = false, RunResultChecker? allowedFailures, bool hideStdout = false, String? workingDirectory, Map<String, String>? environment, bool allowReentrantFlutter = false, Encoding encoding = systemEncoding, }); /// This runs the command in the background from the specified working /// directory. Completes when the process has been started. Future<Process> start( List<String> cmd, { String? workingDirectory, bool allowReentrantFlutter = false, Map<String, String>? environment, ProcessStartMode mode = ProcessStartMode.normal, }); /// This runs the command and streams stdout/stderr from the child process to /// this process' stdout/stderr. Completes with the process's exit code. /// /// If [filter] is null, no lines are removed. /// /// If [filter] is non-null, all lines that do not match it are removed. If /// [mapFunction] is present, all lines that match [filter] are also forwarded /// to [mapFunction] for further processing. /// /// If [stdoutErrorMatcher] is non-null, matching lines from stdout will be /// treated as errors, just as if they had been logged to stderr instead. Future<int> stream( List<String> cmd, { String? workingDirectory, bool allowReentrantFlutter = false, String prefix = '', bool trace = false, RegExp? filter, RegExp? stdoutErrorMatcher, StringConverter? mapFunction, Map<String, String>? environment, }); bool exitsHappySync( List<String> cli, { Map<String, String>? environment, }); Future<bool> exitsHappy( List<String> cli, { Map<String, String>? environment, }); } class _DefaultProcessUtils implements ProcessUtils { _DefaultProcessUtils({ required ProcessManager processManager, required Logger logger, }) : _processManager = processManager, _logger = logger; final ProcessManager _processManager; final Logger _logger; @override Future<RunResult> run( List<String> cmd, { bool throwOnError = false, RunResultChecker? allowedFailures, String? workingDirectory, bool allowReentrantFlutter = false, Map<String, String>? environment, Duration? timeout, int timeoutRetries = 0, }) async { if (cmd.isEmpty) { throw ArgumentError('cmd must be a non-empty list'); } if (timeoutRetries < 0) { throw ArgumentError('timeoutRetries must be non-negative'); } _traceCommand(cmd, workingDirectory: workingDirectory); // When there is no timeout, there's no need to kill a running process, so // we can just use _processManager.run(). if (timeout == null) { final ProcessResult results = await _processManager.run( cmd, workingDirectory: workingDirectory, environment: _environment(allowReentrantFlutter, environment), ); final RunResult runResult = RunResult(results, cmd); _logger.printTrace(runResult.toString()); if (throwOnError && runResult.exitCode != 0 && (allowedFailures == null || !allowedFailures(runResult.exitCode))) { runResult.throwException('Process exited abnormally:\n$runResult'); } return runResult; } // When there is a timeout, we have to kill the running process, so we have // to use _processManager.start() through _runCommand() above. while (true) { assert(timeoutRetries >= 0); timeoutRetries = timeoutRetries - 1; final Process process = await start( cmd, workingDirectory: workingDirectory, allowReentrantFlutter: allowReentrantFlutter, environment: environment, ); final StringBuffer stdoutBuffer = StringBuffer(); final StringBuffer stderrBuffer = StringBuffer(); final Future<void> stdoutFuture = process.stdout .transform<String>(const Utf8Decoder(reportErrors: false)) .listen(stdoutBuffer.write) .asFuture<void>(); final Future<void> stderrFuture = process.stderr .transform<String>(const Utf8Decoder(reportErrors: false)) .listen(stderrBuffer.write) .asFuture<void>(); int? exitCode; exitCode = await process.exitCode.then<int?>((int x) => x).timeout(timeout, onTimeout: () { // The process timed out. Kill it. _processManager.killPid(process.pid); return null; }); String stdoutString; String stderrString; try { Future<void> stdioFuture = Future.wait<void>(<Future<void>>[stdoutFuture, stderrFuture]); if (exitCode == null) { // If we had to kill the process for a timeout, only wait a short time // for the stdio streams to drain in case killing the process didn't // work. stdioFuture = stdioFuture.timeout(const Duration(seconds: 1)); } await stdioFuture; } on Exception { // Ignore errors on the process' stdout and stderr streams. Just capture // whatever we got, and use the exit code } stdoutString = stdoutBuffer.toString(); stderrString = stderrBuffer.toString(); final ProcessResult result = ProcessResult( process.pid, exitCode ?? -1, stdoutString, stderrString); final RunResult runResult = RunResult(result, cmd); // If the process did not timeout. We are done. if (exitCode != null) { _logger.printTrace(runResult.toString()); if (throwOnError && runResult.exitCode != 0 && (allowedFailures == null || !allowedFailures(exitCode))) { runResult.throwException('Process exited abnormally:\n$runResult'); } return runResult; } // If we are out of timeoutRetries, throw a ProcessException. if (timeoutRetries < 0) { runResult.throwException('Process timed out:\n$runResult'); } // Log the timeout with a trace message in verbose mode. _logger.printTrace( 'Process "${cmd[0]}" timed out. $timeoutRetries attempts left:\n' '$runResult', ); } // Unreachable. } @override RunResult runSync( List<String> cmd, { bool throwOnError = false, bool verboseExceptions = false, RunResultChecker? allowedFailures, bool hideStdout = false, String? workingDirectory, Map<String, String>? environment, bool allowReentrantFlutter = false, Encoding encoding = systemEncoding, }) { _traceCommand(cmd, workingDirectory: workingDirectory); final ProcessResult results = _processManager.runSync( cmd, workingDirectory: workingDirectory, environment: _environment(allowReentrantFlutter, environment), stderrEncoding: encoding, stdoutEncoding: encoding, ); final RunResult runResult = RunResult(results, cmd); _logger.printTrace('Exit code ${runResult.exitCode} from: ${cmd.join(' ')}'); bool failedExitCode = runResult.exitCode != 0; if (allowedFailures != null && failedExitCode) { failedExitCode = !allowedFailures(runResult.exitCode); } if (runResult.stdout.isNotEmpty && !hideStdout) { if (failedExitCode && throwOnError) { _logger.printStatus(runResult.stdout.trim()); } else { _logger.printTrace(runResult.stdout.trim()); } } if (runResult.stderr.isNotEmpty) { if (failedExitCode && throwOnError) { _logger.printError(runResult.stderr.trim()); } else { _logger.printTrace(runResult.stderr.trim()); } } if (failedExitCode && throwOnError) { String message = 'The command failed'; if (verboseExceptions) { message = 'The command failed\nStdout:\n${runResult.stdout}\n' 'Stderr:\n${runResult.stderr}'; } runResult.throwException(message); } return runResult; } @override Future<Process> start( List<String> cmd, { String? workingDirectory, bool allowReentrantFlutter = false, Map<String, String>? environment, ProcessStartMode mode = ProcessStartMode.normal, }) { _traceCommand(cmd, workingDirectory: workingDirectory); return _processManager.start( cmd, workingDirectory: workingDirectory, environment: _environment(allowReentrantFlutter, environment), mode: mode, ); } @override Future<int> stream( List<String> cmd, { String? workingDirectory, bool allowReentrantFlutter = false, String prefix = '', bool trace = false, RegExp? filter, RegExp? stdoutErrorMatcher, StringConverter? mapFunction, Map<String, String>? environment, }) async { final Process process = await start( cmd, workingDirectory: workingDirectory, allowReentrantFlutter: allowReentrantFlutter, environment: environment, ); final StreamSubscription<String> stdoutSubscription = process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .where((String line) => filter == null || filter.hasMatch(line)) .listen((String line) { String? mappedLine = line; if (mapFunction != null) { mappedLine = mapFunction(line); } if (mappedLine != null) { final String message = '$prefix$mappedLine'; if (stdoutErrorMatcher?.hasMatch(mappedLine) ?? false) { _logger.printError(message, wrap: false); } else if (trace) { _logger.printTrace(message); } else { _logger.printStatus(message, wrap: false); } } }); final StreamSubscription<String> stderrSubscription = process.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .where((String line) => filter == null || filter.hasMatch(line)) .listen((String line) { String? mappedLine = line; if (mapFunction != null) { mappedLine = mapFunction(line); } if (mappedLine != null) { _logger.printError('$prefix$mappedLine', wrap: false); } }); // Wait for stdout to be fully processed // because process.exitCode may complete first causing flaky tests. await Future.wait<void>(<Future<void>>[ stdoutSubscription.asFuture<void>(), stderrSubscription.asFuture<void>(), ]); // The streams as futures have already completed, so waiting for the // potentially async stream cancellation to complete likely has no benefit. // Further, some Stream implementations commonly used in tests don't // complete the Future returned here, which causes tests using // mocks/FakeAsync to fail when these Futures are awaited. unawaited(stdoutSubscription.cancel()); unawaited(stderrSubscription.cancel()); return process.exitCode; } @override bool exitsHappySync( List<String> cli, { Map<String, String>? environment, }) { _traceCommand(cli); if (!_processManager.canRun(cli.first)) { _logger.printTrace('$cli either does not exist or is not executable.'); return false; } try { return _processManager.runSync(cli, environment: environment).exitCode == 0; } on Exception catch (error) { _logger.printTrace('$cli failed with $error'); return false; } } @override Future<bool> exitsHappy( List<String> cli, { Map<String, String>? environment, }) async { _traceCommand(cli); if (!_processManager.canRun(cli.first)) { _logger.printTrace('$cli either does not exist or is not executable.'); return false; } try { return (await _processManager.run(cli, environment: environment)).exitCode == 0; } on Exception catch (error) { _logger.printTrace('$cli failed with $error'); return false; } } Map<String, String>? _environment(bool allowReentrantFlutter, [ Map<String, String>? environment, ]) { if (allowReentrantFlutter) { if (environment == null) { environment = <String, String>{'FLUTTER_ALREADY_LOCKED': 'true'}; } else { environment['FLUTTER_ALREADY_LOCKED'] = 'true'; } } return environment; } void _traceCommand(List<String> args, { String? workingDirectory }) { final String argsText = args.join(' '); if (workingDirectory == null) { _logger.printTrace('executing: $argsText'); } else { _logger.printTrace('executing: [$workingDirectory/] $argsText'); } } }
flutter/packages/flutter_tools/lib/src/base/process.dart/0
{'file_path': 'flutter/packages/flutter_tools/lib/src/base/process.dart', 'repo_id': 'flutter', 'token_count': 6417}
// 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 '../android/android_workflow.dart'; import '../base/common.dart'; import '../globals.dart' as globals; import '../runner/flutter_command.dart'; class DoctorCommand extends FlutterCommand { DoctorCommand({this.verbose = false}) { argParser.addFlag('android-licenses', negatable: false, help: "Run the Android SDK manager tool to accept the SDK's licenses.", ); argParser.addOption('check-for-remote-artifacts', hide: !verbose, help: 'Used to determine if Flutter engine artifacts for all platforms ' 'are available for download.', valueHelp: 'engine revision git hash',); } final bool verbose; @override final String name = 'doctor'; @override final String description = 'Show information about the installed tooling.'; @override final String category = FlutterCommandCategory.sdk; @override Future<FlutterCommandResult> runCommand() async { globals.flutterVersion.fetchTagsAndUpdate(); if (argResults?.wasParsed('check-for-remote-artifacts') ?? false) { final String engineRevision = stringArgDeprecated('check-for-remote-artifacts')!; if (engineRevision.startsWith(RegExp(r'[a-f0-9]{1,40}'))) { final bool success = await globals.doctor?.checkRemoteArtifacts(engineRevision) ?? false; if (success) { throwToolExit('Artifacts for engine $engineRevision are missing or are ' 'not yet available.', exitCode: 1); } } else { throwToolExit('Remote artifact revision $engineRevision is not a valid ' 'git hash.'); } } final bool success = await globals.doctor?.diagnose( androidLicenses: boolArgDeprecated('android-licenses'), verbose: verbose, androidLicenseValidator: androidLicenseValidator, ) ?? false; return FlutterCommandResult(success ? ExitStatus.success : ExitStatus.warning); } }
flutter/packages/flutter_tools/lib/src/commands/doctor.dart/0
{'file_path': 'flutter/packages/flutter_tools/lib/src/commands/doctor.dart', 'repo_id': 'flutter', 'token_count': 717}
// 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 '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/net.dart'; import '../base/process.dart'; import '../convert.dart'; import '../globals.dart' as globals; /// This is a basic wrapper class for the Fuchsia SDK's `pm` tool. class FuchsiaPM { /// Initializes the staging area at [buildPath] for creating the Fuchsia /// package for the app named [appName]. /// /// When successful, this creates a file under [buildPath] at `meta/package`. /// /// NB: The [buildPath] should probably be e.g. `build/fuchsia/pkg`, and the /// [appName] should probably be the name of the app from the pubspec file. Future<bool> init(String buildPath, String appName) { return _runPMCommand(<String>[ '-o', buildPath, '-n', appName, 'init', ]); } /// Updates, signs, and seals a Fuchsia package. /// /// [buildPath] should be the same [buildPath] passed to [init]. /// [manifestPath] must be a file containing lines formatted as follows: /// /// data/path/to/file/in/the/package=/path/to/file/on/the/host /// /// which describe the contents of the Fuchsia package. It must also contain /// two other entries: /// /// meta/$APPNAME.cm=/path/to/cm/on/the/host/$APPNAME.cm /// meta/package=/path/to/package/file/from/init/package /// /// where $APPNAME is the same [appName] passed to [init], and meta/package /// is set up to be the file `meta/package` created by [init]. Future<bool> build(String buildPath, String manifestPath) { return _runPMCommand(<String>[ '-o', buildPath, '-m', manifestPath, 'build', ]); } /// Constructs a .far representation of the Fuchsia package. /// /// When successful, creates a file `app_name-0.far` under [buildPath], which /// is the Fuchsia package. /// /// [buildPath] should be the same path passed to [init], and [manifestPath] /// should be the same manifest passed to [build]. Future<bool> archive(String buildPath, String manifestPath) { return _runPMCommand(<String>[ '-o', buildPath, '-m', manifestPath, 'archive', ]); } /// Initializes a new package repository at [repoPath] to be later served by /// the 'serve' command. Future<bool> newrepo(String repoPath) { return _runPMCommand(<String>[ 'newrepo', '-repo', repoPath, ]); } /// Spawns an http server in a new process for serving Fuchsia packages. /// /// The argument [repoPath] should have previously been an argument to /// [newrepo]. The [host] should be the host reported by /// [FuchsiaFfx.resolve], and [port] should be an unused port for the /// http server to bind. Future<Process> serve(String repoPath, String host, int port) async { final File? pm = globals.fuchsiaArtifacts?.pm; if (pm == null) { throwToolExit('Fuchsia pm tool not found'); } if (isIPv6Address(host.split('%').first)) { host = '[$host]'; } final List<String> command = <String>[ pm.path, 'serve', '-repo', repoPath, '-l', '$host:$port', '-c', '2', ]; final Process process = await globals.processUtils.start(command); process.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen(globals.printTrace); process.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen(globals.printError); return process; } /// Publishes a Fuchsia package to a served package repository. /// /// For a package repo initialized with [newrepo] at [repoPath] and served /// by [serve], this call publishes the `far` package at [packagePath] to /// the repo such that it will be visible to devices connecting to the /// package server. Future<bool> publish(String repoPath, String packagePath) { return _runPMCommand(<String>[ 'publish', '-a', '-r', repoPath, '-f', packagePath, ]); } Future<bool> _runPMCommand(List<String> args) async { final File? pm = globals.fuchsiaArtifacts?.pm; if (pm == null) { throwToolExit('Fuchsia pm tool not found'); } final List<String> command = <String>[pm.path, ...args]; final RunResult result = await globals.processUtils.run(command); return result.exitCode == 0; } } /// A class for running and retaining state for a Fuchsia package server. /// /// [FuchsiaPackageServer] takes care of initializing the package repository, /// spinning up the package server, publishing packages, and shutting down the /// server. /// /// Example usage: /// var server = FuchsiaPackageServer( /// '/path/to/repo', /// 'server_name', /// await FuchsiaFfx.resolve(deviceName), /// await freshPort()); /// try { /// await server.start(); /// await server.addPackage(farArchivePath); /// ... /// } finally { /// server.stop(); /// } class FuchsiaPackageServer { factory FuchsiaPackageServer( String repo, String name, String host, int port) { return FuchsiaPackageServer._(repo, name, host, port); } FuchsiaPackageServer._(this._repo, this.name, this._host, this._port); static const String deviceHost = 'fuchsia.com'; static const String toolHost = 'flutter-tool'; final String _repo; final String _host; final int _port; Process? _process; // The name used to reference the server by fuchsia-pkg:// urls. final String name; int get port => _port; /// Uses [FuchsiaPM.newrepo] and [FuchsiaPM.serve] to spin up a new Fuchsia /// package server. /// /// Returns false if the repo could not be created or the server could not /// be spawned, and true otherwise. Future<bool> start() async { if (_process != null) { globals.printError('$this already started!'); return false; } // initialize a new repo. final FuchsiaPM? fuchsiaPM = globals.fuchsiaSdk?.fuchsiaPM; if (fuchsiaPM == null || !await fuchsiaPM.newrepo(_repo)) { globals.printError('Failed to create a new package server repo'); return false; } _process = await fuchsiaPM.serve(_repo, _host, _port); // Put a completer on _process.exitCode to watch for error. unawaited(_process?.exitCode.whenComplete(() { // If _process is null, then the server was stopped deliberately. if (_process != null) { globals.printError('Error running Fuchsia pm tool "serve" command'); } })); return true; } /// Forcefully stops the package server process by sending it SIGTERM. void stop() { if (_process != null) { _process?.kill(); _process = null; } } /// Uses [FuchsiaPM.publish] to add the Fuchsia 'far' package at /// [packagePath] to the package server. /// /// Returns true on success and false if the server wasn't started or the /// publish command failed. Future<bool> addPackage(File package) async { if (_process == null) { return false; } return (await globals.fuchsiaSdk?.fuchsiaPM.publish(_repo, package.path)) ?? false; } @override String toString() { final String p = (_process == null) ? 'stopped' : 'running ${_process?.pid}'; return 'FuchsiaPackageServer at $_host:$_port ($p)'; } }
flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart/0
{'file_path': 'flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart', 'repo_id': 'flutter', 'token_count': 2732}
// 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:convert/convert.dart'; import 'package:crypto/crypto.dart'; import '../convert.dart'; import '../persistent_tool_state.dart'; /// This message is displayed on the first run of the Flutter tool, or anytime /// that the contents of this string change. const String _kFlutterFirstRunMessage = ''' ╔════════════════════════════════════════════════════════════════════════════╗ β•‘ Welcome to Flutter! - https://flutter.dev β•‘ β•‘ β•‘ β•‘ The Flutter tool uses Google Analytics to anonymously report feature usage β•‘ β•‘ statistics and basic crash reports. This data is used to help improve β•‘ β•‘ Flutter tools over time. β•‘ β•‘ β•‘ β•‘ Flutter tool analytics are not sent on the very first run. To disable β•‘ β•‘ reporting, type 'flutter config --no-analytics'. To display the current β•‘ β•‘ setting, type 'flutter config'. If you opt out of analytics, an opt-out β•‘ β•‘ event will be sent, and then no further information will be sent by the β•‘ β•‘ Flutter tool. β•‘ β•‘ β•‘ β•‘ By downloading the Flutter SDK, you agree to the Google Terms of Service. β•‘ β•‘ Note: The Google Privacy Policy describes how data is handled in this β•‘ β•‘ service. β•‘ β•‘ β•‘ β•‘ Moreover, Flutter includes the Dart SDK, which may send usage metrics and β•‘ β•‘ crash reports to Google. β•‘ β•‘ β•‘ β•‘ Read about data we send with crash reports: β•‘ β•‘ https://flutter.dev/docs/reference/crash-reporting β•‘ β•‘ β•‘ β•‘ See Google's privacy policy: β•‘ β•‘ https://policies.google.com/privacy β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• '''; /// The first run messenger determines whether the first run license terms /// need to be displayed. class FirstRunMessenger { FirstRunMessenger({ required PersistentToolState persistentToolState }) : _persistentToolState = persistentToolState; final PersistentToolState _persistentToolState; /// Whether the license terms should be displayed. /// /// This is implemented by caching a hash of the previous license terms. This /// does not update the cache hash value. /// /// The persistent tool state setting [PersistentToolState.redisplayWelcomeMessage] /// can also be used to make this return false. This is primarily used to ensure /// that the license terms are not printed during a `flutter upgrade`, until the /// user manually runs the tool. bool shouldDisplayLicenseTerms() { if (_persistentToolState.shouldRedisplayWelcomeMessage == false) { return false; } final String? oldHash = _persistentToolState.lastActiveLicenseTermsHash; return oldHash != _currentHash; } /// Update the cached license terms hash once the new terms have been displayed. void confirmLicenseTermsDisplayed() { _persistentToolState.setLastActiveLicenseTermsHash(_currentHash); } /// The hash of the current license representation. String get _currentHash => hex.encode(md5.convert(utf8.encode(licenseTerms)).bytes); /// The current license terms. String get licenseTerms => _kFlutterFirstRunMessage; }
flutter/packages/flutter_tools/lib/src/reporting/first_run.dart/0
{'file_path': 'flutter/packages/flutter_tools/lib/src/reporting/first_run.dart', 'repo_id': 'flutter', 'token_count': 1894}
// 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/platform.dart'; import '../doctor_validator.dart'; import 'chrome.dart'; /// A validator for Chromium-based browsers. abstract class ChromiumValidator extends DoctorValidator { const ChromiumValidator(super.title); Platform get _platform; ChromiumLauncher get _chromiumLauncher; String get _name; @override Future<ValidationResult> validate() async { final bool canRunChromium = _chromiumLauncher.canFindExecutable(); final String chromiumSearchLocation = _chromiumLauncher.findExecutable(); final List<ValidationMessage> messages = <ValidationMessage>[ if (_platform.environment.containsKey(kChromeEnvironment)) if (!canRunChromium) ValidationMessage.hint('$chromiumSearchLocation is not executable.') else ValidationMessage('$kChromeEnvironment = $chromiumSearchLocation') else if (!canRunChromium) ValidationMessage.hint('Cannot find $_name. Try setting ' '$kChromeEnvironment to a $_name executable.') else ValidationMessage('$_name at $chromiumSearchLocation'), ]; if (!canRunChromium) { return ValidationResult( ValidationType.missing, messages, statusInfo: 'Cannot find $_name executable at $chromiumSearchLocation', ); } return ValidationResult( ValidationType.success, messages, ); } } /// A validator that checks whether Chrome is installed and can run. class ChromeValidator extends ChromiumValidator { const ChromeValidator({ required Platform platform, required ChromiumLauncher chromiumLauncher, }) : _platform = platform, _chromiumLauncher = chromiumLauncher, super('Chrome - develop for the web'); @override final Platform _platform; @override final ChromiumLauncher _chromiumLauncher; @override String get _name => 'Chrome'; } /// A validator that checks whether Edge is installed and can run. class EdgeValidator extends ChromiumValidator { const EdgeValidator({ required Platform platform, required ChromiumLauncher chromiumLauncher, }) : _platform = platform, _chromiumLauncher = chromiumLauncher, super('Edge - develop for the web'); @override final Platform _platform; @override final ChromiumLauncher _chromiumLauncher; @override String get _name => 'Edge'; }
flutter/packages/flutter_tools/lib/src/web/web_validator.dart/0
{'file_path': 'flutter/packages/flutter_tools/lib/src/web/web_validator.dart', 'repo_id': 'flutter', 'token_count': 846}
// 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 'package:args/command_runner.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/devices.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/web/web_device.dart'; import 'package:test/fake.dart'; import '../../src/context.dart'; import '../../src/fakes.dart'; import '../../src/test_flutter_command_runner.dart'; void main() { late FakeDeviceManager deviceManager; late BufferLogger logger; setUpAll(() { Cache.disableLocking(); }); setUp(() { deviceManager = FakeDeviceManager(); logger = BufferLogger.test(); }); testUsingContext('devices can display no connected devices with the --machine flag', () async { final DevicesCommand command = DevicesCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['devices', '--machine']); expect( json.decode(logger.statusText), isEmpty, ); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('devices can display via the --machine flag', () async { deviceManager.devices = <Device>[ WebServerDevice(logger: logger), ]; final DevicesCommand command = DevicesCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['devices', '--machine']); expect( json.decode(logger.statusText), contains(equals( <String, Object>{ 'name': 'Web Server', 'id': 'web-server', 'isSupported': true, 'targetPlatform': 'web-javascript', 'emulator': false, 'sdk': 'Flutter Tools', 'capabilities': <String, Object>{ 'hotReload': true, 'hotRestart': true, 'screenshot': false, 'fastStart': false, 'flutterExit': false, 'hardwareRendering': false, 'startPaused': true, }, }, )), ); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), DeviceManager: () => deviceManager, Logger: () => logger, }); } class FakeDeviceManager extends Fake implements DeviceManager { List<Device> devices = <Device>[]; @override String? specifiedDeviceId; @override Future<List<Device>> refreshAllConnectedDevices({Duration? timeout}) async { return devices; } }
flutter/packages/flutter_tools/test/commands.shard/permeable/devices_test.dart/0
{'file_path': 'flutter/packages/flutter_tools/test/commands.shard/permeable/devices_test.dart', 'repo_id': 'flutter', 'token_count': 1034}
// 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/android/android_device.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/device_port_forwarder.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; void main() { testWithoutContext('AndroidDevicePortForwarder returns the generated host ' 'port from stdout', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:0', 'tcp:123'], stdout: '456', ), ]), logger: BufferLogger.test(), ); expect(await forwarder.forward(123), 456); }); testWithoutContext('AndroidDevicePortForwarder returns the supplied host ' 'port when stdout is empty', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], ), ]), logger: BufferLogger.test(), ); expect(await forwarder.forward(123, hostPort: 456), 456); }); testWithoutContext('AndroidDevicePortForwarder returns the supplied host port ' 'when stdout is the host port', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], stdout: '456', ), ]), logger: BufferLogger.test(), ); expect(await forwarder.forward(123, hostPort: 456), 456); }); testWithoutContext('AndroidDevicePortForwarder throws an exception when stdout ' 'is not blank nor the host port', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], stdout: '123456', ), ]), logger: BufferLogger.test(), ); expect(forwarder.forward(123, hostPort: 456), throwsProcessException()); }); testWithoutContext('AndroidDevicePortForwarder forwardedPorts returns empty ' 'list when forward failed', () { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--list'], exitCode: 1, ), ]), logger: BufferLogger.test(), ); expect(forwarder.forwardedPorts, isEmpty); }); testWithoutContext('disposing device disposes the portForwarder', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:0', 'tcp:123'], stdout: '456', ), const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--list'], stdout: '1234 tcp:456 tcp:123', ), const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], ), ]); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: BufferLogger.test(), ); expect(await forwarder.forward(123), equals(456)); await forwarder.dispose(); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('failures to unforward port do not throw if the forward is missing', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], stderr: "error: listener 'tcp:456' not found", exitCode: 1, ), ]); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: BufferLogger.test(), ); await forwarder.unforward(ForwardedPort(456, 23)); }); testWithoutContext('failures to unforward port print error but are non-fatal', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], stderr: 'error: everything is broken!', exitCode: 1, ), ]); final BufferLogger logger = BufferLogger.test(); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: logger, ); await forwarder.unforward(ForwardedPort(456, 23)); expect(logger.errorText, contains('Failed to unforward port: error: everything is broken!')); }); }
flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart/0
{'file_path': 'flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart', 'repo_id': 'flutter', 'token_count': 2133}
// 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/artifacts.dart'; import 'package:flutter_tools/src/base/config.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/test/web_test_compiler.dart'; import 'package:test/expect.dart'; import '../../src/context.dart'; void main() { testUsingContext('web test compiler issues valid compile command', () async { final BufferLogger logger = BufferLogger.test(); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); fileSystem.file('project/test/fake_test.dart').createSync(recursive: true); fileSystem.file('build/out').createSync(recursive: true); fileSystem.file('build/build/out.sources').createSync(recursive: true); fileSystem.file('build/build/out.json') ..createSync() ..writeAsStringSync('{}'); fileSystem.file('build/build/out.map').createSync(); fileSystem.file('build/build/out.metadata').createSync(); final FakePlatform platform = FakePlatform( environment: <String, String>{}, ); final Config config = Config( Config.kFlutterSettings, fileSystem: fileSystem, logger: logger, platform: platform, ); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand(command: <Pattern>[ 'Artifact.engineDartBinary.TargetPlatform.web_javascript', '--disable-dart-dev', 'Artifact.frontendServerSnapshotForEngineDartSdk.TargetPlatform.web_javascript', '--sdk-root', 'HostArtifact.flutterWebSdk/', '--incremental', '--target=dartdevc', '--experimental-emit-debug-metadata', '--output-dill', 'build/out', '--packages', '.dart_tool/package_config.json', '-Ddart.vm.profile=false', '-Ddart.vm.product=false', '--enable-asserts', '--filesystem-root', 'project/test', '--filesystem-root', 'build', '--filesystem-scheme', 'org-dartlang-app', '--initialize-from-dill', RegExp(r'^build\/(?:[a-z0-9]{32})\.cache\.dill$'), '--platform', 'file:///HostArtifact.webPlatformKernelFolder/ddc_outline_sound.dill', '--verbosity=error', '--sound-null-safety' ], stdout: 'result abc\nline0\nline1\nabc\nabc build/out 0') ]); final WebTestCompiler compiler = WebTestCompiler( logger: logger, fileSystem: fileSystem, platform: FakePlatform( environment: <String, String>{}, ), artifacts: Artifacts.test(), processManager: processManager, config: config, ); const BuildInfo buildInfo = BuildInfo( BuildMode.debug, '', treeShakeIcons: false, ); await compiler.initialize( projectDirectory: fileSystem.directory('project'), testOutputDir: 'build', testFiles: <String>['project/test/fake_test.dart'], buildInfo: buildInfo, ); expect(processManager.hasRemainingExpectations, isFalse); }); }
flutter/packages/flutter_tools/test/general.shard/test/web_test_compiler_test.dart/0
{'file_path': 'flutter/packages/flutter_tools/test/general.shard/test/web_test_compiler_test.dart', 'repo_id': 'flutter', 'token_count': 1346}
// 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 'package:file/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/web/memory_fs.dart'; import '../../src/common.dart'; void main() { testWithoutContext('correctly parses source, source map, metadata, manifest files', () { final MemoryFileSystem fileSystem = MemoryFileSystem(); final File source = fileSystem.file('source') ..writeAsStringSync('main() {}'); final File sourcemap = fileSystem.file('sourcemap') ..writeAsStringSync('{}'); final File metadata = fileSystem.file('metadata') ..writeAsStringSync('{}'); final File manifest = fileSystem.file('manifest') ..writeAsStringSync(json.encode(<String, Object>{ '/foo.js': <String, Object>{ 'code': <int>[0, source.lengthSync()], 'sourcemap': <int>[0, 2], 'metadata': <int>[0, 2], }, })); final WebMemoryFS webMemoryFS = WebMemoryFS(); webMemoryFS.write(source, manifest, sourcemap, metadata); expect(utf8.decode(webMemoryFS.files['foo.js']!), 'main() {}'); expect(utf8.decode(webMemoryFS.sourcemaps['foo.js.map']!), '{}'); expect(utf8.decode(webMemoryFS.metadataFiles['foo.js.metadata']!), '{}'); expect(webMemoryFS.mergedMetadata, '{}'); }); }
flutter/packages/flutter_tools/test/general.shard/web/memory_fs_test.dart/0
{'file_path': 'flutter/packages/flutter_tools/test/general.shard/web/memory_fs_test.dart', 'repo_id': 'flutter', 'token_count': 543}
// 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/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import '../src/common.dart'; import 'test_utils.dart'; // Test that verbosity it propagated to Gradle tasks correctly. void main() { late Directory tempDir; late String flutterBin; late Directory exampleAppDir; setUp(() async { tempDir = createResolvedTempDirectorySync('flutter_build_test.'); flutterBin = fileSystem.path.join( getFlutterRoot(), 'bin', 'flutter', ); exampleAppDir = tempDir.childDirectory('aaa').childDirectory('example'); processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'create', '--template=plugin', '--platforms=android', 'aaa', ], workingDirectory: tempDir.path); }); tearDown(() async { tryToDelete(tempDir); }); test( 'flutter build apk -v output should contain gen_snapshot command', () async { final ProcessResult result = processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', '--target-platform=android-arm', '-v', ], workingDirectory: exampleAppDir.path); expect( result.stdout, contains(RegExp(r'executing:\s+\S+gen_snapshot\s+'))); }, ); }
flutter/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart/0
{'file_path': 'flutter/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_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 file contains a bunch of different index.html "styles" that can be written // by Flutter Web users. // This should be somewhat kept in sync with the different index.html files present // in `flutter/dev/integration_tests/web/web`. // @see https://github.com/flutter/flutter/tree/master/dev/integration_tests/web/web /// index_with_flutterjs_entrypoint_loaded.html String indexHtmlFlutterJsCallback = _generateFlutterJsIndexHtml(''' window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ onEntrypointLoaded: onEntrypointLoaded, serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, } }); // Once the entrypoint is ready, do things! async function onEntrypointLoaded(engineInitializer) { const appRunner = await engineInitializer.initializeEngine(); appRunner.runApp(); } }); '''); /// index_with_flutterjs_short.html String indexHtmlFlutterJsPromisesShort = _generateFlutterJsIndexHtml(''' window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, } }).then(function(engineInitializer) { return engineInitializer.autoStart(); }); }); '''); /// index_with_flutterjs.html String indexHtmlFlutterJsPromisesFull = _generateFlutterJsIndexHtml(''' window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, } }).then(function(engineInitializer) { return engineInitializer.initializeEngine(); }).then(function(appRunner) { return appRunner.runApp(); }); }); '''); /// index_without_flutterjs.html String indexHtmlNoFlutterJs = ''' <!DOCTYPE HTML> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <title>Web Test</title> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="Web Test"> <link rel="manifest" href="manifest.json"> </head> <body> <!-- This script installs service_worker.js to provide PWA functionality to application. For more information, see: https://developers.google.com/web/fundamentals/primers/service-workers --> <script> var serviceWorkerVersion = null; var scriptLoaded = false; function loadMainDartJs() { if (scriptLoaded) { return; } scriptLoaded = true; var scriptTag = document.createElement('script'); scriptTag.src = 'main.dart.js'; scriptTag.type = 'application/javascript'; document.body.append(scriptTag); } if ('serviceWorker' in navigator) { // Service workers are supported. Use them. window.addEventListener('load', function () { // Wait for registration to finish before dropping the <script> tag. // Otherwise, the browser will load the script multiple times, // potentially different versions. var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion; navigator.serviceWorker.register(serviceWorkerUrl) .then((reg) => { function waitForActivation(serviceWorker) { serviceWorker.addEventListener('statechange', () => { if (serviceWorker.state == 'activated') { console.log('Installed new service worker.'); loadMainDartJs(); } }); } if (!reg.active && (reg.installing || reg.waiting)) { // No active web worker and we have installed or are installing // one for the first time. Simply wait for it to activate. waitForActivation(reg.installing ?? reg.waiting); } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) { // When the app updates the serviceWorkerVersion changes, so we // need to ask the service worker to update. console.log('New service worker available.'); reg.update(); waitForActivation(reg.installing); } else { // Existing service worker is still good. console.log('Loading app from service worker.'); loadMainDartJs(); } }); // If service worker doesn't succeed in a reasonable amount of time, // fallback to plaint <script> tag. setTimeout(() => { if (!scriptLoaded) { console.warn( 'Failed to load app from service worker. Falling back to plain <script> tag.', ); loadMainDartJs(); } }, 4000); }); } else { // Service workers not supported. Just drop the <script> tag. loadMainDartJs(); } </script> </body> </html> '''; // Generates the scaffolding of an index.html file, with a configurable `initScript`. String _generateFlutterJsIndexHtml(String initScript) => ''' <!DOCTYPE HTML> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <title>Integration test. App load with flutter.js and onEntrypointLoaded API</title> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="Web Test"> <link rel="manifest" href="manifest.json"> <script> // The value below is injected by flutter build, do not touch. var serviceWorkerVersion = null; </script> <!-- This script adds the flutter initialization JS code --> <script src="flutter.js" defer></script> </head> <body> <script> $initScript </script> </body> </html> ''';
flutter/packages/flutter_tools/test/web.shard/test_data/hot_reload_index_html_samples.dart/0
{'file_path': 'flutter/packages/flutter_tools/test/web.shard/test_data/hot_reload_index_html_samples.dart', 'repo_id': 'flutter', 'token_count': 2497}
// 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:fuchsia_remote_debug_protocol/src/dart/dart_vm.dart'; import 'package:test/fake.dart'; import 'package:test/test.dart'; import 'package:vm_service/vm_service.dart' as vms; void main() { group('DartVm.connect', () { tearDown(() { restoreVmServiceConnectionFunction(); }); test('disconnect closes peer', () async { final FakeVmService service = FakeVmService(); Future<vms.VmService> fakeServiceFunction( Uri uri, { Duration? timeout, }) { return Future<vms.VmService>(() => service); } fuchsiaVmServiceConnectionFunction = fakeServiceFunction; final DartVm vm = await DartVm.connect(Uri.parse('http://this.whatever/ws')); expect(vm, isNot(null)); await vm.stop(); expect(service.disposed, true); }); }); group('DartVm.getAllFlutterViews', () { late FakeVmService fakeService; setUp(() { fakeService = FakeVmService(); }); tearDown(() { restoreVmServiceConnectionFunction(); }); test('basic flutter view parsing', () async { final Map<String, dynamic> flutterViewCannedResponses = <String, dynamic>{ 'views': <Map<String, dynamic>>[ <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView0', }, <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView1', 'isolate': <String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/1', 'name': 'file://flutterBinary1', 'number': '1', }, }, <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView2', 'isolate': <String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/2', 'name': 'file://flutterBinary2', 'number': '2', }, }, ], }; Future<vms.VmService> fakeVmConnectionFunction( Uri uri, { Duration? timeout, }) { fakeService.flutterListViews = vms.Response.parse(flutterViewCannedResponses); return Future<vms.VmService>(() => fakeService); } fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws')); expect(vm, isNot(null)); final List<FlutterView> views = await vm.getAllFlutterViews(); expect(views.length, 3); // Check ID's as they cannot be null. expect(views[0].id, 'flutterView0'); expect(views[1].id, 'flutterView1'); expect(views[2].id, 'flutterView2'); // Verify names. expect(views[0].name, equals(null)); expect(views[1].name, 'file://flutterBinary1'); expect(views[2].name, 'file://flutterBinary2'); }); test('basic flutter view parsing with casting checks', () async { final Map<String, dynamic> flutterViewCannedResponses = <String, dynamic>{ 'views': <dynamic>[ <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView0', }, <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView1', 'isolate': <String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/1', 'name': 'file://flutterBinary1', 'number': '1', }, }, <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView2', 'isolate': <String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/2', 'name': 'file://flutterBinary2', 'number': '2', }, }, ], }; Future<vms.VmService> fakeVmConnectionFunction( Uri uri, { Duration? timeout, }) { fakeService.flutterListViews = vms.Response.parse(flutterViewCannedResponses); return Future<vms.VmService>(() => fakeService); } fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws')); expect(vm, isNot(null)); final List<FlutterView> views = await vm.getAllFlutterViews(); expect(views.length, 3); // Check ID's as they cannot be null. expect(views[0].id, 'flutterView0'); expect(views[1].id, 'flutterView1'); expect(views[2].id, 'flutterView2'); // Verify names. expect(views[0].name, equals(null)); expect(views[1].name, 'file://flutterBinary1'); expect(views[2].name, 'file://flutterBinary2'); }); test('invalid flutter view missing ID', () async { final Map<String, dynamic> flutterViewCannedResponseMissingId = <String, dynamic>{ 'views': <Map<String, dynamic>>[ // Valid flutter view. <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView1', 'isolate': <String, dynamic>{ 'type': '@Isolate', 'name': 'IsolateThing', 'fixedId': 'true', 'id': 'isolates/1', 'number': '1', }, }, // Missing ID. <String, dynamic>{ 'type': 'FlutterView', }, ], }; Future<vms.VmService> fakeVmConnectionFunction( Uri uri, { Duration? timeout, }) { fakeService.flutterListViews = vms.Response.parse(flutterViewCannedResponseMissingId); return Future<vms.VmService>(() => fakeService); } fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws')); expect(vm, isNot(null)); Future<void> failingFunction() async { await vm.getAllFlutterViews(); } // Both views should be invalid as they were missing required fields. expect(failingFunction, throwsA(isA<RpcFormatError>())); }); test('get isolates by pattern', () async { final List<vms.IsolateRef> isolates = <vms.IsolateRef>[ vms.IsolateRef.parse(<String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/1', 'name': 'file://thingThatWillNotMatch:main()', 'number': '1', })!, vms.IsolateRef.parse(<String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/2', 'name': '0:dart_name_pattern()', 'number': '2', })!, vms.IsolateRef.parse(<String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/3', 'name': 'flutterBinary.cm', 'number': '3', })!, vms.IsolateRef.parse(<String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/4', 'name': '0:some_other_dart_name_pattern()', 'number': '4', })!, ]; Future<vms.VmService> fakeVmConnectionFunction( Uri uri, { Duration? timeout, }) { fakeService.vm = FakeVM(isolates: isolates); return Future<vms.VmService>(() => fakeService); } fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws')); expect(vm, isNot(null)); final List<IsolateRef> matchingFlutterIsolates = await vm.getMainIsolatesByPattern('flutterBinary.cm'); expect(matchingFlutterIsolates.length, 1); final List<IsolateRef> allIsolates = await vm.getMainIsolatesByPattern(''); expect(allIsolates.length, 4); }); test('invalid flutter view missing ID', () async { final Map<String, dynamic> flutterViewCannedResponseMissingIsolateName = <String, dynamic>{ 'views': <Map<String, dynamic>>[ // Missing isolate name. <String, dynamic>{ 'type': 'FlutterView', 'id': 'flutterView1', 'isolate': <String, dynamic>{ 'type': '@Isolate', 'fixedId': 'true', 'id': 'isolates/1', 'number': '1', }, }, ], }; Future<vms.VmService> fakeVmConnectionFunction( Uri uri, { Duration? timeout, }) { fakeService.flutterListViews = vms.Response.parse(flutterViewCannedResponseMissingIsolateName); return Future<vms.VmService>(() => fakeService); } fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; final DartVm vm = await DartVm.connect(Uri.parse('http://whatever.com/ws')); expect(vm, isNot(null)); Future<void> failingFunction() async { await vm.getAllFlutterViews(); } // Both views should be invalid as they were missing required fields. expect(failingFunction, throwsA(isA<RpcFormatError>())); }); }); } class FakeVmService extends Fake implements vms.VmService { bool disposed = false; vms.Response? flutterListViews; vms.VM? vm; @override Future<vms.VM> getVM() async => vm!; @override Future<void> dispose() async { disposed = true; } @override Future<vms.Response> callMethod(String method, {String? isolateId, Map<String, dynamic>? args}) async { if (method == '_flutter.listViews') { return flutterListViews!; } throw UnimplementedError(method); } @override Future<void> onDone = Future<void>.value(); } class FakeVM extends Fake implements vms.VM { FakeVM({ this.isolates = const <vms.IsolateRef>[], }); @override List<vms.IsolateRef>? isolates; }
flutter/packages/fuchsia_remote_debug_protocol/test/src/dart/dart_vm_test.dart/0
{'file_path': 'flutter/packages/fuchsia_remote_debug_protocol/test/src/dart/dart_vm_test.dart', 'repo_id': 'flutter', 'token_count': 4860}
import 'package:calculator_3d/utils/calculator_config.dart'; import 'package:flutter/material.dart'; class RimContainer extends StatelessWidget { const RimContainer({ super.key, required this.size, required this.config, required this.glowOffsetAnimation, this.child, }); final double size; final CalculatorConfig config; final Animation<Offset> glowOffsetAnimation; final Widget? child; @override Widget build(BuildContext context) { return Container( width: size, height: size, decoration: BoxDecoration( borderRadius: BorderRadius.circular( config.borderRadius, ), gradient: LinearGradient( colors: [ config.baseColor.shade300, config.baseColor.shade200, config.baseColor.shade100, config.baseColor.shade50, ], begin: Alignment.bottomLeft, end: Alignment.topRight, stops: const [0.01, 0.49, 0.52, 0.7], ), boxShadow: [ BoxShadow( color: Colors.white.withOpacity(0.8), offset: glowOffsetAnimation.value, blurRadius: 6, blurStyle: BlurStyle.solid, ), ], ), child: child, ); } }
flutter_3d_calculator/lib/widgets/rim_container.dart/0
{'file_path': 'flutter_3d_calculator/lib/widgets/rim_container.dart', 'repo_id': 'flutter_3d_calculator', 'token_count': 586}
import 'package:flutter/material.dart'; import 'package:flutter_airbnb_ui/listing.dart'; class ListingInfo extends StatelessWidget { const ListingInfo( this.listing, { super.key, }); final Listing listing; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( listing.address, style: const TextStyle( fontWeight: FontWeight.w700, fontSize: 16, ), ), Row( children: [ const Icon(Icons.star_rounded, size: 18), Text( listing.rating.toString(), style: const TextStyle(fontSize: 16), ), ], ) ], ), const SizedBox(height: 5), Text( listing.title, style: TextStyle( fontSize: 16, color: Colors.black.withOpacity(0.5), ), ), const SizedBox(height: 5), Text( listing.availability, style: TextStyle( color: Colors.black.withOpacity(0.5), ), ), const SizedBox(height: 5), RichText( text: TextSpan( text: '\$${listing.price}', style: const TextStyle( color: Colors.black, fontWeight: FontWeight.w700, fontSize: 14, ), children: const <TextSpan>[ TextSpan( text: ' night', style: TextStyle( color: Colors.black, fontWeight: FontWeight.normal, ), ), ], ), ), ], ); } }
flutter_airbnb_ui/lib/widgets/listing_info.dart/0
{'file_path': 'flutter_airbnb_ui/lib/widgets/listing_info.dart', 'repo_id': 'flutter_airbnb_ui', 'token_count': 1096}