diff --git a/analysis_options.yaml b/analysis_options.yaml index 58f4974890..b5f618f23b 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -7,17 +7,17 @@ # See the configuration guide for more # https://github.com/dart-lang/sdk/tree/master/pkg/analyzer#configuring-the-analyzer # -# There are four similar analysis options files in the flutter repo: +# There are four similar analysis options files in the flutter repos: # - analysis_options.yaml (this file) # - packages/flutter/lib/analysis_options_user.yaml # - https://github.com/flutter/plugins/blob/master/analysis_options.yaml # - https://github.com/flutter/engine/blob/master/analysis_options.yaml # -# This file contains the analysis options used by Flutter tools, such as -# IntelliJ, Android Studio, and the 'flutter analyze' command. +# This file contains the analysis options used by Flutter tools, such as IntelliJ, +# Android Studio, and the `flutter analyze` command. # -# The flutter/plugins and flutter/engine repos contain a copy of this file, -# which should be kept in sync with this file. +# The flutter/plugins repo contains a copy of this file, which should be kept +# in sync with this file. analyzer: language: @@ -124,7 +124,6 @@ linter: - prefer_final_locals - prefer_foreach # - prefer_function_declarations_over_variables # not yet tested - - prefer_generic_function_type_aliases - prefer_initializing_formals # - prefer_interpolation_to_compose_strings # not yet tested # - prefer_iterable_whereType # https://github.com/dart-lang/sdk/issues/32463 @@ -132,7 +131,6 @@ linter: - prefer_is_not_empty - prefer_single_quotes - prefer_typing_uninitialized_variables - - public_member_api_docs - recursive_getters - slash_for_doc_comments - sort_constructors_first diff --git a/analysis_options_repo.yaml b/analysis_options_repo.yaml new file mode 100644 index 0000000000..427474c335 --- /dev/null +++ b/analysis_options_repo.yaml @@ -0,0 +1,157 @@ +# Specify analysis options. +# +# Until there are meta linter rules, each desired lint must be explicitly enabled. +# See: https://github.com/dart-lang/linter/issues/288 +# +# For a list of lints, see: http://dart-lang.github.io/linter/lints/ +# See the configuration guide for more +# https://github.com/dart-lang/sdk/tree/master/pkg/analyzer#configuring-the-analyzer +# +# There are three similar analysis options files in the flutter repo: +# - analysis_options.yaml +# - analysis_options_repo.yaml (this file) +# - packages/flutter/lib/analysis_options_user.yaml +# +# This file contains the analysis options used by 'flutter analyze' when analyzing +# the flutter repository. It is very similar to analysis_options.yaml; +# the only difference (currently) is the public_member_api_docs option, +# which is turned on and programmatically reduced to a single output line +# indicating the # of violations for that rule. + +analyzer: + language: + enableStrictCallChecks: true + enableSuperMixins: true + strong-mode: + implicit-dynamic: false + errors: + # treat missing required parameters as a warning (not a hint) + missing_required_param: warning + # treat missing returns as a warning (not a hint) + missing_return: warning + # allow having TODOs in the code + todo: ignore + # `flutter analyze` (without `--watch`) just ignores directories + # that contain a .dartignore file, and this file does not have any + # effect on what files are actually analyzed. + +linter: + rules: + # these rules are documented on and in the same order as + # the Dart Lint rules page to make maintenance easier + # https://github.com/dart-lang/linter/blob/master/example/all.yaml + - always_declare_return_types + - always_put_control_body_on_new_line + # - always_put_required_named_parameters_first # we prefer having parameters in the same order as fields https://github.com/flutter/flutter/issues/10219 + - always_require_non_null_named_parameters + - always_specify_types + - annotate_overrides + # - avoid_annotating_with_dynamic # conflicts with always_specify_types + - avoid_as + # - avoid_bool_literals_in_conditional_expressions # not yet tested + # - avoid_catches_without_on_clauses # we do this commonly + # - avoid_catching_errors # we do this commonly + - avoid_classes_with_only_static_members + # - avoid_double_and_int_checks # only useful when targeting JS runtime + - avoid_empty_else + # - avoid_field_initializers_in_const_classes # not yet tested + - avoid_function_literals_in_foreach_calls + - avoid_init_to_null + # - avoid_js_rounded_ints # only useful when targeting JS runtime + - avoid_null_checks_in_equality_operators + # - avoid_positional_boolean_parameters # not yet tested + # - avoid_private_typedef_functions # we prefer having typedef (discussion in https://github.com/flutter/flutter/pull/16356) + - avoid_relative_lib_imports + - avoid_renaming_method_parameters + - avoid_return_types_on_setters + # - avoid_returning_null # we do this commonly + # - avoid_returning_this # https://github.com/dart-lang/linter/issues/842 + # - avoid_setters_without_getters # not yet tested + # - avoid_single_cascade_in_expression_statements # not yet tested + - avoid_slow_async_io + # - avoid_types_as_parameter_names # https://github.com/dart-lang/linter/pull/954/files + # - avoid_types_on_closure_parameters # conflicts with always_specify_types + # - avoid_unused_constructor_parameters # https://github.com/dart-lang/linter/pull/847 + - await_only_futures + - camel_case_types + - cancel_subscriptions + # - cascade_invocations # not yet tested + # - close_sinks # https://github.com/flutter/flutter/issues/5789 + # - comment_references # blocked on https://github.com/dart-lang/dartdoc/issues/1153 + # - constant_identifier_names # https://github.com/dart-lang/linter/issues/204 + - control_flow_in_finally + - directives_ordering + - empty_catches + - empty_constructor_bodies + - empty_statements + - hash_and_equals + - implementation_imports + # - invariant_booleans # https://github.com/flutter/flutter/issues/5790 + - iterable_contains_unrelated_type + # - join_return_with_assignment # not yet tested + - library_names + - library_prefixes + - list_remove_unrelated_type + # - literal_only_boolean_expressions # https://github.com/flutter/flutter/issues/5791 + - no_adjacent_strings_in_list + - no_duplicate_case_values + - non_constant_identifier_names + # - omit_local_variable_types # opposite of always_specify_types + # - one_member_abstracts # too many false positives + # - only_throw_errors # https://github.com/flutter/flutter/issues/5792 + - overridden_fields + - package_api_docs + - package_names + - package_prefixed_library_names + # - parameter_assignments # we do this commonly + - prefer_adjacent_string_concatenation + - prefer_asserts_in_initializer_lists + - prefer_bool_in_asserts + - prefer_collection_literals + - prefer_conditional_assignment + - prefer_const_constructors + - prefer_const_constructors_in_immutables + - prefer_const_declarations + - prefer_const_literals_to_create_immutables + # - prefer_constructors_over_static_methods # not yet tested + - prefer_contains + - prefer_equal_for_default_values + # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods + - prefer_final_fields + - prefer_final_locals + - prefer_foreach + # - prefer_function_declarations_over_variables # not yet tested + - prefer_initializing_formals + # - prefer_interpolation_to_compose_strings # not yet tested + # - prefer_iterable_whereType # https://github.com/dart-lang/sdk/issues/32463 + - prefer_is_empty + - prefer_is_not_empty + - prefer_single_quotes + - prefer_typing_uninitialized_variables + - public_member_api_docs # this is the only difference from analysis_options.yaml + - recursive_getters + - slash_for_doc_comments + - sort_constructors_first + - sort_unnamed_constructors_first + - super_goes_last + - test_types_in_equals + - throw_in_finally + # - type_annotate_public_apis # subset of always_specify_types + - type_init_formals + # - unawaited_futures # https://github.com/flutter/flutter/issues/5793 + - unnecessary_brace_in_string_interps + - unnecessary_getters_setters + # - unnecessary_lambdas # https://github.com/dart-lang/linter/issues/498 + - unnecessary_null_aware_assignments + - unnecessary_null_in_if_null_operators + - unnecessary_overrides + - unnecessary_parenthesis + # - unnecessary_statements # not yet tested + - unnecessary_this + - unrelated_type_equality_checks + - use_rethrow_when_possible + # - use_setters_to_change_properties # not yet tested + # - use_string_buffers # https://github.com/dart-lang/linter/pull/664 + # - use_to_and_as_if_applicable # has false positives, so we prefer to catch this by code-review + - valid_regexps + # - void_checks # not yet tested diff --git a/dev/bots/prepare_package.dart b/dev/bots/prepare_package.dart index 28160f6520..756466e74d 100644 --- a/dev/bots/prepare_package.dart +++ b/dev/bots/prepare_package.dart @@ -175,7 +175,7 @@ class ProcessRunner { } } -typedef HttpReader = Future Function(Uri url, {Map headers}); +typedef Future HttpReader(Uri url, {Map headers}); /// Creates a pre-populated Flutter archive from a git repo. class ArchiveCreator { diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 7bbd5718a5..375df5565c 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -8,7 +8,7 @@ import 'dart:io'; import 'package:path/path.dart' as path; -typedef ShardRunner = Future Function(); +typedef Future ShardRunner(); final String flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))); final String flutter = path.join(flutterRoot, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter'); @@ -71,8 +71,12 @@ Future _generateDocs() async { } Future _verifyInternationalizations() async { - final EvalResult genResult = await _evalCommand(dart, - [ '--preview-dart-2', path.join('dev', 'tools', 'gen_localizations.dart'), ], + final EvalResult genResult = await _evalCommand( + dart, + [ + '--preview-dart-2', + path.join('dev', 'tools', 'gen_localizations.dart'), + ], workingDirectory: flutterRoot, ); diff --git a/dev/bots/test/fake_process_manager.dart b/dev/bots/test/fake_process_manager.dart index e94f07ccce..54471d9124 100644 --- a/dev/bots/test/fake_process_manager.dart +++ b/dev/bots/test/fake_process_manager.dart @@ -150,7 +150,7 @@ class FakeProcess extends Mock implements Process { } /// Callback used to receive stdin input when it occurs. -typedef StringReceivedCallback = void Function(String received); +typedef void StringReceivedCallback(String received); /// A stream consumer class that consumes UTF8 strings as lists of ints. class StringStreamConsumer implements StreamConsumer> { diff --git a/dev/devicelab/bin/tasks/gradle_plugin_test.dart b/dev/devicelab/bin/tasks/gradle_plugin_test.dart index 26830f880e..bbeb70f233 100644 --- a/dev/devicelab/bin/tasks/gradle_plugin_test.dart +++ b/dev/devicelab/bin/tasks/gradle_plugin_test.dart @@ -32,6 +32,14 @@ void main() async { return new TaskResult.failure(errorMessage); } + section('gradlew assembleDebug no-preview-dart-2'); + await project.runGradleTask('assembleDebug', options: ['-Ppreview-dart-2=false']); + errorMessage = _validateSnapshotDependency(project, + '${project.rootPath}/build/app/intermediates/flutter/debug/snapshot_blob.bin'); + if (errorMessage != null) { + return new TaskResult.failure(errorMessage); + } + section('gradlew assembleProfile'); await project.runGradleTask('assembleProfile'); diff --git a/dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark_dart1.dart b/dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark_dart1.dart new file mode 100644 index 0000000000..4d9767565b --- /dev/null +++ b/dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark_dart1.dart @@ -0,0 +1,12 @@ +// Copyright (c) 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 'package:flutter_devicelab/tasks/hot_mode_tests.dart'; +import 'package:flutter_devicelab/framework/framework.dart'; + +Future main() async { + await task(createHotModeTest(isPreviewDart2: false)); +} diff --git a/dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios__benchmark_dart1.dart b/dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios__benchmark_dart1.dart new file mode 100644 index 0000000000..99c70d710e --- /dev/null +++ b/dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios__benchmark_dart1.dart @@ -0,0 +1,14 @@ +// Copyright (c) 2018 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 'package:flutter_devicelab/tasks/hot_mode_tests.dart'; +import 'package:flutter_devicelab/framework/framework.dart'; +import 'package:flutter_devicelab/framework/adb.dart'; + +Future main() async { + deviceOperatingSystem = DeviceOperatingSystem.ios; + await task(createHotModeTest(isPreviewDart2: false)); +} diff --git a/dev/devicelab/lib/framework/framework.dart b/dev/devicelab/lib/framework/framework.dart index f8335016b1..9eca2d9aec 100644 --- a/dev/devicelab/lib/framework/framework.dart +++ b/dev/devicelab/lib/framework/framework.dart @@ -20,7 +20,7 @@ const Duration _kDefaultTaskTimeout = const Duration(minutes: 15); /// Represents a unit of work performed in the CI environment that can /// succeed, fail and be retried independently of others. -typedef TaskFunction = Future Function(); +typedef Future TaskFunction(); bool _isTaskRegistered = false; diff --git a/dev/devicelab/lib/tasks/analysis.dart b/dev/devicelab/lib/tasks/analysis.dart index 768fcb74c4..fb681394a2 100644 --- a/dev/devicelab/lib/tasks/analysis.dart +++ b/dev/devicelab/lib/tasks/analysis.dart @@ -15,7 +15,7 @@ const int _kRunsPerBenchmark = 3; /// Runs a benchmark once and reports the result as a lower-is-better numeric /// value. -typedef _Benchmark = Future Function(); +typedef Future _Benchmark(); /// Path to the generated "mega gallery" app. Directory get _megaGalleryDirectory => dir(path.join(Directory.systemTemp.path, 'mega_gallery')); diff --git a/dev/devicelab/lib/tasks/hot_mode_tests.dart b/dev/devicelab/lib/tasks/hot_mode_tests.dart index 9913c2ba51..a710e80e41 100644 --- a/dev/devicelab/lib/tasks/hot_mode_tests.dart +++ b/dev/devicelab/lib/tasks/hot_mode_tests.dart @@ -16,7 +16,7 @@ import '../framework/utils.dart'; final Directory _editedFlutterGalleryDir = dir(path.join(Directory.systemTemp.path, 'edited_flutter_gallery')); final Directory flutterGalleryDir = dir(path.join(flutterDirectory.path, 'examples/flutter_gallery')); -TaskFunction createHotModeTest() { +TaskFunction createHotModeTest({ bool isPreviewDart2 = true }) { return () async { final Device device = await devices.workingDevice; await device.unlock(); @@ -25,6 +25,10 @@ TaskFunction createHotModeTest() { final List options = [ '--hot', '-d', device.deviceId, '--benchmark', '--verbose', '--resident' ]; + if (isPreviewDart2) + options.add('--preview-dart-2'); + else + options.add('--no-preview-dart-2'); setLocalEngineOptionIfNecessary(options); int hotReloadCount = 0; Map twoReloadsData; @@ -88,8 +92,8 @@ TaskFunction createHotModeTest() { } benchmarkFile.deleteSync(); - // start `flutter run` again to make sure it loads from the previous - // state; frontend loads up from previously generated kernel files. + // start `flutter run` again to make sure it loads from the previous state + // (in case of --preview-dart-2 frontend loads up from previously generated kernel files). { final Process process = await startProcess( path.join(flutterDirectory.path, 'bin', 'flutter'), diff --git a/dev/devicelab/lib/tasks/microbenchmarks.dart b/dev/devicelab/lib/tasks/microbenchmarks.dart index 15764c09ce..1d2a67a712 100644 --- a/dev/devicelab/lib/tasks/microbenchmarks.dart +++ b/dev/devicelab/lib/tasks/microbenchmarks.dart @@ -23,7 +23,7 @@ TaskFunction createMicrobenchmarkTask() { final Device device = await devices.workingDevice; await device.unlock(); - Future> _runMicrobench(String benchmarkPath) async { + Future> _runMicrobench(String benchmarkPath, {bool previewDart2 = true}) async { Future> _run() async { print('Running $benchmarkPath'); final Directory appDir = dir( @@ -38,6 +38,10 @@ TaskFunction createMicrobenchmarkTask() { '-d', device.deviceId, ]; + if (previewDart2) + options.add('--preview-dart-2'); + else + options.add('--no-preview-dart-2'); setLocalEngineOptionIfNecessary(options); options.add(benchmarkPath); return await _startFlutter( @@ -57,6 +61,26 @@ TaskFunction createMicrobenchmarkTask() { allResults.addAll(await _runMicrobench('lib/gestures/velocity_tracker_bench.dart')); allResults.addAll(await _runMicrobench('lib/stocks/animation_bench.dart')); + // Run micro-benchmarks once again in --no-preview-dart-2 mode. + // Append "_dart1" suffix to the result keys to distinguish them from + // the original results. + + void addDart1Results(Map benchmarkResults) { + benchmarkResults.forEach((String key, double result) { + allResults[key + '_dart1'] = result; + }); + } + + addDart1Results(await _runMicrobench( + 'lib/stocks/layout_bench.dart', previewDart2: false)); + addDart1Results(await _runMicrobench( + 'lib/stocks/layout_bench.dart', previewDart2: false)); + addDart1Results(await _runMicrobench( + 'lib/stocks/build_bench.dart', previewDart2: false)); + addDart1Results(await _runMicrobench( + 'lib/gestures/velocity_tracker_bench.dart', previewDart2: false)); + addDart1Results(await _runMicrobench( + 'lib/stocks/animation_bench.dart', previewDart2: false)); return new TaskResult.success(allResults, benchmarkScoreKeys: allResults.keys.toList()); }; } diff --git a/dev/devicelab/lib/tasks/perf_tests.dart b/dev/devicelab/lib/tasks/perf_tests.dart index 3cb76dd346..34748de0ac 100644 --- a/dev/devicelab/lib/tasks/perf_tests.dart +++ b/dev/devicelab/lib/tasks/perf_tests.dart @@ -205,13 +205,23 @@ class CompileTest { final Map metrics = {} ..addAll(await _compileAot()) ..addAll(await _compileApp()) - ..addAll(await _compileDebug()); + ..addAll(await _compileDebug()) + ..addAll(_suffix(await _compileAot(previewDart2: false), '__dart1')) + ..addAll(_suffix(await _compileApp(previewDart2: false), '__dart1')) + ..addAll(_suffix(await _compileDebug(previewDart2: false), '__dart1')); return new TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList()); }); } - static Future> _compileAot() async { + static Map _suffix(Map map, String suffix) { + return new Map.fromIterables( + map.keys.map((String key) => '$key$suffix'), + map.values, + ); + } + + static Future> _compileAot({ bool previewDart2 = true }) async { // Generate blobs instead of assembly. await flutter('clean'); final Stopwatch watch = new Stopwatch()..start(); @@ -230,6 +240,10 @@ class CompileTest { options.add('android-arm'); break; } + if (previewDart2) + options.add('--preview-dart-2'); + else + options.add('--no-preview-dart-2'); setLocalEngineOptionIfNecessary(options); final String compileLog = await evalFlutter('build', options: options); watch.stop(); @@ -244,11 +258,15 @@ class CompileTest { return metrics; } - static Future> _compileApp() async { + static Future> _compileApp({ bool previewDart2 = true }) async { await flutter('clean'); final Stopwatch watch = new Stopwatch(); int releaseSizeInBytes; final List options = ['--release']; + if (previewDart2) + options.add('--preview-dart-2'); + else + options.add('--no-preview-dart-2'); setLocalEngineOptionIfNecessary(options); switch (deviceOperatingSystem) { case DeviceOperatingSystem.ios: @@ -281,10 +299,14 @@ class CompileTest { }; } - static Future> _compileDebug() async { + static Future> _compileDebug({ bool previewDart2 = true }) async { await flutter('clean'); final Stopwatch watch = new Stopwatch(); final List options = ['--debug']; + if (previewDart2) + options.add('--preview-dart-2'); + else + options.add('--no-preview-dart-2'); setLocalEngineOptionIfNecessary(options); switch (deviceOperatingSystem) { case DeviceOperatingSystem.ios: diff --git a/dev/devicelab/manifest.yaml b/dev/devicelab/manifest.yaml index cee29b27bd..b7f18f3974 100644 --- a/dev/devicelab/manifest.yaml +++ b/dev/devicelab/manifest.yaml @@ -154,6 +154,21 @@ tasks: stage: devicelab required_agent_capabilities: ["mac/android"] + hot_mode_dev_cycle__benchmark_dart1: + description: > + Measures the performance of Dart VM hot patching feature under + --no-preview-dart-2 option, that disables Dart 2.0 frontend. + stage: devicelab + required_agent_capabilities: ["mac/android"] + + hot_mode_dev_cycle_ios__benchmark_dart1: + description: > + Measures the performance of Dart VM hot patching feature under + --no-preview-dart-2 option, that disables Dart 2.0 frontend. + stage: devicelab_ios + required_agent_capabilities: ["mac/ios"] + flaky: true + complex_layout_scroll_perf__memory: description: > Measures memory usage of the scroll performance test. diff --git a/dev/devicelab/test/adb_test.dart b/dev/devicelab/test/adb_test.dart index e43d397dfd..6cc8dc8b3f 100644 --- a/dev/devicelab/test/adb_test.dart +++ b/dev/devicelab/test/adb_test.dart @@ -112,7 +112,7 @@ CommandArgs cmd({ ); } -typedef ExitErrorFactory = dynamic Function(); +typedef dynamic ExitErrorFactory(); class CommandArgs { CommandArgs({ this.command, this.arguments, this.environment }); diff --git a/dev/integration_tests/channels/lib/src/test_step.dart b/dev/integration_tests/channels/lib/src/test_step.dart index ce5157268e..037da9aa59 100644 --- a/dev/integration_tests/channels/lib/src/test_step.dart +++ b/dev/integration_tests/channels/lib/src/test_step.dart @@ -11,7 +11,7 @@ import 'pair.dart'; enum TestStatus { ok, pending, failed, complete } -typedef TestStep = Future Function(); +typedef Future TestStep(); const String nothing = '-'; diff --git a/dev/integration_tests/platform_interaction/lib/src/test_step.dart b/dev/integration_tests/platform_interaction/lib/src/test_step.dart index 4e40fc8305..3ed5523c3c 100644 --- a/dev/integration_tests/platform_interaction/lib/src/test_step.dart +++ b/dev/integration_tests/platform_interaction/lib/src/test_step.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; enum TestStatus { ok, pending, failed, complete } -typedef TestStep = Future Function(); +typedef Future TestStep(); const String nothing = '-'; diff --git a/dev/manual_tests/lib/material_arc.dart b/dev/manual_tests/lib/material_arc.dart index 43f05325d9..d8aa5026f1 100644 --- a/dev/manual_tests/lib/material_arc.dart +++ b/dev/manual_tests/lib/material_arc.dart @@ -396,7 +396,7 @@ class _RectangleDemoState extends State<_RectangleDemo> { } } -typedef _DemoBuilder = Widget Function(_ArcDemo demo); +typedef Widget _DemoBuilder(_ArcDemo demo); class _ArcDemo { _ArcDemo(this.title, this.builder, TickerProvider vsync) diff --git a/dev/manual_tests/lib/overlay_geometry.dart b/dev/manual_tests/lib/overlay_geometry.dart index 231cb2e107..8ec50e121b 100644 --- a/dev/manual_tests/lib/overlay_geometry.dart +++ b/dev/manual_tests/lib/overlay_geometry.dart @@ -92,7 +92,7 @@ class OverlayGeometryApp extends StatefulWidget { OverlayGeometryAppState createState() => new OverlayGeometryAppState(); } -typedef CardTapCallback = void Function(GlobalKey targetKey, Offset globalPosition); +typedef void CardTapCallback(GlobalKey targetKey, Offset globalPosition); class CardBuilder extends SliverChildDelegate { CardBuilder({ this.cardModels, this.onTapUp }); diff --git a/examples/flutter_gallery/lib/demo/material/expansion_panels_demo.dart b/examples/flutter_gallery/lib/demo/material/expansion_panels_demo.dart index d8dcbb2bec..68c7258515 100644 --- a/examples/flutter_gallery/lib/demo/material/expansion_panels_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/expansion_panels_demo.dart @@ -10,8 +10,8 @@ enum _Location { Bermuda } -typedef DemoItemBodyBuilder = Widget Function(DemoItem item); -typedef ValueToString = String Function(T value); +typedef Widget DemoItemBodyBuilder(DemoItem item); +typedef String ValueToString(T value); class DualHeaderWithHint extends StatelessWidget { const DualHeaderWithHint({ diff --git a/examples/flutter_gallery/lib/demo/material/grid_list_demo.dart b/examples/flutter_gallery/lib/demo/material/grid_list_demo.dart index 3ce74d447f..89e60e7293 100644 --- a/examples/flutter_gallery/lib/demo/material/grid_list_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/grid_list_demo.dart @@ -10,7 +10,7 @@ enum GridDemoTileStyle { twoLine } -typedef BannerTapCallback = void Function(Photo photo); +typedef void BannerTapCallback(Photo photo); const double _kMinFlingVelocity = 800.0; const String _kGalleryAssetsPackage = 'flutter_gallery_assets'; diff --git a/examples/flutter_gallery/lib/gallery/updater.dart b/examples/flutter_gallery/lib/gallery/updater.dart index 28172b7c2c..7356038ed9 100644 --- a/examples/flutter_gallery/lib/gallery/updater.dart +++ b/examples/flutter_gallery/lib/gallery/updater.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; -typedef UpdateUrlFetcher = Future Function(); +typedef Future UpdateUrlFetcher(); class Updater extends StatefulWidget { const Updater({ @required this.updateUrlFetcher, this.child, Key key }) diff --git a/examples/layers/services/isolate.dart b/examples/layers/services/isolate.dart index c1d9f2ef49..2efae63a14 100644 --- a/examples/layers/services/isolate.dart +++ b/examples/layers/services/isolate.dart @@ -9,8 +9,8 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -typedef OnProgressListener = void Function(double completed, double total); -typedef OnResultListener = void Function(String result); +typedef void OnProgressListener(double completed, double total); +typedef void OnResultListener(String result); // An encapsulation of a large amount of synchronous processing. // diff --git a/examples/layers/widgets/styled_text.dart b/examples/layers/widgets/styled_text.dart index 6db42cb9f0..bcb002c584 100644 --- a/examples/layers/widgets/styled_text.dart +++ b/examples/layers/widgets/styled_text.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; -typedef _TextTransformer = Widget Function(String name, String text); +typedef Widget _TextTransformer(String name, String text); // From https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film) const String _kDialogText = ''' diff --git a/examples/stocks/lib/i18n/stock_messages_all.dart b/examples/stocks/lib/i18n/stock_messages_all.dart index 8e26e85429..77ebdf91e5 100644 --- a/examples/stocks/lib/i18n/stock_messages_all.dart +++ b/examples/stocks/lib/i18n/stock_messages_all.dart @@ -12,7 +12,7 @@ import 'package:intl/src/intl_helpers.dart'; import 'stock_messages_en.dart' as messages_en; import 'stock_messages_es.dart' as messages_es; -typedef LibraryLoader = Future Function(); +typedef Future LibraryLoader(); Map _deferredLibraries = { 'en': () => new Future.value(null), 'es': () => new Future.value(null), diff --git a/examples/stocks/lib/i18n/stock_messages_en.dart b/examples/stocks/lib/i18n/stock_messages_en.dart index 4945ea97ac..04eb511a6a 100644 --- a/examples/stocks/lib/i18n/stock_messages_en.dart +++ b/examples/stocks/lib/i18n/stock_messages_en.dart @@ -12,7 +12,7 @@ final messages = new MessageLookup(); final _keepAnalysisHappy = Intl.defaultLocale; // ignore: non_constant_identifier_names -typedef MessageIfAbsent = dynamic Function(String message_str, List args); +typedef MessageIfAbsent(String message_str, List args); class MessageLookup extends MessageLookupByLibrary { get localeName => 'en'; diff --git a/examples/stocks/lib/stock_home.dart b/examples/stocks/lib/stock_home.dart index eb3a87cae0..b50b951f21 100644 --- a/examples/stocks/lib/stock_home.dart +++ b/examples/stocks/lib/stock_home.dart @@ -11,7 +11,7 @@ import 'stock_strings.dart'; import 'stock_symbol_viewer.dart'; import 'stock_types.dart'; -typedef ModeUpdater = void Function(StockMode mode); +typedef void ModeUpdater(StockMode mode); enum _StockMenuItem { autorefresh, refresh, speedUp, speedDown } enum StockHomeTab { market, portfolio } diff --git a/examples/stocks/lib/stock_row.dart b/examples/stocks/lib/stock_row.dart index 6e519be4bd..f22c5be4ae 100644 --- a/examples/stocks/lib/stock_row.dart +++ b/examples/stocks/lib/stock_row.dart @@ -7,7 +7,7 @@ import 'package:flutter/material.dart'; import 'stock_arrow.dart'; import 'stock_data.dart'; -typedef StockRowActionCallback = void Function(Stock stock); +typedef void StockRowActionCallback(Stock stock); class StockRow extends StatelessWidget { StockRow({ diff --git a/packages/flutter/lib/src/animation/animation.dart b/packages/flutter/lib/src/animation/animation.dart index be2c9f6d63..346657356b 100644 --- a/packages/flutter/lib/src/animation/animation.dart +++ b/packages/flutter/lib/src/animation/animation.dart @@ -22,7 +22,7 @@ enum AnimationStatus { } /// Signature for listeners attached using [Animation.addStatusListener]. -typedef AnimationStatusListener = void Function(AnimationStatus status); +typedef void AnimationStatusListener(AnimationStatus status); /// An animation with a value of type `T`. /// diff --git a/packages/flutter/lib/src/cupertino/refresh.dart b/packages/flutter/lib/src/cupertino/refresh.dart index 4f28e484af..95298924de 100644 --- a/packages/flutter/lib/src/cupertino/refresh.dart +++ b/packages/flutter/lib/src/cupertino/refresh.dart @@ -204,7 +204,7 @@ enum RefreshIndicatorMode { /// /// The `pulledExtent` parameter is the currently available space either from /// overscrolling or as held by the sliver during refresh. -typedef RefreshControlIndicatorBuilder = Widget Function( +typedef Widget RefreshControlIndicatorBuilder( BuildContext context, RefreshIndicatorMode refreshState, double pulledExtent, @@ -216,7 +216,7 @@ typedef RefreshControlIndicatorBuilder = Widget Function( /// pulled a `refreshTriggerPullDistance`. Must return a [Future]. Upon /// completion of the [Future], the [CupertinoRefreshControl] enters the /// [RefreshIndicatorMode.done] state and will start to go away. -typedef RefreshCallback = Future Function(); +typedef Future RefreshCallback(); /// A sliver widget implementing the iOS-style pull to refresh content control. /// diff --git a/packages/flutter/lib/src/foundation/assertions.dart b/packages/flutter/lib/src/foundation/assertions.dart index 773bfb66d7..51297a5e5e 100644 --- a/packages/flutter/lib/src/foundation/assertions.dart +++ b/packages/flutter/lib/src/foundation/assertions.dart @@ -6,11 +6,11 @@ import 'basic_types.dart'; import 'print.dart'; /// Signature for [FlutterError.onError] handler. -typedef FlutterExceptionHandler = void Function(FlutterErrorDetails details); +typedef void FlutterExceptionHandler(FlutterErrorDetails details); /// Signature for [FlutterErrorDetails.informationCollector] callback /// and other callbacks that collect information into a string buffer. -typedef InformationCollector = void Function(StringBuffer information); +typedef void InformationCollector(StringBuffer information); /// Class for information provided to [FlutterExceptionHandler] callbacks. /// diff --git a/packages/flutter/lib/src/foundation/basic_types.dart b/packages/flutter/lib/src/foundation/basic_types.dart index 95df91ae18..990586dfef 100644 --- a/packages/flutter/lib/src/foundation/basic_types.dart +++ b/packages/flutter/lib/src/foundation/basic_types.dart @@ -12,7 +12,7 @@ export 'dart:ui' show VoidCallback; /// Signature for callbacks that report that an underlying value has changed. /// /// See also [ValueSetter]. -typedef ValueChanged = void Function(T value); +typedef void ValueChanged(T value); /// Signature for callbacks that report that a value has been set. /// @@ -26,7 +26,7 @@ typedef ValueChanged = void Function(T value); /// /// * [ValueGetter], the getter equivalent of this signature. /// * [AsyncValueSetter], an asynchronous version of this signature. -typedef ValueSetter = void Function(T value); +typedef void ValueSetter(T value); /// Signature for callbacks that are to report a value on demand. /// @@ -34,10 +34,10 @@ typedef ValueSetter = void Function(T value); /// /// * [ValueSetter], the setter equivalent of this signature. /// * [AsyncValueGetter], an asynchronous version of this signature. -typedef ValueGetter = T Function(); +typedef T ValueGetter(); /// Signature for callbacks that filter an iterable. -typedef IterableFilter = Iterable Function(Iterable input); +typedef Iterable IterableFilter(Iterable input); /// Signature of callbacks that have no arguments and return no data, but that /// return a [Future] to indicate when their work is complete. @@ -47,7 +47,7 @@ typedef IterableFilter = Iterable Function(Iterable input); /// * [VoidCallback], a synchronous version of this signature. /// * [AsyncValueGetter], a signature for asynchronous getters. /// * [AsyncValueSetter], a signature for asynchronous setters. -typedef AsyncCallback = Future Function(); +typedef Future AsyncCallback(); /// Signature for callbacks that report that a value has been set and return a /// [Future] that completes when the value has been saved. @@ -56,7 +56,7 @@ typedef AsyncCallback = Future Function(); /// /// * [ValueSetter], a synchronous version of this signature. /// * [AsyncValueGetter], the getter equivalent of this signature. -typedef AsyncValueSetter = Future Function(T value); +typedef Future AsyncValueSetter(T value); /// Signature for callbacks that are to asynchronously report a value on demand. /// @@ -64,7 +64,7 @@ typedef AsyncValueSetter = Future Function(T value); /// /// * [ValueGetter], a synchronous version of this signature. /// * [AsyncValueSetter], the setter equivalent of this signature. -typedef AsyncValueGetter = Future Function(); +typedef Future AsyncValueGetter(); // BITFIELD diff --git a/packages/flutter/lib/src/foundation/binding.dart b/packages/flutter/lib/src/foundation/binding.dart index 88cf69df1f..e9bbb58e0c 100644 --- a/packages/flutter/lib/src/foundation/binding.dart +++ b/packages/flutter/lib/src/foundation/binding.dart @@ -22,7 +22,7 @@ import 'print.dart'; /// "type" key will be set to the string `_extensionType` to indicate /// that this is a return value from a service extension, and the /// "method" key will be set to the full name of the method. -typedef ServiceExtensionCallback = Future> Function(Map parameters); +typedef Future> ServiceExtensionCallback(Map parameters); /// Base class for mixins that provide singleton services (also known as /// "bindings"). diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index 45d846a5a1..d929c799e8 100644 --- a/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/packages/flutter/lib/src/foundation/diagnostics.dart @@ -1661,7 +1661,7 @@ class ObjectFlagProperty extends DiagnosticsProperty { /// May throw exception if accessing the property would throw an exception /// and callers must handle that case gracefully. For example, accessing a /// property may trigger an assert that layout constraints were violated. -typedef ComputePropertyValueCallback = T Function(); +typedef T ComputePropertyValueCallback(); /// Property with a [value] of type [T]. /// diff --git a/packages/flutter/lib/src/foundation/isolates.dart b/packages/flutter/lib/src/foundation/isolates.dart index 10864f3d4f..a7c988b61c 100644 --- a/packages/flutter/lib/src/foundation/isolates.dart +++ b/packages/flutter/lib/src/foundation/isolates.dart @@ -18,7 +18,7 @@ import 'profile.dart'; /// of classes, not closures or instance methods of objects. /// /// {@macro flutter.foundation.compute.limitations} -typedef ComputeCallback = R Function(Q message); +typedef R ComputeCallback(Q message); /// Spawn an isolate, run `callback` on that isolate, passing it `message`, and /// (eventually) return the value returned by `callback`. diff --git a/packages/flutter/lib/src/foundation/licenses.dart b/packages/flutter/lib/src/foundation/licenses.dart index 50f62d5187..cbacdf48b6 100644 --- a/packages/flutter/lib/src/foundation/licenses.dart +++ b/packages/flutter/lib/src/foundation/licenses.dart @@ -5,7 +5,7 @@ import 'dart:async'; /// Signature for callbacks passed to [LicenseRegistry.addLicense]. -typedef LicenseEntryCollector = Stream Function(); +typedef Stream LicenseEntryCollector(); /// A string that represents one paragraph in a [LicenseEntry]. /// diff --git a/packages/flutter/lib/src/foundation/print.dart b/packages/flutter/lib/src/foundation/print.dart index d8f7ddb8a3..5057aaef51 100644 --- a/packages/flutter/lib/src/foundation/print.dart +++ b/packages/flutter/lib/src/foundation/print.dart @@ -6,7 +6,7 @@ import 'dart:async'; import 'dart:collection'; /// Signature for [debugPrint] implementations. -typedef DebugPrintCallback = void Function(String message, { int wrapWidth }); +typedef void DebugPrintCallback(String message, { int wrapWidth }); /// Prints a message to the console, which you can access using the "flutter" /// tool's "logs" command ("flutter logs"). diff --git a/packages/flutter/lib/src/gestures/drag_details.dart b/packages/flutter/lib/src/gestures/drag_details.dart index eebf316f42..0a623da80f 100644 --- a/packages/flutter/lib/src/gestures/drag_details.dart +++ b/packages/flutter/lib/src/gestures/drag_details.dart @@ -38,7 +38,7 @@ class DragDownDetails { /// The `details` object provides the position of the touch. /// /// See [DragGestureRecognizer.onDown]. -typedef GestureDragDownCallback = void Function(DragDownDetails details); +typedef void GestureDragDownCallback(DragDownDetails details); /// Details object for callbacks that use [GestureDragStartCallback]. /// @@ -80,7 +80,7 @@ class DragStartDetails { /// touched the surface. /// /// See [DragGestureRecognizer.onStart]. -typedef GestureDragStartCallback = void Function(DragStartDetails details); +typedef void GestureDragStartCallback(DragStartDetails details); /// Details object for callbacks that use [GestureDragUpdateCallback]. /// @@ -150,7 +150,7 @@ class DragUpdateDetails { /// has travelled since the last update. /// /// See [DragGestureRecognizer.onUpdate]. -typedef GestureDragUpdateCallback = void Function(DragUpdateDetails details); +typedef void GestureDragUpdateCallback(DragUpdateDetails details); /// Details object for callbacks that use [GestureDragEndCallback]. /// diff --git a/packages/flutter/lib/src/gestures/long_press.dart b/packages/flutter/lib/src/gestures/long_press.dart index 20c47643b2..b0ad86f40b 100644 --- a/packages/flutter/lib/src/gestures/long_press.dart +++ b/packages/flutter/lib/src/gestures/long_press.dart @@ -9,7 +9,7 @@ import 'recognizer.dart'; /// Signature for when a pointer has remained in contact with the screen at the /// same location for a long period of time. -typedef GestureLongPressCallback = void Function(); +typedef void GestureLongPressCallback(); /// Recognizes when the user has pressed down at the same location for a long /// period of time. diff --git a/packages/flutter/lib/src/gestures/monodrag.dart b/packages/flutter/lib/src/gestures/monodrag.dart index 2bb11539eb..88fc5d7943 100644 --- a/packages/flutter/lib/src/gestures/monodrag.dart +++ b/packages/flutter/lib/src/gestures/monodrag.dart @@ -22,13 +22,13 @@ enum _DragState { /// the screen is available in the `details`. /// /// See [DragGestureRecognizer.onEnd]. -typedef GestureDragEndCallback = void Function(DragEndDetails details); +typedef void GestureDragEndCallback(DragEndDetails details); /// Signature for when the pointer that previously triggered a /// [GestureDragDownCallback] did not complete. /// /// See [DragGestureRecognizer.onCancel]. -typedef GestureDragCancelCallback = void Function(); +typedef void GestureDragCancelCallback(); /// Recognizes movement. /// diff --git a/packages/flutter/lib/src/gestures/multidrag.dart b/packages/flutter/lib/src/gestures/multidrag.dart index 983d55abb4..5998e236f0 100644 --- a/packages/flutter/lib/src/gestures/multidrag.dart +++ b/packages/flutter/lib/src/gestures/multidrag.dart @@ -17,7 +17,7 @@ import 'recognizer.dart'; import 'velocity_tracker.dart'; /// Signature for when [MultiDragGestureRecognizer] recognizes the start of a drag gesture. -typedef GestureMultiDragStartCallback = Drag Function(Offset position); +typedef Drag GestureMultiDragStartCallback(Offset position); /// Per-pointer state for a [MultiDragGestureRecognizer]. /// diff --git a/packages/flutter/lib/src/gestures/multitap.dart b/packages/flutter/lib/src/gestures/multitap.dart index d26230bfa6..35f4a3dae7 100644 --- a/packages/flutter/lib/src/gestures/multitap.dart +++ b/packages/flutter/lib/src/gestures/multitap.dart @@ -15,22 +15,22 @@ import 'tap.dart'; /// Signature for callback when the user has tapped the screen at the same /// location twice in quick succession. -typedef GestureDoubleTapCallback = void Function(); +typedef void GestureDoubleTapCallback(); /// Signature used by [MultiTapGestureRecognizer] for when a pointer that might /// cause a tap has contacted the screen at a particular location. -typedef GestureMultiTapDownCallback = void Function(int pointer, TapDownDetails details); +typedef void GestureMultiTapDownCallback(int pointer, TapDownDetails details); /// Signature used by [MultiTapGestureRecognizer] for when a pointer that will /// trigger a tap has stopped contacting the screen at a particular location. -typedef GestureMultiTapUpCallback = void Function(int pointer, TapUpDetails details); +typedef void GestureMultiTapUpCallback(int pointer, TapUpDetails details); /// Signature used by [MultiTapGestureRecognizer] for when a tap has occurred. -typedef GestureMultiTapCallback = void Function(int pointer); +typedef void GestureMultiTapCallback(int pointer); /// Signature for when the pointer that previously triggered a /// [GestureMultiTapDownCallback] will not end up causing a tap. -typedef GestureMultiTapCancelCallback = void Function(int pointer); +typedef void GestureMultiTapCancelCallback(int pointer); /// TapTracker helps track individual tap sequences as part of a /// larger gesture. diff --git a/packages/flutter/lib/src/gestures/pointer_router.dart b/packages/flutter/lib/src/gestures/pointer_router.dart index 898d67847f..184192dc41 100644 --- a/packages/flutter/lib/src/gestures/pointer_router.dart +++ b/packages/flutter/lib/src/gestures/pointer_router.dart @@ -9,7 +9,7 @@ import 'package:flutter/foundation.dart'; import 'events.dart'; /// A callback that receives a [PointerEvent] -typedef PointerRoute = void Function(PointerEvent event); +typedef void PointerRoute(PointerEvent event); /// A routing table for [PointerEvent] events. class PointerRouter { diff --git a/packages/flutter/lib/src/gestures/recognizer.dart b/packages/flutter/lib/src/gestures/recognizer.dart index 9789d53f39..c4b01edffa 100644 --- a/packages/flutter/lib/src/gestures/recognizer.dart +++ b/packages/flutter/lib/src/gestures/recognizer.dart @@ -22,7 +22,7 @@ export 'pointer_router.dart' show PointerRouter; /// [GestureRecognizer.invokeCallback]. This allows the /// [GestureRecognizer.invokeCallback] mechanism to be generically used with /// anonymous functions that return objects of particular types. -typedef RecognizerCallback = T Function(); +typedef T RecognizerCallback(); /// The base class that all gesture recognizers inherit from. /// diff --git a/packages/flutter/lib/src/gestures/scale.dart b/packages/flutter/lib/src/gestures/scale.dart index e239375ccc..2d4b197ec9 100644 --- a/packages/flutter/lib/src/gestures/scale.dart +++ b/packages/flutter/lib/src/gestures/scale.dart @@ -84,14 +84,14 @@ class ScaleEndDetails { /// Signature for when the pointers in contact with the screen have established /// a focal point and initial scale of 1.0. -typedef GestureScaleStartCallback = void Function(ScaleStartDetails details); +typedef void GestureScaleStartCallback(ScaleStartDetails details); /// Signature for when the pointers in contact with the screen have indicated a /// new focal point and/or scale. -typedef GestureScaleUpdateCallback = void Function(ScaleUpdateDetails details); +typedef void GestureScaleUpdateCallback(ScaleUpdateDetails details); /// Signature for when the pointers are no longer in contact with the screen. -typedef GestureScaleEndCallback = void Function(ScaleEndDetails details); +typedef void GestureScaleEndCallback(ScaleEndDetails details); bool _isFlingGesture(Velocity velocity) { assert(velocity != null); diff --git a/packages/flutter/lib/src/gestures/tap.dart b/packages/flutter/lib/src/gestures/tap.dart index 39d1a73c6c..37c3a75e42 100644 --- a/packages/flutter/lib/src/gestures/tap.dart +++ b/packages/flutter/lib/src/gestures/tap.dart @@ -26,7 +26,7 @@ class TapDownDetails { /// /// The position at which the pointer contacted the screen is available in the /// `details`. -typedef GestureTapDownCallback = void Function(TapDownDetails details); +typedef void GestureTapDownCallback(TapDownDetails details); /// Details for [GestureTapUpCallback], such as position. class TapUpDetails { @@ -45,14 +45,14 @@ class TapUpDetails { /// /// The position at which the pointer stopped contacting the screen is available /// in the `details`. -typedef GestureTapUpCallback = void Function(TapUpDetails details); +typedef void GestureTapUpCallback(TapUpDetails details); /// Signature for when a tap has occurred. -typedef GestureTapCallback = void Function(); +typedef void GestureTapCallback(); /// Signature for when the pointer that previously triggered a /// [GestureTapDownCallback] will not end up causing a tap. -typedef GestureTapCancelCallback = void Function(); +typedef void GestureTapCancelCallback(); /// Recognizes taps. /// diff --git a/packages/flutter/lib/src/material/animated_icons/animated_icons.dart b/packages/flutter/lib/src/material/animated_icons/animated_icons.dart index 124573aa13..89f94862e8 100644 --- a/packages/flutter/lib/src/material/animated_icons/animated_icons.dart +++ b/packages/flutter/lib/src/material/animated_icons/animated_icons.dart @@ -125,7 +125,7 @@ class AnimatedIcon extends StatelessWidget { } } -typedef _UiPathFactory = ui.Path Function(); +typedef ui.Path _UiPathFactory(); class _AnimatedIconPainter extends CustomPainter { _AnimatedIconPainter({ @@ -296,4 +296,4 @@ T _interpolate(List values, double progress, _Interpolator interpolator return interpolator(values[lowIdx], values[highIdx], t); } -typedef _Interpolator = T Function(T a, T b, double progress); +typedef T _Interpolator(T a, T b, double progress); diff --git a/packages/flutter/lib/src/material/arc.dart b/packages/flutter/lib/src/material/arc.dart index 3bf7d2486c..f0b5db156f 100644 --- a/packages/flutter/lib/src/material/arc.dart +++ b/packages/flutter/lib/src/material/arc.dart @@ -193,7 +193,7 @@ const List<_Diagonal> _allDiagonals = const <_Diagonal>[ const _Diagonal(_CornerId.bottomLeft, _CornerId.topRight), ]; -typedef _KeyFunc = dynamic Function(T input); +typedef dynamic _KeyFunc(T input); // Select the element for which the key function returns the maximum value. T _maxBy(Iterable input, _KeyFunc keyFunc) { diff --git a/packages/flutter/lib/src/material/data_table.dart b/packages/flutter/lib/src/material/data_table.dart index c5e5fb7969..03d4a92c8d 100644 --- a/packages/flutter/lib/src/material/data_table.dart +++ b/packages/flutter/lib/src/material/data_table.dart @@ -21,7 +21,7 @@ import 'theme_data.dart'; import 'tooltip.dart'; /// Signature for [DataColumn.onSort] callback. -typedef DataColumnSortCallback = void Function(int columnIndex, bool ascending); +typedef void DataColumnSortCallback(int columnIndex, bool ascending); /// Column configuration for a [DataTable]. /// diff --git a/packages/flutter/lib/src/material/date_picker.dart b/packages/flutter/lib/src/material/date_picker.dart index f3a3adaacb..3e573e29c3 100644 --- a/packages/flutter/lib/src/material/date_picker.dart +++ b/packages/flutter/lib/src/material/date_picker.dart @@ -1008,7 +1008,7 @@ class _DatePickerDialogState extends State<_DatePickerDialog> { /// Signature for predicating dates for enabled date selections. /// /// See [showDatePicker]. -typedef SelectableDayPredicate = bool Function(DateTime day); +typedef bool SelectableDayPredicate(DateTime day); /// Shows a dialog containing a material design date picker. /// diff --git a/packages/flutter/lib/src/material/expansion_panel.dart b/packages/flutter/lib/src/material/expansion_panel.dart index 62b2e4fd40..cc46150c08 100644 --- a/packages/flutter/lib/src/material/expansion_panel.dart +++ b/packages/flutter/lib/src/material/expansion_panel.dart @@ -43,11 +43,11 @@ class _SaltedKey extends LocalKey { /// /// The position of the panel within an [ExpansionPanelList] is given by /// [panelIndex]. -typedef ExpansionPanelCallback = void Function(int panelIndex, bool isExpanded); +typedef void ExpansionPanelCallback(int panelIndex, bool isExpanded); /// Signature for the callback that's called when the header of the /// [ExpansionPanel] needs to rebuild. -typedef ExpansionPanelHeaderBuilder = Widget Function(BuildContext context, bool isExpanded); +typedef Widget ExpansionPanelHeaderBuilder(BuildContext context, bool isExpanded); /// A material expansion panel. It has a header and a body and can be either /// expanded or collapsed. The body of the panel is only visible when it is diff --git a/packages/flutter/lib/src/material/material.dart b/packages/flutter/lib/src/material/material.dart index cb54929208..a4cbacc2c8 100644 --- a/packages/flutter/lib/src/material/material.dart +++ b/packages/flutter/lib/src/material/material.dart @@ -12,7 +12,7 @@ import 'theme.dart'; /// Signature for the callback used by ink effects to obtain the rectangle for the effect. /// /// Used by [InkHighlight] and [InkSplash], for example. -typedef RectCallback = Rect Function(); +typedef Rect RectCallback(); /// The various kinds of material in material design. Used to /// configure the default behavior of [Material] widgets. diff --git a/packages/flutter/lib/src/material/popup_menu.dart b/packages/flutter/lib/src/material/popup_menu.dart index a386532b4c..ebb4588c3b 100644 --- a/packages/flutter/lib/src/material/popup_menu.dart +++ b/packages/flutter/lib/src/material/popup_menu.dart @@ -739,19 +739,19 @@ Future showMenu({ /// dismissed. /// /// Used by [PopupMenuButton.onSelected]. -typedef PopupMenuItemSelected = void Function(T value); +typedef void PopupMenuItemSelected(T value); /// Signature for the callback invoked when a [PopupMenuButton] is dismissed /// without selecting an item. /// /// Used by [PopupMenuButton.onCanceled]. -typedef PopupMenuCanceled = void Function(); +typedef void PopupMenuCanceled(); /// Signature used by [PopupMenuButton] to lazily construct the items shown when /// the button is pressed. /// /// Used by [PopupMenuButton.itemBuilder]. -typedef PopupMenuItemBuilder = List> Function(BuildContext context); +typedef List> PopupMenuItemBuilder(BuildContext context); /// Displays a menu when pressed and calls [onSelected] when the menu is dismissed /// because an item was selected. The value passed to [onSelected] is the value of diff --git a/packages/flutter/lib/src/material/refresh_indicator.dart b/packages/flutter/lib/src/material/refresh_indicator.dart index 070e47f0dd..5e045e1bb0 100644 --- a/packages/flutter/lib/src/material/refresh_indicator.dart +++ b/packages/flutter/lib/src/material/refresh_indicator.dart @@ -32,7 +32,7 @@ const Duration _kIndicatorScaleDuration = const Duration(milliseconds: 200); /// finished. /// /// Used by [RefreshIndicator.onRefresh]. -typedef RefreshCallback = Future Function(); +typedef Future RefreshCallback(); // The state machine moves through these modes only when the scrollable // identified by scrollableKey has been scrolled to its min or max limit. diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index 44d9e08df4..45e5d3e42e 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -43,7 +43,7 @@ const FloatingActionButtonAnimator _kDefaultFloatingActionButtonAnimator = Float /// not end with a [Path.close]. The returned [Path] is built under the /// assumption it will be added to an existing path that is at the `start` /// coordinates using [Path.addPath]. -typedef ComputeNotch = Path Function(Rect host, Rect guest, Offset start, Offset end); +typedef Path ComputeNotch(Rect host, Rect guest, Offset start, Offset end); enum _ScaffoldSlot { body, diff --git a/packages/flutter/lib/src/material/slider.dart b/packages/flutter/lib/src/material/slider.dart index 66fc336da9..6a12412435 100644 --- a/packages/flutter/lib/src/material/slider.dart +++ b/packages/flutter/lib/src/material/slider.dart @@ -26,7 +26,7 @@ import 'theme.dart'; /// See also: /// /// * [Slider.semanticFormatterCallback], which shows an example use case. -typedef SemanticFormatterCallback = String Function(double value); +typedef String SemanticFormatterCallback(double value); /// A Material Design slider. /// diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index 1fb1e6cffe..d89d440821 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -174,7 +174,7 @@ class _TabStyle extends AnimatedWidget { } } -typedef _LayoutCallback = void Function(List xOffsets, TextDirection textDirection, double width); +typedef void _LayoutCallback(List xOffsets, TextDirection textDirection, double width); class _TabLabelBarRenderer extends RenderFlex { _TabLabelBarRenderer({ diff --git a/packages/flutter/lib/src/painting/image_stream.dart b/packages/flutter/lib/src/painting/image_stream.dart index a761bd65c5..9edcbcbe76 100644 --- a/packages/flutter/lib/src/painting/image_stream.dart +++ b/packages/flutter/lib/src/painting/image_stream.dart @@ -66,7 +66,7 @@ class ImageInfo { /// frame is requested if the call was asynchronous (after the current frame) /// and no rendering frame is requested if the call was synchronous (within the /// same stack frame as the call to [ImageStream.addListener]). -typedef ImageListener = void Function(ImageInfo image, bool synchronousCall); +typedef void ImageListener(ImageInfo image, bool synchronousCall); /// A handle to an image resource. /// diff --git a/packages/flutter/lib/src/rendering/custom_paint.dart b/packages/flutter/lib/src/rendering/custom_paint.dart index 0555c73a27..4758be525b 100644 --- a/packages/flutter/lib/src/rendering/custom_paint.dart +++ b/packages/flutter/lib/src/rendering/custom_paint.dart @@ -22,7 +22,7 @@ import 'proxy_box.dart'; /// The returned list must not be mutated after this function completes. To /// change the semantic information, the function must return a new list /// instead. -typedef SemanticsBuilderCallback = List Function(Size size); +typedef List SemanticsBuilderCallback(Size size); /// The interface used by [CustomPaint] (in the widgets library) and /// [RenderCustomPaint] (in the rendering library). diff --git a/packages/flutter/lib/src/rendering/editable.dart b/packages/flutter/lib/src/rendering/editable.dart index 17bf7857a3..40903409c2 100644 --- a/packages/flutter/lib/src/rendering/editable.dart +++ b/packages/flutter/lib/src/rendering/editable.dart @@ -22,7 +22,7 @@ const double _kCaretWidth = 1.0; // pixels /// (including the cursor location). /// /// Used by [RenderEditable.onSelectionChanged]. -typedef SelectionChangedHandler = void Function(TextSelection selection, RenderEditable renderObject, SelectionChangedCause cause); +typedef void SelectionChangedHandler(TextSelection selection, RenderEditable renderObject, SelectionChangedCause cause); /// Indicates what triggered the change in selected text (including changes to /// the cursor location). @@ -46,7 +46,7 @@ enum SelectionChangedCause { /// Signature for the callback that reports when the caret location changes. /// /// Used by [RenderEditable.onCaretChanged]. -typedef CaretChangedHandler = void Function(Rect caretRect); +typedef void CaretChangedHandler(Rect caretRect); /// Represents the coordinates of the point in a selection, and the text /// direction at that point, relative to top left of the [RenderEditable] that diff --git a/packages/flutter/lib/src/rendering/flex.dart b/packages/flutter/lib/src/rendering/flex.dart index a7ac74ba37..97a85ce1db 100644 --- a/packages/flutter/lib/src/rendering/flex.dart +++ b/packages/flutter/lib/src/rendering/flex.dart @@ -212,7 +212,7 @@ bool _startIsTopLeft(Axis direction, TextDirection textDirection, VerticalDirect return null; } -typedef _ChildSizingFunction = double Function(RenderBox child, double extent); +typedef double _ChildSizingFunction(RenderBox child, double extent); /// Displays its children in a one-dimensional array. /// diff --git a/packages/flutter/lib/src/rendering/list_body.dart b/packages/flutter/lib/src/rendering/list_body.dart index 193cf25f89..a7b8adf0a9 100644 --- a/packages/flutter/lib/src/rendering/list_body.dart +++ b/packages/flutter/lib/src/rendering/list_body.dart @@ -10,7 +10,7 @@ import 'object.dart'; /// Parent data for use with [RenderListBody]. class ListBodyParentData extends ContainerBoxParentData { } -typedef _ChildSizingFunction = double Function(RenderBox child); +typedef double _ChildSizingFunction(RenderBox child); /// Displays its children sequentially along a given axis, forcing them to the /// dimensions of the parent in the other axis. diff --git a/packages/flutter/lib/src/rendering/list_wheel_viewport.dart b/packages/flutter/lib/src/rendering/list_wheel_viewport.dart index 7481aebad0..8622bae4d0 100644 --- a/packages/flutter/lib/src/rendering/list_wheel_viewport.dart +++ b/packages/flutter/lib/src/rendering/list_wheel_viewport.dart @@ -13,7 +13,7 @@ import 'object.dart'; import 'viewport.dart'; import 'viewport_offset.dart'; -typedef _ChildSizingFunction = double Function(RenderBox child); +typedef double _ChildSizingFunction(RenderBox child); /// [ParentData] for use with [RenderListWheelViewport]. class ListWheelParentData extends ContainerBoxParentData { } diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index 6ac107b9a6..85b3d9cecf 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -42,7 +42,7 @@ class ParentData { /// of the [PaintingContext.canvas] to the coordinate system of the callee. /// /// Used by many of the methods of [PaintingContext]. -typedef PaintingContextCallback = void Function(PaintingContext context, Offset offset); +typedef void PaintingContextCallback(PaintingContext context, Offset offset); /// A place to paint. /// @@ -531,12 +531,12 @@ abstract class Constraints { /// Signature for a function that is called for each [RenderObject]. /// /// Used by [RenderObject.visitChildren] and [RenderObject.visitChildrenForSemantics]. -typedef RenderObjectVisitor = void Function(RenderObject child); +typedef void RenderObjectVisitor(RenderObject child); /// Signature for a function that is called during layout. /// /// Used by [RenderObject.invokeLayoutCallback]. -typedef LayoutCallback = void Function(T constraints); +typedef void LayoutCallback(T constraints); /// A reference to the semantics tree. /// diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index 26de9c5a29..ecbaf6f0be 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -876,7 +876,7 @@ class RenderAnimatedOpacity extends RenderProxyBox { /// Signature for a function that creates a [Shader] for a given [Rect]. /// /// Used by [RenderShaderMask] and the [ShaderMask] widget. -typedef ShaderCallback = Shader Function(Rect bounds); +typedef Shader ShaderCallback(Rect bounds); /// Applies a mask generated by a [Shader] to its child. /// @@ -2390,22 +2390,22 @@ class RenderFractionalTranslation extends RenderProxyBox { /// Signature for listening to [PointerDownEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. -typedef PointerDownEventListener = void Function(PointerDownEvent event); +typedef void PointerDownEventListener(PointerDownEvent event); /// Signature for listening to [PointerMoveEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. -typedef PointerMoveEventListener = void Function(PointerMoveEvent event); +typedef void PointerMoveEventListener(PointerMoveEvent event); /// Signature for listening to [PointerUpEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. -typedef PointerUpEventListener = void Function(PointerUpEvent event); +typedef void PointerUpEventListener(PointerUpEvent event); /// Signature for listening to [PointerCancelEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. -typedef PointerCancelEventListener = void Function(PointerCancelEvent event); +typedef void PointerCancelEventListener(PointerCancelEvent event); /// Calls callbacks in response to pointer events. /// diff --git a/packages/flutter/lib/src/scheduler/binding.dart b/packages/flutter/lib/src/scheduler/binding.dart index e0ee9b6d1f..c3846481e2 100644 --- a/packages/flutter/lib/src/scheduler/binding.dart +++ b/packages/flutter/lib/src/scheduler/binding.dart @@ -39,13 +39,13 @@ set timeDilation(double value) { /// scheduler's epoch. Use timeStamp to determine how far to advance animation /// timelines so that all the animations in the system are synchronized to a /// common time base. -typedef FrameCallback = void Function(Duration timeStamp); +typedef void FrameCallback(Duration timeStamp); /// Signature for [Scheduler.scheduleTask] callbacks. /// /// The type argument `T` is the task's return value. Consider [void] if the /// task does not return a value. -typedef TaskCallback = T Function(); +typedef T TaskCallback(); /// Signature for the [SchedulerBinding.schedulingStrategy] callback. Called /// whenever the system needs to decide whether a task at a given @@ -55,7 +55,7 @@ typedef TaskCallback = T Function(); /// at this time, false otherwise. /// /// See also [defaultSchedulingStrategy]. -typedef SchedulingStrategy = bool Function({ int priority, SchedulerBinding scheduler }); +typedef bool SchedulingStrategy({ int priority, SchedulerBinding scheduler }); class _TaskEntry { _TaskEntry(this.task, this.priority, this.debugLabel, this.flow) { diff --git a/packages/flutter/lib/src/scheduler/ticker.dart b/packages/flutter/lib/src/scheduler/ticker.dart index e8daee55cb..613283e859 100644 --- a/packages/flutter/lib/src/scheduler/ticker.dart +++ b/packages/flutter/lib/src/scheduler/ticker.dart @@ -12,7 +12,7 @@ import 'binding.dart'; /// /// The argument is the time that the object had spent enabled so far /// at the time of the callback being called. -typedef TickerCallback = void Function(Duration elapsed); +typedef void TickerCallback(Duration elapsed); /// An interface implemented by classes that can vend [Ticker] objects. /// diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 63e6ad0464..cef05c6938 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -23,19 +23,19 @@ export 'semantics_event.dart'; /// Return false to stop visiting nodes. /// /// Used by [SemanticsNode.visitChildren]. -typedef SemanticsNodeVisitor = bool Function(SemanticsNode node); +typedef bool SemanticsNodeVisitor(SemanticsNode node); /// Signature for [SemanticsAction]s that move the cursor. /// /// If `extendSelection` is set to true the cursor movement should extend the /// current selection or (if nothing is currently selected) start a selection. -typedef MoveCursorHandler = void Function(bool extendSelection); +typedef void MoveCursorHandler(bool extendSelection); /// Signature for the [SemanticsAction.setSelection] handlers to change the /// text selection (or re-position the cursor) to `selection`. -typedef SetSelectionHandler = void Function(TextSelection selection); +typedef void SetSelectionHandler(TextSelection selection); -typedef _SemanticsActionHandler = void Function(dynamic args); +typedef void _SemanticsActionHandler(dynamic args); /// A tag for a [SemanticsNode]. /// diff --git a/packages/flutter/lib/src/services/platform_messages.dart b/packages/flutter/lib/src/services/platform_messages.dart index bc903c3736..55f782a1be 100644 --- a/packages/flutter/lib/src/services/platform_messages.dart +++ b/packages/flutter/lib/src/services/platform_messages.dart @@ -10,7 +10,7 @@ import 'package:flutter/foundation.dart'; import 'platform_channel.dart'; -typedef _MessageHandler = Future Function(ByteData message); +typedef Future _MessageHandler(ByteData message); /// Sends binary messages to and receives binary messages from platform plugins. /// diff --git a/packages/flutter/lib/src/services/text_formatter.dart b/packages/flutter/lib/src/services/text_formatter.dart index 8cf5d7025b..2c13b01ceb 100644 --- a/packages/flutter/lib/src/services/text_formatter.dart +++ b/packages/flutter/lib/src/services/text_formatter.dart @@ -53,7 +53,7 @@ abstract class TextInputFormatter { /// Function signature expected for creating custom [TextInputFormatter] /// shorthands via [TextInputFormatter.withFunction]; -typedef TextInputFormatFunction = TextEditingValue Function( +typedef TextEditingValue TextInputFormatFunction( TextEditingValue oldValue, TextEditingValue newValue, ); diff --git a/packages/flutter/lib/src/widgets/animated_cross_fade.dart b/packages/flutter/lib/src/widgets/animated_cross_fade.dart index d5d11900ca..a501589a4b 100644 --- a/packages/flutter/lib/src/widgets/animated_cross_fade.dart +++ b/packages/flutter/lib/src/widgets/animated_cross_fade.dart @@ -57,7 +57,7 @@ enum CrossFadeState { /// ); /// } /// ``` -typedef AnimatedCrossFadeBuilder = Widget Function(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey); +typedef Widget AnimatedCrossFadeBuilder(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey); /// A widget that cross-fades between two given children and animates itself /// between their sizes. diff --git a/packages/flutter/lib/src/widgets/animated_list.dart b/packages/flutter/lib/src/widgets/animated_list.dart index 2b6301b994..9833e0dd7f 100644 --- a/packages/flutter/lib/src/widgets/animated_list.dart +++ b/packages/flutter/lib/src/widgets/animated_list.dart @@ -14,10 +14,10 @@ import 'scroll_view.dart'; import 'ticker_provider.dart'; /// Signature for the builder callback used by [AnimatedList]. -typedef AnimatedListItemBuilder = Widget Function(BuildContext context, int index, Animation animation); +typedef Widget AnimatedListItemBuilder(BuildContext context, int index, Animation animation); /// Signature for the builder callback used by [AnimatedListState.removeItem]. -typedef AnimatedListRemovedItemBuilder = Widget Function(BuildContext context, Animation animation); +typedef Widget AnimatedListRemovedItemBuilder(BuildContext context, Animation animation); // The default insert/remove animation duration. const Duration _kDuration = const Duration(milliseconds: 300); diff --git a/packages/flutter/lib/src/widgets/animated_switcher.dart b/packages/flutter/lib/src/widgets/animated_switcher.dart index 46dd3ef7d8..4d96c48f0d 100644 --- a/packages/flutter/lib/src/widgets/animated_switcher.dart +++ b/packages/flutter/lib/src/widgets/animated_switcher.dart @@ -43,7 +43,7 @@ class _AnimatedSwitcherChildEntry { /// /// The function should return a widget which wraps the given `child`. It may /// also use the `animation` to inform its transition. It must not return null. -typedef AnimatedSwitcherTransitionBuilder = Widget Function(Widget child, Animation animation); +typedef Widget AnimatedSwitcherTransitionBuilder(Widget child, Animation animation); /// Signature for builders used to generate custom layouts for /// [AnimatedSwitcher]. @@ -55,7 +55,7 @@ typedef AnimatedSwitcherTransitionBuilder = Widget Function(Widget child, Animat /// The `previousChildren` list is an unmodifiable list, sorted with the oldest /// at the beginning and the newest at the end. It does not include the /// `currentChild`. -typedef AnimatedSwitcherLayoutBuilder = Widget Function(Widget currentChild, List previousChildren); +typedef Widget AnimatedSwitcherLayoutBuilder(Widget currentChild, List previousChildren); /// A widget that by default does a [FadeTransition] between a new widget and /// the widget previously set on the [AnimatedSwitcher] as a child. diff --git a/packages/flutter/lib/src/widgets/app.dart b/packages/flutter/lib/src/widgets/app.dart index 8c86fe16de..3611ccc825 100644 --- a/packages/flutter/lib/src/widgets/app.dart +++ b/packages/flutter/lib/src/widgets/app.dart @@ -31,7 +31,7 @@ export 'dart:ui' show Locale; /// The `locale` is the device's locale when the app started, or the device /// locale the user selected after the app was started. The `supportedLocales` /// parameter is just the value of [WidgetsApp.supportedLocales]. -typedef LocaleResolutionCallback = Locale Function(Locale locale, Iterable supportedLocales); +typedef Locale LocaleResolutionCallback(Locale locale, Iterable supportedLocales); /// The signature of [WidgetsApp.onGenerateTitle]. /// @@ -41,7 +41,7 @@ typedef LocaleResolutionCallback = Locale Function(Locale locale, Iterable { /// itself based on a snapshot from interacting with a [Stream]. /// * [FutureBuilder], which delegates to an [AsyncWidgetBuilder] to build /// itself based on a snapshot from interacting with a [Future]. -typedef AsyncWidgetBuilder = Widget Function(BuildContext context, AsyncSnapshot snapshot); +typedef Widget AsyncWidgetBuilder(BuildContext context, AsyncSnapshot snapshot); /// Widget that builds itself based on the latest snapshot of interaction with /// a [Stream]. diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 0a23ef7fe9..be5c27eeb0 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -5402,7 +5402,7 @@ class Builder extends StatelessWidget { /// Signature for the builder callback used by [StatefulBuilder]. /// /// Call [setState] to schedule the [StatefulBuilder] to rebuild. -typedef StatefulWidgetBuilder = Widget Function(BuildContext context, StateSetter setState); +typedef Widget StatefulWidgetBuilder(BuildContext context, StateSetter setState); /// A platonic widget that both has state and calls a closure to obtain its child widget. /// diff --git a/packages/flutter/lib/src/widgets/dismissible.dart b/packages/flutter/lib/src/widgets/dismissible.dart index ca0640d451..b90cf84669 100644 --- a/packages/flutter/lib/src/widgets/dismissible.dart +++ b/packages/flutter/lib/src/widgets/dismissible.dart @@ -20,7 +20,7 @@ const double _kDismissThreshold = 0.4; /// the given `direction`. /// /// Used by [Dismissible.onDismissed]. -typedef DismissDirectionCallback = void Function(DismissDirection direction); +typedef void DismissDirectionCallback(DismissDirection direction); /// The direction in which a [Dismissible] can be dismissed. enum DismissDirection { diff --git a/packages/flutter/lib/src/widgets/drag_target.dart b/packages/flutter/lib/src/widgets/drag_target.dart index d463e7f359..1841685f4e 100644 --- a/packages/flutter/lib/src/widgets/drag_target.dart +++ b/packages/flutter/lib/src/widgets/drag_target.dart @@ -14,12 +14,12 @@ import 'overlay.dart'; /// Signature for determining whether the given data will be accepted by a [DragTarget]. /// /// Used by [DragTarget.onWillAccept]. -typedef DragTargetWillAccept = bool Function(T data); +typedef bool DragTargetWillAccept(T data); /// Signature for causing a [DragTarget] to accept the given data. /// /// Used by [DragTarget.onAccept]. -typedef DragTargetAccept = void Function(T data); +typedef void DragTargetAccept(T data); /// Signature for building children of a [DragTarget]. /// @@ -29,17 +29,17 @@ typedef DragTargetAccept = void Function(T data); /// this [DragTarget] and that will not be accepted by the [DragTarget]. /// /// Used by [DragTarget.builder]. -typedef DragTargetBuilder = Widget Function(BuildContext context, List candidateData, List rejectedData); +typedef Widget DragTargetBuilder(BuildContext context, List candidateData, List rejectedData); /// Signature for when a [Draggable] is dropped without being accepted by a [DragTarget]. /// /// Used by [Draggable.onDraggableCanceled]. -typedef DraggableCanceledCallback = void Function(Velocity velocity, Offset offset); +typedef void DraggableCanceledCallback(Velocity velocity, Offset offset); /// Signature for when a [Draggable] leaves a [DragTarget]. /// /// Used by [DragTarget.onLeave]. -typedef DragTargetLeave = void Function(T data); +typedef void DragTargetLeave(T data); /// Where the [Draggable] should be anchored during a drag. enum DragAnchor { @@ -481,7 +481,7 @@ class _DragTargetState extends State> { } enum _DragEndKind { dropped, canceled } -typedef _OnDragEnd = void Function(Velocity velocity, Offset offset, bool wasAccepted); +typedef void _OnDragEnd(Velocity velocity, Offset offset, bool wasAccepted); // The lifetime of this object is a little dubious right now. Specifically, it // lives as long as the pointer is down. Arguably it should self-immolate if the diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 32973f1cfa..b7664dc258 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -24,7 +24,7 @@ export 'package:flutter/rendering.dart' show SelectionChangedCause; /// Signature for the callback that reports when the user changes the selection /// (including the cursor location). -typedef SelectionChangedCallback = void Function(TextSelection selection, SelectionChangedCause cause); +typedef void SelectionChangedCallback(TextSelection selection, SelectionChangedCause cause); const Duration _kCursorBlinkHalfPeriod = const Duration(milliseconds: 500); diff --git a/packages/flutter/lib/src/widgets/fade_in_image.dart b/packages/flutter/lib/src/widgets/fade_in_image.dart index 6ce6312d1f..fbfc815b39 100644 --- a/packages/flutter/lib/src/widgets/fade_in_image.dart +++ b/packages/flutter/lib/src/widgets/fade_in_image.dart @@ -311,7 +311,7 @@ enum FadeInImagePhase { completed, } -typedef _ImageProviderResolverListener = void Function(); +typedef void _ImageProviderResolverListener(); class _ImageProviderResolver { _ImageProviderResolver({ diff --git a/packages/flutter/lib/src/widgets/form.dart b/packages/flutter/lib/src/widgets/form.dart index 214f77178d..47d6e3e6a1 100644 --- a/packages/flutter/lib/src/widgets/form.dart +++ b/packages/flutter/lib/src/widgets/form.dart @@ -183,17 +183,17 @@ class _FormScope extends InheritedWidget { /// Signature for validating a form field. /// /// Used by [FormField.validator]. -typedef FormFieldValidator = String Function(T value); +typedef String FormFieldValidator(T value); /// Signature for being notified when a form field changes value. /// /// Used by [FormField.onSaved]. -typedef FormFieldSetter = void Function(T newValue); +typedef void FormFieldSetter(T newValue); /// Signature for building the widget representing the form field. /// /// Used by [FormField.builder]. -typedef FormFieldBuilder = Widget Function(FormFieldState field); +typedef Widget FormFieldBuilder(FormFieldState field); /// A single form field. /// diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 05e71bbddc..43ff5e8382 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -829,7 +829,7 @@ enum _StateLifecycle { } /// The signature of [State.setState] functions. -typedef StateSetter = void Function(VoidCallback fn); +typedef void StateSetter(VoidCallback fn); /// The logic and internal state for a [StatefulWidget]. /// @@ -1751,7 +1751,7 @@ class _InactiveElements { /// /// It is safe to call `element.visitChildElements` reentrantly within /// this callback. -typedef ElementVisitor = void Function(Element element); +typedef void ElementVisitor(Element element); /// A handle to the location of a widget in the widget tree. /// @@ -3518,7 +3518,7 @@ abstract class Element extends DiagnosticableTree implements BuildContext { /// * [FlutterError.reportError], which is typically called with the same /// [FlutterErrorDetails] object immediately prior to [ErrorWidget.builder] /// being called. -typedef ErrorWidgetBuilder = Widget Function(FlutterErrorDetails details); +typedef Widget ErrorWidgetBuilder(FlutterErrorDetails details); /// A widget that renders an exception's message. /// @@ -3581,13 +3581,13 @@ class ErrorWidget extends LeafRenderObjectWidget { /// or [State.build]. /// /// Used by [Builder.builder], [OverlayEntry.builder], etc. -typedef WidgetBuilder = Widget Function(BuildContext context); +typedef Widget WidgetBuilder(BuildContext context); /// Signature for a function that creates a widget for a given index, e.g., in a /// list. /// /// Used by [ListView.builder] and other APIs that use lazily-generated widgets. -typedef IndexedWidgetBuilder = Widget Function(BuildContext context, int index); +typedef Widget IndexedWidgetBuilder(BuildContext context, int index); /// A builder that builds a widget given a child. /// @@ -3595,7 +3595,7 @@ typedef IndexedWidgetBuilder = Widget Function(BuildContext context, int index); /// /// Used by [AnimatedBuilder.builder], as well as [WidgetsApp.builder] and /// [MaterialApp.builder]. -typedef TransitionBuilder = Widget Function(BuildContext context, Widget child); +typedef Widget TransitionBuilder(BuildContext context, Widget child); /// An [Element] that composes other [Element]s. /// diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index 463f57d0a5..7be656c332 100644 --- a/packages/flutter/lib/src/widgets/gesture_detector.dart +++ b/packages/flutter/lib/src/widgets/gesture_detector.dart @@ -61,10 +61,10 @@ abstract class GestureRecognizerFactory { } /// Signature for closures that implement [GestureRecognizerFactory.constructor]. -typedef GestureRecognizerFactoryConstructor = T Function(); +typedef T GestureRecognizerFactoryConstructor(); /// Signature for closures that implement [GestureRecognizerFactory.initializer]. -typedef GestureRecognizerFactoryInitializer = void Function(T instance); +typedef void GestureRecognizerFactoryInitializer(T instance); /// Factory for creating gesture recognizers that delegates to callbacks. /// diff --git a/packages/flutter/lib/src/widgets/heroes.dart b/packages/flutter/lib/src/widgets/heroes.dart index d2f2063c70..d936656e90 100644 --- a/packages/flutter/lib/src/widgets/heroes.dart +++ b/packages/flutter/lib/src/widgets/heroes.dart @@ -18,9 +18,9 @@ import 'transitions.dart'; /// This is typically used with a [HeroController] to provide an animation for /// [Hero] positions that looks nicer than a linear movement. For example, see /// [MaterialRectArcTween]. -typedef CreateRectTween = Tween Function(Rect begin, Rect end); +typedef Tween CreateRectTween(Rect begin, Rect end); -typedef _OnFlightEnded = void Function(_HeroFlight flight); +typedef void _OnFlightEnded(_HeroFlight flight); enum _HeroFlightType { push, // Fly the "to" hero and animate with the "to" route. diff --git a/packages/flutter/lib/src/widgets/implicit_animations.dart b/packages/flutter/lib/src/widgets/implicit_animations.dart index 8846a5add5..6b84e066f8 100644 --- a/packages/flutter/lib/src/widgets/implicit_animations.dart +++ b/packages/flutter/lib/src/widgets/implicit_animations.dart @@ -223,10 +223,10 @@ abstract class ImplicitlyAnimatedWidget extends StatefulWidget { /// /// This is the type of one of the arguments of [TweenVisitor], the signature /// used by [AnimatedWidgetBaseState.forEachTween]. -typedef TweenConstructor = Tween Function(T targetValue); +typedef Tween TweenConstructor(T targetValue); /// Signature for callbacks passed to [AnimatedWidgetBaseState.forEachTween]. -typedef TweenVisitor = Tween Function(Tween tween, T targetValue, TweenConstructor constructor); +typedef Tween TweenVisitor(Tween tween, T targetValue, TweenConstructor constructor); /// A base class for widgets with implicit animations. /// diff --git a/packages/flutter/lib/src/widgets/layout_builder.dart b/packages/flutter/lib/src/widgets/layout_builder.dart index 6e37a1cdbd..6b6f321159 100644 --- a/packages/flutter/lib/src/widgets/layout_builder.dart +++ b/packages/flutter/lib/src/widgets/layout_builder.dart @@ -9,7 +9,7 @@ import 'debug.dart'; import 'framework.dart'; /// The signature of the [LayoutBuilder] builder function. -typedef LayoutWidgetBuilder = Widget Function(BuildContext context, BoxConstraints constraints); +typedef Widget LayoutWidgetBuilder(BuildContext context, BoxConstraints constraints); /// Builds a widget tree that can depend on the parent widget's size. /// diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 6ad81a43bc..98d9a4cee3 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -23,16 +23,16 @@ import 'ticker_provider.dart'; /// Creates a route for the given route settings. /// /// Used by [Navigator.onGenerateRoute] and [Navigator.onUnknownRoute]. -typedef RouteFactory = Route Function(RouteSettings settings); +typedef Route RouteFactory(RouteSettings settings); /// Signature for the [Navigator.popUntil] predicate argument. -typedef RoutePredicate = bool Function(Route route); +typedef bool RoutePredicate(Route route); /// Signature for a callback that verifies that it's OK to call [Navigator.pop]. /// /// Used by [Form.onWillPop], [ModalRoute.addScopedWillPopCallback], /// [ModalRoute.removeScopedWillPopCallback], and [WillPopScope]. -typedef WillPopCallback = Future Function(); +typedef Future WillPopCallback(); /// Indicates whether the current route should be popped. /// diff --git a/packages/flutter/lib/src/widgets/nested_scroll_view.dart b/packages/flutter/lib/src/widgets/nested_scroll_view.dart index 2976f79ecf..720e01751e 100644 --- a/packages/flutter/lib/src/widgets/nested_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/nested_scroll_view.dart @@ -34,7 +34,7 @@ import 'viewport.dart'; /// [SliverAppBar.forceElevated] property to ensure that the app bar shows a /// shadow, since it would otherwise not necessarily be aware that it had /// content ostensibly below it. -typedef NestedScrollViewHeaderSliversBuilder = List Function(BuildContext context, bool innerBoxIsScrolled); +typedef List NestedScrollViewHeaderSliversBuilder(BuildContext context, bool innerBoxIsScrolled); /// A scrolling view inside of which can be nested other scrolling views, with /// their scroll positions being intrinsically linked. @@ -454,7 +454,7 @@ class _NestedScrollMetrics extends FixedScrollMetrics { final double correctionOffset; } -typedef _NestedScrollActivityGetter = ScrollActivity Function(_NestedScrollPosition position); +typedef ScrollActivity _NestedScrollActivityGetter(_NestedScrollPosition position); class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldController { _NestedScrollCoordinator(this._state, this._parent, this._onHasScrolledBodyChanged) { diff --git a/packages/flutter/lib/src/widgets/notification_listener.dart b/packages/flutter/lib/src/widgets/notification_listener.dart index f1be92ae72..66f743d82c 100644 --- a/packages/flutter/lib/src/widgets/notification_listener.dart +++ b/packages/flutter/lib/src/widgets/notification_listener.dart @@ -10,7 +10,7 @@ import 'framework.dart'; /// notification to continue to be dispatched to further ancestors. /// /// Used by [NotificationListener.onNotification]. -typedef NotificationListenerCallback = bool Function(T notification); +typedef bool NotificationListenerCallback(T notification); /// A notification that can bubble up the widget tree. /// diff --git a/packages/flutter/lib/src/widgets/orientation_builder.dart b/packages/flutter/lib/src/widgets/orientation_builder.dart index b8825acb17..85029cc380 100644 --- a/packages/flutter/lib/src/widgets/orientation_builder.dart +++ b/packages/flutter/lib/src/widgets/orientation_builder.dart @@ -10,7 +10,7 @@ import 'media_query.dart'; /// Signature for a function that builds a widget given an [Orientation]. /// /// Used by [OrientationBuilder.builder]. -typedef OrientationWidgetBuilder = Widget Function(BuildContext context, Orientation orientation); +typedef Widget OrientationWidgetBuilder(BuildContext context, Orientation orientation); /// Builds a widget tree that can depend on the parent widget's orientation /// (distinct from the device orientation). diff --git a/packages/flutter/lib/src/widgets/pages.dart b/packages/flutter/lib/src/widgets/pages.dart index eb86935403..af498d57bf 100644 --- a/packages/flutter/lib/src/widgets/pages.dart +++ b/packages/flutter/lib/src/widgets/pages.dart @@ -48,13 +48,13 @@ abstract class PageRoute extends ModalRoute { /// primary contents. /// /// See [ModalRoute.buildPage] for complete definition of the parameters. -typedef RoutePageBuilder = Widget Function(BuildContext context, Animation animation, Animation secondaryAnimation); +typedef Widget RoutePageBuilder(BuildContext context, Animation animation, Animation secondaryAnimation); /// Signature for the [PageRouteBuilder] function that builds the route's /// transitions. /// /// See [ModalRoute.buildTransitions] for complete definition of the parameters. -typedef RouteTransitionsBuilder = Widget Function(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child); +typedef Widget RouteTransitionsBuilder(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child); Widget _defaultTransitionsBuilder(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { return child; diff --git a/packages/flutter/lib/src/widgets/scroll_notification.dart b/packages/flutter/lib/src/widgets/scroll_notification.dart index ba85032ea6..8ab378aca7 100644 --- a/packages/flutter/lib/src/widgets/scroll_notification.dart +++ b/packages/flutter/lib/src/widgets/scroll_notification.dart @@ -284,7 +284,7 @@ class UserScrollNotification extends ScrollNotification { /// A predicate for [ScrollNotification], used to customize widgets that /// listen to notifications from their children. -typedef ScrollNotificationPredicate = bool Function(ScrollNotification notification); +typedef bool ScrollNotificationPredicate(ScrollNotification notification); /// A [ScrollNotificationPredicate] that checks whether /// `notification.depth == 0`, which means that the notification did not bubble diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 67179d1560..563ccc035b 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -25,7 +25,7 @@ export 'package:flutter/physics.dart' show Tolerance; /// Signature used by [Scrollable] to build the viewport through which the /// scrollable content is displayed. -typedef ViewportBuilder = Widget Function(BuildContext context, ViewportOffset position); +typedef Widget ViewportBuilder(BuildContext context, ViewportOffset position); /// A widget that scrolls. /// diff --git a/packages/flutter/lib/src/widgets/text_selection.dart b/packages/flutter/lib/src/widgets/text_selection.dart index 1b37cc3400..597ac50996 100644 --- a/packages/flutter/lib/src/widgets/text_selection.dart +++ b/packages/flutter/lib/src/widgets/text_selection.dart @@ -58,7 +58,7 @@ enum _TextSelectionHandlePosition { start, end } /// of the [RenderBox] given by the [TextSelectionOverlay.renderObject]. /// /// Used by [TextSelectionOverlay.onSelectionOverlayChanged]. -typedef TextSelectionOverlayChanged = void Function(TextEditingValue value, Rect caretRect); +typedef void TextSelectionOverlayChanged(TextEditingValue value, Rect caretRect); /// An interface for manipulating the selection, to be used by the implementor /// of the toolbar widget. diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index 248c073e3a..248f6107dd 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -24,9 +24,9 @@ import 'icon_data.dart'; /// Signature for the builder callback used by /// [WidgetInspector.selectButtonBuilder]. -typedef InspectorSelectButtonBuilder = Widget Function(BuildContext context, VoidCallback onPressed); +typedef Widget InspectorSelectButtonBuilder(BuildContext context, VoidCallback onPressed); -typedef _RegisterServiceExtensionCallback = void Function({ +typedef void _RegisterServiceExtensionCallback({ @required String name, @required ServiceExtensionCallback callback }); @@ -93,7 +93,7 @@ List<_DiagnosticsPathNode> _followDiagnosticableChain(List chain /// Signature for the selection change callback used by /// [WidgetInspectorService.selectionChangedCallback]. -typedef InspectorSelectionChangedCallback = void Function(); +typedef void InspectorSelectionChangedCallback(); /// Structure to help reference count Dart objects referenced by a GUI tool /// using [WidgetInspectorService]. diff --git a/packages/flutter/test/gestures/arena_test.dart b/packages/flutter/test/gestures/arena_test.dart index 97ad099187..38931be6b8 100644 --- a/packages/flutter/test/gestures/arena_test.dart +++ b/packages/flutter/test/gestures/arena_test.dart @@ -5,7 +5,7 @@ import 'package:flutter/gestures.dart'; import 'package:test/test.dart'; -typedef GestureArenaCallback = void Function(Object key); +typedef void GestureArenaCallback(Object key); const int primaryKey = 4; diff --git a/packages/flutter/test/gestures/gesture_binding_test.dart b/packages/flutter/test/gestures/gesture_binding_test.dart index dc8b9244e8..8af8b290d2 100644 --- a/packages/flutter/test/gestures/gesture_binding_test.dart +++ b/packages/flutter/test/gestures/gesture_binding_test.dart @@ -8,7 +8,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:test/test.dart'; -typedef HandleEventCallback = void Function(PointerEvent event); +typedef void HandleEventCallback(PointerEvent event); class TestGestureFlutterBinding extends BindingBase with GestureBinding { HandleEventCallback callback; diff --git a/packages/flutter/test/gestures/gesture_tester.dart b/packages/flutter/test/gestures/gesture_tester.dart index c0784d9ac1..4f88224413 100644 --- a/packages/flutter/test/gestures/gesture_tester.dart +++ b/packages/flutter/test/gestures/gesture_tester.dart @@ -31,7 +31,7 @@ class GestureTester { } } -typedef GestureTest = void Function(GestureTester tester); +typedef void GestureTest(GestureTester tester); @isTest void testGesture(String description, GestureTest callback) { diff --git a/packages/flutter/test/gestures/locking_test.dart b/packages/flutter/test/gestures/locking_test.dart index 1aa0c8fd75..f4975a0ed7 100644 --- a/packages/flutter/test/gestures/locking_test.dart +++ b/packages/flutter/test/gestures/locking_test.dart @@ -9,7 +9,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:test/test.dart'; -typedef HandleEventCallback = void Function(PointerEvent event); +typedef void HandleEventCallback(PointerEvent event); class TestGestureFlutterBinding extends BindingBase with GestureBinding { HandleEventCallback callback; diff --git a/packages/flutter/test/material/feedback_test.dart b/packages/flutter/test/material/feedback_test.dart index eb4a739648..672fc2ff2f 100644 --- a/packages/flutter/test/material/feedback_test.dart +++ b/packages/flutter/test/material/feedback_test.dart @@ -224,4 +224,4 @@ class TestWidget extends StatelessWidget { } } -typedef HandlerCreator = VoidCallback Function(BuildContext context); +typedef VoidCallback HandlerCreator(BuildContext context); diff --git a/packages/flutter/test/material/tabs_test.dart b/packages/flutter/test/material/tabs_test.dart index c11bb4d463..0960c66451 100644 --- a/packages/flutter/test/material/tabs_test.dart +++ b/packages/flutter/test/material/tabs_test.dart @@ -69,7 +69,7 @@ Widget buildFrame({ ); } -typedef TabControllerFrameBuilder = Widget Function(BuildContext context, TabController controller); +typedef Widget TabControllerFrameBuilder(BuildContext context, TabController controller); class TabControllerFrame extends StatefulWidget { const TabControllerFrame({ this.length, this.initialIndex = 0, this.builder }); diff --git a/packages/flutter/test/rendering/mock_canvas.dart b/packages/flutter/test/rendering/mock_canvas.dart index 0d287a99e8..b7b57f01f5 100644 --- a/packages/flutter/test/rendering/mock_canvas.dart +++ b/packages/flutter/test/rendering/mock_canvas.dart @@ -59,13 +59,13 @@ Matcher get paintsAssertion => new _TestRecordingCanvasPaintsAssertionMatcher(); /// ```dart /// if (methodName == #drawCircle) { ... } /// ``` -typedef PaintPatternPredicate = bool Function(Symbol methodName, List arguments); +typedef bool PaintPatternPredicate(Symbol methodName, List arguments); /// The signature of [RenderObject.paint] functions. -typedef _ContextPainterFunction = void Function(PaintingContext context, Offset offset); +typedef void _ContextPainterFunction(PaintingContext context, Offset offset); /// The signature of functions that paint directly on a canvas. -typedef _CanvasPainterFunction = void Function(Canvas canvas); +typedef void _CanvasPainterFunction(Canvas canvas); /// Builder interface for patterns used to match display lists (canvas calls). /// diff --git a/packages/flutter/test/widgets/dismissible_test.dart b/packages/flutter/test/widgets/dismissible_test.dart index af8226eaf5..e856064425 100644 --- a/packages/flutter/test/widgets/dismissible_test.dart +++ b/packages/flutter/test/widgets/dismissible_test.dart @@ -61,7 +61,7 @@ Widget buildTest({ double startToEndThreshold, TextDirection textDirection = Tex ); } -typedef DismissMethod = Future Function(WidgetTester tester, Finder finder, { @required AxisDirection gestureDirection }); +typedef Future DismissMethod(WidgetTester tester, Finder finder, { @required AxisDirection gestureDirection }); Future dismissElement(WidgetTester tester, Finder finder, { @required AxisDirection gestureDirection }) async { Offset downLocation; diff --git a/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart b/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart index 2e1e7cc422..0a8d070bd0 100644 --- a/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart +++ b/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart @@ -5,7 +5,7 @@ import 'package:flutter_test/flutter_test.dart' hide TypeMatcher; import 'package:flutter/widgets.dart'; -typedef TestCallback = void Function(BuildContext context); +typedef void TestCallback(BuildContext context); class TestWidget extends StatefulWidget { const TestWidget(this.callback); diff --git a/packages/flutter/test/widgets/navigator_test.dart b/packages/flutter/test/widgets/navigator_test.dart index ba3e4fa1a7..8f594fa9be 100644 --- a/packages/flutter/test/widgets/navigator_test.dart +++ b/packages/flutter/test/widgets/navigator_test.dart @@ -42,7 +42,7 @@ class SecondWidgetState extends State { } } -typedef ExceptionCallback = void Function(dynamic exception); +typedef void ExceptionCallback(dynamic exception); class ThirdWidget extends StatelessWidget { const ThirdWidget({ this.targetKey, this.onException }); @@ -89,7 +89,7 @@ class OnTapPage extends StatelessWidget { } } -typedef OnObservation = void Function(Route route, Route previousRoute); +typedef void OnObservation(Route route, Route previousRoute); class TestObserver extends NavigatorObserver { OnObservation onPushed; diff --git a/packages/flutter/test/widgets/semantics_traversal_test.dart b/packages/flutter/test/widgets/semantics_traversal_test.dart index b57de03efa..6f8cd55666 100644 --- a/packages/flutter/test/widgets/semantics_traversal_test.dart +++ b/packages/flutter/test/widgets/semantics_traversal_test.dart @@ -14,7 +14,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; -typedef TraversalTestFunction = Future Function(TraversalTester tester); +typedef Future TraversalTestFunction(TraversalTester tester); const Size tenByTen = const Size(10.0, 10.0); void main() { diff --git a/packages/flutter/test/widgets/shape_decoration_test.dart b/packages/flutter/test/widgets/shape_decoration_test.dart index 11c78d3de1..9fa7d0ec2b 100644 --- a/packages/flutter/test/widgets/shape_decoration_test.dart +++ b/packages/flutter/test/widgets/shape_decoration_test.dart @@ -105,7 +105,7 @@ Future main() async { }); } -typedef Logger = void Function(String caller); +typedef void Logger(String caller); class TestBorder extends ShapeBorder { const TestBorder(this.onLog) : assert(onLog != null); diff --git a/packages/flutter/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart index ef06516d90..498516bf96 100644 --- a/packages/flutter/test/widgets/widget_inspector_test.dart +++ b/packages/flutter/test/widgets/widget_inspector_test.dart @@ -10,7 +10,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -typedef InspectorServiceExtensionCallback = FutureOr> Function(Map parameters); +typedef FutureOr> InspectorServiceExtensionCallback(Map parameters); void main() { TestWidgetInspectorService.runTests(); diff --git a/packages/flutter_driver/lib/src/driver/driver.dart b/packages/flutter_driver/lib/src/driver/driver.dart index b7c9d76a03..9f8d2560ae 100644 --- a/packages/flutter_driver/lib/src/driver/driver.dart +++ b/packages/flutter_driver/lib/src/driver/driver.dart @@ -111,7 +111,7 @@ const CommonFinders find = const CommonFinders._(); /// If computation is asynchronous, the function may return a [Future]. /// /// See also [FlutterDriver.waitFor]. -typedef EvaluatorFunction = dynamic Function(); +typedef dynamic EvaluatorFunction(); /// Drives a Flutter Application running in another process. class FlutterDriver { @@ -770,7 +770,7 @@ class VMServiceClientConnection { } /// A function that connects to a Dart VM service given the [url]. -typedef VMServiceConnectFunction = Future Function(String url); +typedef Future VMServiceConnectFunction(String url); /// The connection function used by [FlutterDriver.connect]. /// diff --git a/packages/flutter_driver/lib/src/extension/extension.dart b/packages/flutter_driver/lib/src/extension/extension.dart index 07acce4079..fb68e0de9c 100644 --- a/packages/flutter_driver/lib/src/extension/extension.dart +++ b/packages/flutter_driver/lib/src/extension/extension.dart @@ -33,7 +33,7 @@ const String _extensionMethod = 'ext.flutter.$_extensionMethodName'; /// /// Messages are described in string form and should return a [Future] which /// eventually completes to a string response. -typedef DataHandler = Future Function(String message); +typedef Future DataHandler(String message); class _DriverBinding extends BindingBase with ServicesBinding, SchedulerBinding, GestureBinding, PaintingBinding, RendererBinding, WidgetsBinding { _DriverBinding(this._handler); @@ -68,14 +68,14 @@ void enableFlutterDriverExtension({ DataHandler handler }) { } /// Signature for functions that handle a command and return a result. -typedef CommandHandlerCallback = Future Function(Command c); +typedef Future CommandHandlerCallback(Command c); /// Signature for functions that deserialize a JSON map to a command object. -typedef CommandDeserializerCallback = Command Function(Map params); +typedef Command CommandDeserializerCallback(Map params); /// Signature for functions that run the given finder and return the [Element] /// found, if any, or null otherwise. -typedef FinderConstructor = Finder Function(SerializableFinder finder); +typedef Finder FinderConstructor(SerializableFinder finder); /// The class that manages communication between a Flutter Driver test and the /// application being remote-controlled, on the application side. diff --git a/packages/flutter_test/lib/src/finders.dart b/packages/flutter_test/lib/src/finders.dart index 335512f42f..c274d9f310 100644 --- a/packages/flutter_test/lib/src/finders.dart +++ b/packages/flutter_test/lib/src/finders.dart @@ -9,10 +9,10 @@ import 'package:meta/meta.dart'; import 'all_elements.dart'; /// Signature for [CommonFinders.byWidgetPredicate]. -typedef WidgetPredicate = bool Function(Widget widget); +typedef bool WidgetPredicate(Widget widget); /// Signature for [CommonFinders.byElementPredicate]. -typedef ElementPredicate = bool Function(Element element); +typedef bool ElementPredicate(Element element); /// Some frequently used widget [Finder]s. const CommonFinders find = const CommonFinders._(); diff --git a/packages/flutter_test/lib/src/matchers.dart b/packages/flutter_test/lib/src/matchers.dart index 37ac91009e..19e31fbbe1 100644 --- a/packages/flutter_test/lib/src/matchers.dart +++ b/packages/flutter_test/lib/src/matchers.dart @@ -636,7 +636,7 @@ class _HasGoodToStringDeep extends Matcher { /// /// This makes it useful for comparing numbers, [Color]s, [Offset]s and other /// sets of value for which a metric space is defined. -typedef DistanceFunction = num Function(T a, T b); +typedef num DistanceFunction(T a, T b); /// The type of a union of instances of [DistanceFunction] for various types /// T. @@ -649,7 +649,7 @@ typedef DistanceFunction = num Function(T a, T b); /// /// Calling an instance of this type must either be done dynamically, or by /// first casting it to a [DistanceFunction] for some concrete T. -typedef AnyDistanceFunction = num Function(Null a, Null b); +typedef num AnyDistanceFunction(Null a, Null b); const Map _kStandardDistanceFunctions = const { Color: _maxComponentColorDistance, diff --git a/packages/flutter_test/lib/src/test_exception_reporter.dart b/packages/flutter_test/lib/src/test_exception_reporter.dart index d579522bb8..df8386b846 100644 --- a/packages/flutter_test/lib/src/test_exception_reporter.dart +++ b/packages/flutter_test/lib/src/test_exception_reporter.dart @@ -7,7 +7,7 @@ import 'package:stack_trace/stack_trace.dart' as stack_trace; import 'package:test/test.dart' as test_package; /// Signature for the [reportTestException] callback. -typedef TestExceptionReporter = void Function(FlutterErrorDetails details, String testDescription); +typedef void TestExceptionReporter(FlutterErrorDetails details, String testDescription); /// A function that is called by the test framework when an unexpected error /// occurred during a test. diff --git a/packages/flutter_test/lib/src/test_pointer.dart b/packages/flutter_test/lib/src/test_pointer.dart index 10a1a27e7f..4328046c76 100644 --- a/packages/flutter_test/lib/src/test_pointer.dart +++ b/packages/flutter_test/lib/src/test_pointer.dart @@ -113,10 +113,10 @@ class TestPointer { /// Signature for a callback that can dispatch events and returns a future that /// completes when the event dispatch is complete. -typedef EventDispatcher = Future Function(PointerEvent event, HitTestResult result); +typedef Future EventDispatcher(PointerEvent event, HitTestResult result); /// Signature for callbacks that perform hit-testing at a given location. -typedef HitTester = HitTestResult Function(Offset location); +typedef HitTestResult HitTester(Offset location); /// A class for performing gestures in tests. /// diff --git a/packages/flutter_test/lib/src/widget_tester.dart b/packages/flutter_test/lib/src/widget_tester.dart index 742407d55b..cf72722c03 100644 --- a/packages/flutter_test/lib/src/widget_tester.dart +++ b/packages/flutter_test/lib/src/widget_tester.dart @@ -24,7 +24,7 @@ import 'test_text_input.dart'; export 'package:test/test.dart' hide expect; /// Signature for callback to [testWidgets] and [benchmarkWidgets]. -typedef WidgetTesterCallback = Future Function(WidgetTester widgetTester); +typedef Future WidgetTesterCallback(WidgetTester widgetTester); /// Runs the [callback] inside the Flutter test environment. /// @@ -608,7 +608,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker } } -typedef _TickerDisposeCallback = void Function(_TestTicker ticker); +typedef void _TickerDisposeCallback(_TestTicker ticker); class _TestTicker extends Ticker { _TestTicker(TickerCallback onTick, this._onDispose) : super(onTick); diff --git a/packages/flutter_tools/bin/xcode_backend.sh b/packages/flutter_tools/bin/xcode_backend.sh index 2a59407056..7dec223b25 100755 --- a/packages/flutter_tools/bin/xcode_backend.sh +++ b/packages/flutter_tools/bin/xcode_backend.sh @@ -102,6 +102,13 @@ BuildApp() { local_engine_flag="--local-engine=$LOCAL_ENGINE" fi + local preview_dart_2_flag="" + if [[ -n "$PREVIEW_DART_2" ]]; then + preview_dart_2_flag="--preview-dart-2" + else + preview_dart_2_flag="--no-preview-dart-2" + fi + local track_widget_creation_flag="" if [[ -n "$TRACK_WIDGET_CREATION" ]]; then track_widget_creation_flag="--track-widget-creation" @@ -120,6 +127,7 @@ BuildApp() { --${build_mode} \ --ios-arch="${archs}" \ ${local_engine_flag} \ + ${preview_dart_2_flag} \ ${track_widget_creation_flag} if [[ $? -ne 0 ]]; then @@ -159,10 +167,12 @@ BuildApp() { ${verbose_flag} \ build bundle \ --target="${target_path}" \ + --snapshot="${build_dir}/snapshot_blob.bin" \ --depfile="${build_dir}/snapshot_blob.bin.d" \ --asset-dir="${derived_dir}/flutter_assets" \ ${precompilation_flag} \ ${local_engine_flag} \ + ${preview_dart_2_flag} \ ${track_widget_creation_flag} if [[ $? -ne 0 ]]; then diff --git a/packages/flutter_tools/gradle/flutter.gradle b/packages/flutter_tools/gradle/flutter.gradle index e933a96f04..6f14e9cf89 100644 --- a/packages/flutter_tools/gradle/flutter.gradle +++ b/packages/flutter_tools/gradle/flutter.gradle @@ -260,6 +260,10 @@ class FlutterPlugin implements Plugin { if (project.hasProperty('verbose')) { verboseValue = project.property('verbose').toBoolean() } + Boolean previewDart2Value = true + if (project.hasProperty('preview-dart-2')) { + previewDart2Value = project.property('preview-dart-2').toBoolean() + } String[] fileSystemRootsValue = null if (project.hasProperty('filesystem-roots')) { fileSystemRootsValue = project.property('filesystem-roots').split('\\|') @@ -311,6 +315,7 @@ class FlutterPlugin implements Plugin { localEngineSrcPath this.localEngineSrcPath targetPath target verbose verboseValue + previewDart2 previewDart2Value fileSystemRoots fileSystemRootsValue fileSystemScheme fileSystemSchemeValue trackWidgetCreation trackWidgetCreationValue @@ -355,6 +360,8 @@ abstract class BaseFlutterTask extends DefaultTask { @Optional @Input Boolean verbose @Optional @Input + Boolean previewDart2 + @Optional @Input String[] fileSystemRoots @Optional @Input String fileSystemScheme @@ -376,10 +383,12 @@ abstract class BaseFlutterTask extends DefaultTask { if (buildMode != 'debug') { // For AOT builds, include the gen_snapshot depfile. FileCollection depfiles = project.files("${intermediateDir}/snapshot.d") - // Include the kernel compiler depfile, since kernel compile is the - // first stage of AOT build in this mode, and it includes all the - // Dart sources. - depfiles += project.files("${intermediateDir}/kernel_compile.d") + if (previewDart2) { + // For Dart 2, also include the kernel compiler depfile, since + // kernel compile is the first stage of AOT build in this mode, + // and it includes all the Dart sources. + depfiles += project.files("${intermediateDir}/kernel_compile.d") + } return depfiles } return project.files("${intermediateDir}/snapshot_blob.bin.d") @@ -406,6 +415,11 @@ abstract class BaseFlutterTask extends DefaultTask { args "--target", targetPath args "--target-platform", "android-arm" args "--output-dir", "${intermediateDir}" + if (previewDart2) { + args "--preview-dart-2" + } else { + args "--no-preview-dart-2" + } if (trackWidgetCreation) { args "--track-widget-creation" } @@ -438,6 +452,11 @@ abstract class BaseFlutterTask extends DefaultTask { if (verbose) { args "--verbose" } + if (previewDart2) { + args "--preview-dart-2" + } else { + args "--no-preview-dart-2" + } if (fileSystemRoots != null) { for (root in fileSystemRoots) { args "--filesystem-root", root @@ -456,6 +475,9 @@ abstract class BaseFlutterTask extends DefaultTask { args "--precompiled" } else { args "--depfile", "${intermediateDir}/snapshot_blob.bin.d" + if (!previewDart2) { + args "--snapshot", "${intermediateDir}/snapshot_blob.bin" + } } args "--asset-dir", "${intermediateDir}/flutter_assets" } @@ -511,7 +533,9 @@ class FlutterTask extends BaseFlutterTask { // We have a dependencies file. Add a dependency on gen_snapshot as well, since the // snapshots have to be rebuilt if it changes. sources += readDependencies(project.file("${intermediateDir}/gen_snapshot.d")) - sources += readDependencies(project.file("${intermediateDir}/frontend_server.d")) + if (previewDart2) { + sources += readDependencies(project.file("${intermediateDir}/frontend_server.d")) + } if (localEngineSrcPath != null) { sources += project.files("$localEngineSrcPath/$localEngine") } diff --git a/packages/flutter_tools/lib/src/android/gradle.dart b/packages/flutter_tools/lib/src/android/gradle.dart index 1dca022d8f..d4ef33f987 100644 --- a/packages/flutter_tools/lib/src/android/gradle.dart +++ b/packages/flutter_tools/lib/src/android/gradle.dart @@ -327,16 +327,21 @@ Future _buildGradleProjectV2(String gradle, BuildInfo buildInfo, String ta if (target != null) { command.add('-Ptarget=$target'); } - if (buildInfo.trackWidgetCreation) - command.add('-Ptrack-widget-creation=true'); - if (buildInfo.extraFrontEndOptions != null) - command.add('-Pextra-front-end-options=${buildInfo.extraFrontEndOptions}'); - if (buildInfo.extraGenSnapshotOptions != null) - command.add('-Pextra-gen-snapshot-options=${buildInfo.extraGenSnapshotOptions}'); - if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty) - command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); - if (buildInfo.fileSystemScheme != null) - command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}'); + if (buildInfo.previewDart2) { + command.add('-Ppreview-dart-2=true'); + if (buildInfo.trackWidgetCreation) + command.add('-Ptrack-widget-creation=true'); + if (buildInfo.extraFrontEndOptions != null) + command.add('-Pextra-front-end-options=${buildInfo.extraFrontEndOptions}'); + if (buildInfo.extraGenSnapshotOptions != null) + command.add('-Pextra-gen-snapshot-options=${buildInfo.extraGenSnapshotOptions}'); + if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty) + command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); + if (buildInfo.fileSystemScheme != null) + command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}'); + } else { + command.add('-Ppreview-dart-2=false'); + } if (buildInfo.buildSharedLibrary && androidSdk.ndk != null) { command.add('-Pbuild-shared-library=true'); } diff --git a/packages/flutter_tools/lib/src/base/build.dart b/packages/flutter_tools/lib/src/base/build.dart index 9cbc972d93..3c48c1feca 100644 --- a/packages/flutter_tools/lib/src/base/build.dart +++ b/packages/flutter_tools/lib/src/base/build.dart @@ -70,6 +70,70 @@ class GenSnapshot { } } +/// Dart snapshot builder. +/// +/// Builds Dart snapshots in one of three modes: +/// * Script snapshot: architecture-independent snapshot of a Dart script +/// and core libraries. +/// * AOT snapshot: architecture-specific ahead-of-time compiled snapshot +/// suitable for loading with `mmap`. +/// * Assembly AOT snapshot: architecture-specific ahead-of-time compile to +/// assembly suitable for compilation as a static or dynamic library. +class ScriptSnapshotter { + /// Builds an architecture-independent snapshot of the specified script. + Future build({ + @required String mainPath, + @required String snapshotPath, + @required String depfilePath, + @required String packagesPath + }) async { + final SnapshotType snapshotType = new SnapshotType(null, BuildMode.debug); + final String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData); + final String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData); + final List args = [ + '--snapshot_kind=script', + '--script_snapshot=$snapshotPath', + '--vm_snapshot_data=$vmSnapshotData', + '--isolate_snapshot_data=$isolateSnapshotData', + '--enable-mirrors=false', + mainPath, + ]; + + final Fingerprinter fingerprinter = new Fingerprinter( + fingerprintPath: '$depfilePath.fingerprint', + paths: [ + mainPath, + snapshotPath, + vmSnapshotData, + isolateSnapshotData, + ], + properties: { + 'buildMode': snapshotType.mode.toString(), + 'targetPlatform': snapshotType.platform?.toString() ?? '', + 'entryPoint': mainPath, + }, + depfilePaths: [depfilePath], + ); + if (await fingerprinter.doesFingerprintMatch()) { + printTrace('Skipping script snapshot build. Fingerprints match.'); + return 0; + } + + // Build the snapshot. + final int exitCode = await genSnapshot.run( + snapshotType: snapshotType, + packagesPath: packagesPath, + depfilePath: depfilePath, + additionalArgs: args, + ); + + if (exitCode != 0) + return exitCode; + await fingerprinter.writeFingerprint(); + return exitCode; + } +} + class AOTSnapshotter { /// Builds an architecture-specific ahead-of-time compiled snapshot of the specified script. Future build({ @@ -78,6 +142,7 @@ class AOTSnapshotter { @required String mainPath, @required String packagesPath, @required String outputPath, + @required bool previewDart2, @required bool buildSharedLibrary, IOSArch iosArch, List extraGenSnapshotOptions = const [], @@ -133,10 +198,12 @@ class AOTSnapshotter { '--embedder_entry_points_manifest=$ioEntryPoints', '--dependencies=$depfilePath', ]; - genSnapshotArgs.addAll([ - '--reify-generic-functions', - '--strong', - ]); + if (previewDart2) { + genSnapshotArgs.addAll([ + '--reify-generic-functions', + '--strong', + ]); + } if (extraGenSnapshotOptions != null && extraGenSnapshotOptions.isNotEmpty) { printTrace('Extra gen_snapshot options: $extraGenSnapshotOptions'); genSnapshotArgs.addAll(extraGenSnapshotOptions); @@ -191,6 +258,7 @@ class AOTSnapshotter { 'buildMode': buildMode.toString(), 'targetPlatform': platform.toString(), 'entryPoint': mainPath, + 'dart2': previewDart2.toString(), 'sharedLib': buildSharedLibrary.toString(), 'extraGenSnapshotOptions': extraGenSnapshotOptions.join(' '), }, diff --git a/packages/flutter_tools/lib/src/base/context.dart b/packages/flutter_tools/lib/src/base/context.dart index e62e376236..fff6975b32 100644 --- a/packages/flutter_tools/lib/src/base/context.dart +++ b/packages/flutter_tools/lib/src/base/context.dart @@ -11,7 +11,7 @@ import 'package:meta/meta.dart'; /// /// Generators are allowed to return `null`, in which case the context will /// store the `null` value as the value for that type. -typedef Generator = dynamic Function(); +typedef dynamic Generator(); /// An exception thrown by [AppContext] when you try to get a [Type] value from /// the context, and the instantiation of the value results in a dependency diff --git a/packages/flutter_tools/lib/src/base/fingerprint.dart b/packages/flutter_tools/lib/src/base/fingerprint.dart index 429130fa18..43f57b1c8f 100644 --- a/packages/flutter_tools/lib/src/base/fingerprint.dart +++ b/packages/flutter_tools/lib/src/base/fingerprint.dart @@ -13,7 +13,7 @@ import '../globals.dart'; import '../version.dart'; import 'file_system.dart'; -typedef FingerprintPathFilter = bool Function(String path); +typedef bool FingerprintPathFilter(String path); /// A tool that can be used to compute, compare, and write [Fingerprint]s for a /// set of input files and associated build settings. diff --git a/packages/flutter_tools/lib/src/base/io.dart b/packages/flutter_tools/lib/src/base/io.dart index 562f55171e..e397b6c85a 100644 --- a/packages/flutter_tools/lib/src/base/io.dart +++ b/packages/flutter_tools/lib/src/base/io.dart @@ -77,7 +77,7 @@ export 'dart:io' WebSocketTransformer; /// Exits the process with the given [exitCode]. -typedef ExitFunction = void Function(int exitCode); +typedef void ExitFunction(int exitCode); const ExitFunction _defaultExitFunction = io.exit; diff --git a/packages/flutter_tools/lib/src/base/logger.dart b/packages/flutter_tools/lib/src/base/logger.dart index 6c6e5136e2..7248c7793e 100644 --- a/packages/flutter_tools/lib/src/base/logger.dart +++ b/packages/flutter_tools/lib/src/base/logger.dart @@ -53,7 +53,7 @@ abstract class Logger { }); } -typedef _FinishCallback = void Function(); +typedef void _FinishCallback(); class StdoutLogger extends Logger { diff --git a/packages/flutter_tools/lib/src/base/net.dart b/packages/flutter_tools/lib/src/base/net.dart index 46551e2730..343898f14c 100644 --- a/packages/flutter_tools/lib/src/base/net.dart +++ b/packages/flutter_tools/lib/src/base/net.dart @@ -11,7 +11,7 @@ import 'io.dart'; const int kNetworkProblemExitCode = 50; -typedef HttpClientFactory = HttpClient Function(); +typedef HttpClient HttpClientFactory(); /// Download a file from the given URL and return the bytes. Future> fetchUrl(Uri url) async { diff --git a/packages/flutter_tools/lib/src/base/process.dart b/packages/flutter_tools/lib/src/base/process.dart index 1a142acd15..992687a2e7 100644 --- a/packages/flutter_tools/lib/src/base/process.dart +++ b/packages/flutter_tools/lib/src/base/process.dart @@ -11,10 +11,10 @@ import 'io.dart'; import 'process_manager.dart'; import 'utils.dart'; -typedef StringConverter = String Function(String string); +typedef String StringConverter(String string); /// A function that will be run before the VM exits. -typedef ShutdownHook = Future Function(); +typedef Future ShutdownHook(); // 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 diff --git a/packages/flutter_tools/lib/src/base/utils.dart b/packages/flutter_tools/lib/src/base/utils.dart index 8d78e9991a..aa1eaa9b10 100644 --- a/packages/flutter_tools/lib/src/base/utils.dart +++ b/packages/flutter_tools/lib/src/base/utils.dart @@ -233,7 +233,7 @@ class Uuid { Clock get clock => context[Clock]; -typedef AsyncCallback = Future Function(); +typedef Future AsyncCallback(); /// A [Timer] inspired class that: /// - has a different initial value for the first callback delay diff --git a/packages/flutter_tools/lib/src/build_info.dart b/packages/flutter_tools/lib/src/build_info.dart index e7f8b52c79..fbcab759a2 100644 --- a/packages/flutter_tools/lib/src/build_info.dart +++ b/packages/flutter_tools/lib/src/build_info.dart @@ -11,6 +11,7 @@ import 'globals.dart'; /// Information about a build to be performed or used. class BuildInfo { const BuildInfo(this.mode, this.flavor, { + this.previewDart2 = false, this.trackWidgetCreation = false, this.extraFrontEndOptions, this.extraGenSnapshotOptions, @@ -32,6 +33,9 @@ class BuildInfo { /// Mode-Flavor (e.g. Release-Paid). final String flavor; + /// Whether build should be done using Dart2 Frontend parser. + final bool previewDart2; + final List fileSystemRoots; final String fileSystemScheme; @@ -89,6 +93,7 @@ class BuildInfo { BuildInfo withTargetPlatform(TargetPlatform targetPlatform) => new BuildInfo(mode, flavor, + previewDart2: previewDart2, trackWidgetCreation: trackWidgetCreation, extraFrontEndOptions: extraFrontEndOptions, extraGenSnapshotOptions: extraGenSnapshotOptions, diff --git a/packages/flutter_tools/lib/src/bundle.dart b/packages/flutter_tools/lib/src/bundle.dart index 42f0687907..02a65101d4 100644 --- a/packages/flutter_tools/lib/src/bundle.dart +++ b/packages/flutter_tools/lib/src/bundle.dart @@ -6,6 +6,7 @@ import 'dart:async'; import 'artifacts.dart'; import 'asset.dart'; +import 'base/build.dart'; import 'base/common.dart'; import 'base/file_system.dart'; import 'build_info.dart'; @@ -23,6 +24,7 @@ String get defaultApplicationKernelPath => fs.path.join(getBuildDirectory(), 'ap const String defaultPrivateKeyPath = 'privatekey.der'; const String _kKernelKey = 'kernel_blob.bin'; +const String _kSnapshotKey = 'snapshot_blob.bin'; const String _kVMSnapshotData = 'vm_snapshot_data'; const String _kIsolateSnapshotData = 'isolate_snapshot_data'; const String _kDylibKey = 'libapp.so'; @@ -31,11 +33,13 @@ const String _kPlatformKernelKey = 'platform.dill'; Future build({ String mainPath = defaultMainPath, String manifestPath = defaultManifestPath, + String snapshotPath, String applicationKernelFilePath, String depfilePath, String privateKeyPath = defaultPrivateKeyPath, String assetDirPath, String packagesPath, + bool previewDart2 = false, bool precompiledSnapshot = false, bool reportLicensedPackages = false, bool trackWidgetCreation = false, @@ -43,13 +47,32 @@ Future build({ List fileSystemRoots, String fileSystemScheme, }) async { + snapshotPath ??= defaultSnapshotPath; depfilePath ??= defaultDepfilePath; assetDirPath ??= getAssetBuildDirectory(); packagesPath ??= fs.path.absolute(PackageMap.globalPackagesPath); applicationKernelFilePath ??= defaultApplicationKernelPath; + File snapshotFile; + + if (!precompiledSnapshot && !previewDart2) { + ensureDirectoryExists(snapshotPath); + + // In a precompiled snapshot, the instruction buffer contains script + // content equivalents + final int result = await new ScriptSnapshotter().build( + mainPath: mainPath, + snapshotPath: snapshotPath, + depfilePath: depfilePath, + packagesPath: packagesPath, + ); + if (result != 0) + throwToolExit('Failed to run the Flutter compiler. Exit code: $result', exitCode: result); + + snapshotFile = fs.file(snapshotPath); + } DevFSContent kernelContent; - if (!precompiledSnapshot) { + if (!precompiledSnapshot && previewDart2) { if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty) printTrace('Extra front-end options: $extraFrontEndOptions'); ensureDirectoryExists(applicationKernelFilePath); @@ -86,6 +109,7 @@ Future build({ await assemble( assetBundle: assets, kernelContent: kernelContent, + snapshotFile: snapshotFile, privateKeyPath: privateKeyPath, assetDirPath: assetDirPath, ); @@ -119,6 +143,7 @@ Future buildAssets({ Future assemble({ AssetBundle assetBundle, DevFSContent kernelContent, + File snapshotFile, File dylibFile, String privateKeyPath = defaultPrivateKeyPath, String assetDirPath, @@ -127,16 +152,21 @@ Future assemble({ printTrace('Building bundle'); final Map assetEntries = new Map.from(assetBundle.entries); + final String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData); + final String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData); if (kernelContent != null) { final String platformKernelDill = artifacts.getArtifactPath(Artifact.platformKernelDill); - final String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData); - final String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData); assetEntries[_kKernelKey] = kernelContent; assetEntries[_kPlatformKernelKey] = new DevFSFileContent(fs.file(platformKernelDill)); assetEntries[_kVMSnapshotData] = new DevFSFileContent(fs.file(vmSnapshotData)); assetEntries[_kIsolateSnapshotData] = new DevFSFileContent(fs.file(isolateSnapshotData)); } + if (snapshotFile != null) { + assetEntries[_kSnapshotKey] = new DevFSFileContent(snapshotFile); + assetEntries[_kVMSnapshotData] = new DevFSFileContent(fs.file(vmSnapshotData)); + assetEntries[_kIsolateSnapshotData] = new DevFSFileContent(fs.file(isolateSnapshotData)); + } if (dylibFile != null) assetEntries[_kDylibKey] = new DevFSFileContent(dylibFile); diff --git a/packages/flutter_tools/lib/src/commands/analyze.dart b/packages/flutter_tools/lib/src/commands/analyze.dart index 7941f799cd..42e8a326fb 100644 --- a/packages/flutter_tools/lib/src/commands/analyze.dart +++ b/packages/flutter_tools/lib/src/commands/analyze.dart @@ -26,6 +26,8 @@ class AnalyzeCommand extends FlutterCommand { argParser.addFlag('watch', help: 'Run analysis continuously, watching the filesystem for changes.', negatable: false); + argParser.addFlag('preview-dart-2', + defaultsTo: true, help: 'Preview Dart 2.0 functionality.'); argParser.addOption('write', valueHelp: 'file', help: 'Also output the results to a file. This is useful with --watch ' @@ -85,6 +87,7 @@ class AnalyzeCommand extends FlutterCommand { argResults, runner.getRepoRoots(), runner.getRepoPackages(), + previewDart2: argResults['preview-dart-2'], ).analyze(); } else { return new AnalyzeOnce( @@ -92,6 +95,7 @@ class AnalyzeCommand extends FlutterCommand { runner.getRepoRoots(), runner.getRepoPackages(), workingDirectory: workingDirectory, + previewDart2: argResults['preview-dart-2'], ).analyze(); } } diff --git a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart index aad07d3369..a31eff324b 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart @@ -19,10 +19,13 @@ import '../globals.dart'; import 'analyze_base.dart'; class AnalyzeContinuously extends AnalyzeBase { - AnalyzeContinuously(ArgResults argResults, this.repoRoots, this.repoPackages) : super(argResults); + AnalyzeContinuously(ArgResults argResults, this.repoRoots, this.repoPackages, { + this.previewDart2 = false, + }) : super(argResults); final List repoRoots; final List repoPackages; + final bool previewDart2; String analysisTarget; bool firstAnalysis = true; @@ -57,7 +60,7 @@ class AnalyzeContinuously extends AnalyzeBase { final String sdkPath = argResults['dart-sdk'] ?? sdk.dartSdkPath; - final AnalysisServer server = new AnalysisServer(sdkPath, directories); + final AnalysisServer server = new AnalysisServer(sdkPath, directories, previewDart2: previewDart2); server.onAnalyzing.listen((bool isAnalyzing) => _handleAnalysisStatus(server, isAnalyzing)); server.onErrors.listen(_handleAnalysisErrors); diff --git a/packages/flutter_tools/lib/src/commands/analyze_once.dart b/packages/flutter_tools/lib/src/commands/analyze_once.dart index 3866596296..b8840a90ee 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_once.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_once.dart @@ -24,6 +24,7 @@ class AnalyzeOnce extends AnalyzeBase { this.repoRoots, this.repoPackages, { this.workingDirectory, + this.previewDart2 = false, }) : super(argResults); final List repoRoots; @@ -32,6 +33,8 @@ class AnalyzeOnce extends AnalyzeBase { /// The working directory for testing analysis using dartanalyzer. final Directory workingDirectory; + final bool previewDart2; + @override Future analyze() async { final String currentDirectory = @@ -88,6 +91,7 @@ class AnalyzeOnce extends AnalyzeBase { final AnalysisServer server = new AnalysisServer( sdkPath, directories.toList(), + previewDart2: previewDart2, ); StreamSubscription subscription; diff --git a/packages/flutter_tools/lib/src/commands/build_aot.dart b/packages/flutter_tools/lib/src/commands/build_aot.dart index bd4c3bf4db..2d9fe924c9 100644 --- a/packages/flutter_tools/lib/src/commands/build_aot.dart +++ b/packages/flutter_tools/lib/src/commands/build_aot.dart @@ -28,6 +28,11 @@ class BuildAotCommand extends BuildSubCommand { allowed: ['android-arm', 'android-arm64', 'ios'] ) ..addFlag('quiet', defaultsTo: false) + ..addFlag('preview-dart-2', + defaultsTo: true, + hide: !verboseHelp, + help: 'Preview Dart 2.0 functionality.', + ) ..addFlag('build-shared-library', negatable: false, defaultsTo: false, @@ -74,20 +79,23 @@ class BuildAotCommand extends BuildSubCommand { } final String outputPath = argResults['output-dir'] ?? getAotBuildDirectory(); try { + final bool previewDart2 = argResults['preview-dart-2']; String mainPath = findMainDartFile(targetFile); final AOTSnapshotter snapshotter = new AOTSnapshotter(); - // Compile to kernel. - mainPath = await snapshotter.compileKernel( - platform: platform, - buildMode: buildMode, - mainPath: mainPath, - outputPath: outputPath, - extraFrontEndOptions: argResults[FlutterOptions.kExtraFrontEndOptions], - ); - if (mainPath == null) { - printError('Compiler terminated unexpectedly.'); - return; + // Compile to kernel, if Dart 2. + if (previewDart2) { + mainPath = await snapshotter.compileKernel( + platform: platform, + buildMode: buildMode, + mainPath: mainPath, + outputPath: outputPath, + extraFrontEndOptions: argResults[FlutterOptions.kExtraFrontEndOptions], + ); + if (mainPath == null) { + printError('Compiler terminated unexpectedly.'); + return; + } } // Build AOT snapshot. @@ -108,6 +116,7 @@ class BuildAotCommand extends BuildSubCommand { mainPath: mainPath, packagesPath: PackageMap.globalPackagesPath, outputPath: outputPath, + previewDart2: previewDart2, buildSharedLibrary: false, extraGenSnapshotOptions: argResults[FlutterOptions.kExtraGenSnapshotOptions], ).then((int buildExitCode) { @@ -134,6 +143,7 @@ class BuildAotCommand extends BuildSubCommand { mainPath: mainPath, packagesPath: PackageMap.globalPackagesPath, outputPath: outputPath, + previewDart2: previewDart2, buildSharedLibrary: argResults['build-shared-library'], extraGenSnapshotOptions: argResults[FlutterOptions.kExtraGenSnapshotOptions], ); diff --git a/packages/flutter_tools/lib/src/commands/build_apk.dart b/packages/flutter_tools/lib/src/commands/build_apk.dart index 0c9ff1a4cb..e6e2cc54f3 100644 --- a/packages/flutter_tools/lib/src/commands/build_apk.dart +++ b/packages/flutter_tools/lib/src/commands/build_apk.dart @@ -17,6 +17,11 @@ class BuildApkCommand extends BuildSubCommand { usesBuildNameOption(); argParser + ..addFlag('preview-dart-2', + defaultsTo: true, + hide: !verboseHelp, + help: 'Preview Dart 2.0 functionality.', + ) ..addFlag('track-widget-creation', negatable: false, hide: !verboseHelp) ..addFlag('build-shared-library', negatable: false, diff --git a/packages/flutter_tools/lib/src/commands/build_bundle.dart b/packages/flutter_tools/lib/src/commands/build_bundle.dart index 581bc165f8..811433414f 100644 --- a/packages/flutter_tools/lib/src/commands/build_bundle.dart +++ b/packages/flutter_tools/lib/src/commands/build_bundle.dart @@ -19,8 +19,14 @@ class BuildBundleCommand extends BuildSubCommand { ..addOption('asset-base', help: 'Ignored. Will be removed.', hide: !verboseHelp) ..addOption('manifest', defaultsTo: defaultManifestPath) ..addOption('private-key', defaultsTo: defaultPrivateKeyPath) + ..addOption('snapshot', defaultsTo: defaultSnapshotPath) ..addOption('depfile', defaultsTo: defaultDepfilePath) ..addOption('kernel-file', defaultsTo: defaultApplicationKernelPath) + ..addFlag('preview-dart-2', + defaultsTo: true, + hide: !verboseHelp, + help: 'Preview Dart 2.0 functionality.', + ) ..addFlag('track-widget-creation', hide: !verboseHelp, help: 'Track widget creation locations. Requires Dart 2.0 functionality.', @@ -66,10 +72,12 @@ class BuildBundleCommand extends BuildSubCommand { await build( mainPath: targetFile, manifestPath: argResults['manifest'], + snapshotPath: argResults['snapshot'], applicationKernelFilePath: argResults['kernel-file'], depfilePath: argResults['depfile'], privateKeyPath: argResults['private-key'], assetDirPath: argResults['asset-dir'], + previewDart2: argResults['preview-dart-2'], precompiledSnapshot: argResults['precompiled'], reportLicensedPackages: argResults['report-licensed-packages'], trackWidgetCreation: argResults['track-widget-creation'], diff --git a/packages/flutter_tools/lib/src/commands/build_ios.dart b/packages/flutter_tools/lib/src/commands/build_ios.dart index db2fe23891..5196e1bf59 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios.dart @@ -38,7 +38,11 @@ class BuildIOSCommand extends BuildSubCommand { ..addFlag('codesign', defaultsTo: true, help: 'Codesign the application bundle (only available on device builds).', - ); + ) + ..addFlag('preview-dart-2', + defaultsTo: true, + hide: !verboseHelp, + help: 'Preview Dart 2.0 functionality.'); } @override diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index 15b174d066..a675722990 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -73,9 +73,9 @@ class DaemonCommand extends FlutterCommand { } } -typedef DispatchCommand = void Function(Map command); +typedef void DispatchCommand(Map command); -typedef CommandHandler = Future Function(Map args); +typedef Future CommandHandler(Map args); class Daemon { Daemon( @@ -334,6 +334,7 @@ class AppDomain extends Domain { final BuildInfo buildInfo = new BuildInfo( getBuildModeForName(mode) ?? BuildMode.debug, flavor, + previewDart2: _getBoolArg(args, 'preview-dart-2'), ); DebuggingOptions options; if (buildInfo.isRelease) { @@ -384,6 +385,7 @@ class AppDomain extends Domain { final FlutterDevice flutterDevice = new FlutterDevice( device, + previewDart2: options.buildInfo.previewDart2, trackWidgetCreation: trackWidgetCreation, dillOutputPath: dillOutputPath, ); @@ -563,7 +565,7 @@ class AppDomain extends Domain { } } -typedef _DeviceEventHandler = void Function(Device device); +typedef void _DeviceEventHandler(Device device); /// This domain lets callers list and monitor connected devices. /// diff --git a/packages/flutter_tools/lib/src/commands/drive.dart b/packages/flutter_tools/lib/src/commands/drive.dart index ee39c9dd3b..bec0e38530 100644 --- a/packages/flutter_tools/lib/src/commands/drive.dart +++ b/packages/flutter_tools/lib/src/commands/drive.dart @@ -62,7 +62,10 @@ class DriveCommand extends RunCommandBase { 'just before the extension, so e.g. if the target is "lib/main.dart", the\n' 'driver will be "test_driver/main_test.dart".', valueHelp: 'path', - ); + ) + ..addFlag('preview-dart-2', + defaultsTo: true, + help: 'Preview Dart 2.0 functionality.'); } @override @@ -120,7 +123,7 @@ class DriveCommand extends RunCommandBase { Cache.releaseLockEarly(); try { - await testRunner([testFile], observatoryUri); + await testRunner([testFile], observatoryUri, argResults['preview-dart-2']); } catch (error, stackTrace) { if (error is ToolExit) rethrow; @@ -179,7 +182,7 @@ class DriveCommand extends RunCommandBase { } /// Finds a device to test on. May launch a simulator, if necessary. -typedef TargetDeviceFinder = Future Function(); +typedef Future TargetDeviceFinder(); TargetDeviceFinder targetDeviceFinder = findTargetDevice; void restoreTargetDeviceFinder() { targetDeviceFinder = findTargetDevice; @@ -213,7 +216,7 @@ Future findTargetDevice() async { } /// Starts the application on the device given command configuration. -typedef AppStarter = Future Function(DriveCommand command); +typedef Future AppStarter(DriveCommand command); AppStarter appStarter = _startApp; // (mutable for testing) void restoreAppStarter() { @@ -272,20 +275,24 @@ Future _startApp(DriveCommand command) async { } /// Runs driver tests. -typedef TestRunner = Future Function(List testArgs, String observatoryUri); +typedef Future TestRunner(List testArgs, String observatoryUri, bool previewDart2); TestRunner testRunner = _runTests; void restoreTestRunner() { testRunner = _runTests; } -Future _runTests(List testArgs, String observatoryUri) async { +Future _runTests(List testArgs, String observatoryUri, bool previewDart2) async { printTrace('Running driver tests.'); PackageMap.globalPackagesPath = fs.path.normalize(fs.path.absolute(PackageMap.globalPackagesPath)); final List args = testArgs.toList() ..add('--packages=${PackageMap.globalPackagesPath}') - ..add('-rexpanded') - ..add('--preview-dart-2'); + ..add('-rexpanded'); + if (previewDart2) { + args.add('--preview-dart-2'); + } else { + args.add('--no-preview-dart-2'); + } final String dartVmPath = fs.path.join(dartSdkPath, 'bin', 'dart'); final int result = await runCommandAndStreamOutput( @@ -298,7 +305,7 @@ Future _runTests(List testArgs, String observatoryUri) async { /// Stops the application. -typedef AppStopper = Future Function(DriveCommand command); +typedef Future AppStopper(DriveCommand command); AppStopper appStopper = _stopApp; void restoreAppStopper() { appStopper = _stopApp; diff --git a/packages/flutter_tools/lib/src/commands/fuchsia_reload.dart b/packages/flutter_tools/lib/src/commands/fuchsia_reload.dart index cd45e83428..17723c5275 100644 --- a/packages/flutter_tools/lib/src/commands/fuchsia_reload.dart +++ b/packages/flutter_tools/lib/src/commands/fuchsia_reload.dart @@ -53,6 +53,10 @@ class FuchsiaReloadCommand extends FlutterCommand { argParser.addOption('name-override', abbr: 'n', help: 'On-device name of the application binary.'); + argParser.addFlag('preview-dart-2', + abbr: '2', + defaultsTo: false, + help: 'Preview Dart 2.0 functionality.'); argParser.addOption('target', abbr: 't', defaultsTo: bundle.defaultMainPath, @@ -128,8 +132,13 @@ class FuchsiaReloadCommand extends FlutterCommand { final List observatoryUris = fullAddresses.map( (String a) => Uri.parse('http://$a') ).toList(); - final FuchsiaDevice device = new FuchsiaDevice(fullAddresses[0], name: _address); - final FlutterDevice flutterDevice = new FlutterDevice(device, trackWidgetCreation: false); + final FuchsiaDevice device = new FuchsiaDevice( + fullAddresses[0], name: _address); + final FlutterDevice flutterDevice = new FlutterDevice( + device, + trackWidgetCreation: false, + previewDart2: false, + ); flutterDevice.observatoryUris = observatoryUris; final HotRunner hotRunner = new HotRunner( [flutterDevice], diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 076502a3ee..2fb8efe00f 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -120,6 +120,11 @@ class RunCommand extends RunCommandBase { hide: !verboseHelp, help: 'Specify a pre-built application binary to use when running.', ) + ..addFlag('preview-dart-2', + defaultsTo: true, + hide: !verboseHelp, + help: 'Preview Dart 2.0 functionality.', + ) ..addFlag('track-widget-creation', hide: !verboseHelp, help: 'Track widget creation locations. Requires Dart 2.0 functionality.', @@ -342,6 +347,7 @@ class RunCommand extends RunCommandBase { final List flutterDevices = devices.map((Device device) { return new FlutterDevice( device, + previewDart2: argResults['preview-dart-2'], trackWidgetCreation: argResults['track-widget-creation'], dillOutputPath: argResults['output-dill'], fileSystemRoots: argResults['filesystem-root'], diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index 49320d1e39..a9252d27fc 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -68,6 +68,11 @@ class TestCommand extends FlutterCommand { help: 'Handle machine structured JSON command input\n' 'and provide output and progress in machine friendly format.', ) + ..addFlag('preview-dart-2', + defaultsTo: true, + hide: !verboseHelp, + help: 'Preview Dart 2.0 functionality.', + ) ..addFlag('track-widget-creation', negatable: false, hide: !verboseHelp, @@ -218,6 +223,7 @@ class TestCommand extends FlutterCommand { startPaused: startPaused, ipv6: argResults['ipv6'], machine: machine, + previewDart2: argResults['preview-dart-2'], trackWidgetCreation: argResults['track-widget-creation'], updateGoldens: argResults['update-goldens'], ); diff --git a/packages/flutter_tools/lib/src/compile.dart b/packages/flutter_tools/lib/src/compile.dart index 9fb660f90b..d01745956e 100644 --- a/packages/flutter_tools/lib/src/compile.dart +++ b/packages/flutter_tools/lib/src/compile.dart @@ -17,7 +17,7 @@ import 'globals.dart'; KernelCompiler get kernelCompiler => context[KernelCompiler]; -typedef CompilerMessageConsumer = void Function(String message); +typedef void CompilerMessageConsumer(String message); class CompilerOutput { final String outputFilename; diff --git a/packages/flutter_tools/lib/src/dart/analysis.dart b/packages/flutter_tools/lib/src/dart/analysis.dart index cbf0f2b0cb..65e6d10a47 100644 --- a/packages/flutter_tools/lib/src/dart/analysis.dart +++ b/packages/flutter_tools/lib/src/dart/analysis.dart @@ -13,10 +13,11 @@ import '../base/process_manager.dart'; import '../globals.dart'; class AnalysisServer { - AnalysisServer(this.sdkPath, this.directories); + AnalysisServer(this.sdkPath, this.directories, {this.previewDart2 = false}); final String sdkPath; final List directories; + final bool previewDart2; Process _process; final StreamController _analyzingController = @@ -34,9 +35,14 @@ class AnalysisServer { snapshot, '--sdk', sdkPath, - '--preview-dart-2', ]; + if (previewDart2) { + command.add('--preview-dart-2'); + } else { + command.add('--no-preview-dart-2'); + } + printTrace('dart ${command.skip(1).join(' ')}'); _process = await processManager.start(command); // This callback hookup can't throw. diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index 1a429d27d4..d633374aa0 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart @@ -121,7 +121,7 @@ Future pubGet({ throwToolExit('$directory: pub did not update .packages file (pubspec.yaml file has a newer timestamp)'); } -typedef MessageFilter = String Function(String message); +typedef String MessageFilter(String message); /// Runs pub in 'batch' mode, forwarding complete lines written by pub to its /// stdout/stderr streams to the corresponding stream of this process, optionally diff --git a/packages/flutter_tools/lib/src/devfs.dart b/packages/flutter_tools/lib/src/devfs.dart index 3724c9221c..dce136c2a0 100644 --- a/packages/flutter_tools/lib/src/devfs.dart +++ b/packages/flutter_tools/lib/src/devfs.dart @@ -6,7 +6,6 @@ import 'dart:async'; import 'dart:convert' show base64, utf8; import 'package:json_rpc_2/json_rpc_2.dart' as rpc; -import 'package:meta/meta.dart'; import 'asset.dart'; import 'base/context.dart'; @@ -402,14 +401,14 @@ class DevFS { /// /// Returns the number of bytes synced. Future update({ - @required String mainPath, + String mainPath, String target, AssetBundle bundle, DateTime firstBuildTime, bool bundleFirstUpload = false, bool bundleDirty = false, Set fileFilter, - @required ResidentCompiler generator, + ResidentCompiler generator, String dillOutputPath, bool fullRestart = false, String projectRootPath, @@ -425,9 +424,10 @@ class DevFS { await _scanDirectory(rootDirectory, recursive: true, fileFilter: fileFilter); + final bool previewDart2 = generator != null; if (fs.isFileSync(_packagesFilePath)) { printTrace('Scanning package files'); - await _scanPackages(fileFilter); + await _scanPackages(fileFilter, previewDart2); } if (bundle != null) { printTrace('Scanning asset files'); @@ -468,9 +468,10 @@ class DevFS { String archivePath; if (deviceUri.path.startsWith(assetBuildDirPrefix)) archivePath = deviceUri.path.substring(assetBuildDirPrefix.length); - // When doing full restart in, copy content so that isModified does not - // reset last check timestamp because we want to report all modified - // files to incremental compiler next time user does hot reload. + // When doing full restart in preview-dart-2 mode, copy content so + // that isModified does not reset last check timestamp because we + // want to report all modified files to incremental compiler next time + // user does hot reload. if (content.isModified || ((bundleDirty || bundleFirstUpload) && archivePath != null)) { dirtyEntries[deviceUri] = content; numBytes += content.size; @@ -478,40 +479,35 @@ class DevFS { assetPathsToEvict.add(archivePath); } }); - - // We run generator even if [dirtyEntries] was empty because we want to - // keep logic of accepting/rejecting generator's output simple: we must - // accept/reject generator's output after every [update] call. Incremental - // run with no changes is supposed to be fast (considering that it is - // initiated by user key press). - final List invalidatedFiles = []; - final Set filesUris = new Set(); - for (Uri uri in dirtyEntries.keys) { - if (!uri.path.startsWith(assetBuildDirPrefix)) { - final DevFSContent content = dirtyEntries[uri]; - if (content is DevFSFileContent) { - filesUris.add(uri); - invalidatedFiles.add(content.file.uri.toString()); - numBytes -= content.size; + if (previewDart2) { + // We run generator even if [dirtyEntries] was empty because we want + // to keep logic of accepting/rejecting generator's output simple: + // we must accept/reject generator's output after every [update] call. + // Incremental run with no changes is supposed to be fast (considering + // that it is initiated by user key press). + final List invalidatedFiles = []; + final Set filesUris = new Set(); + for (Uri uri in dirtyEntries.keys.toList()) { + if (!uri.path.startsWith(assetBuildDirPrefix)) { + final DevFSContent content = dirtyEntries[uri]; + if (content is DevFSFileContent) { + filesUris.add(uri); + invalidatedFiles.add(content.file.uri.toString()); + numBytes -= content.size; + } } } - } - - // No need to send source files because all compilation is done on the - // host and result of compilation is single kernel file. - filesUris.forEach(dirtyEntries.remove); - - printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files'); - if (fullRestart) { - generator.reset(); - } - if (invalidatedFiles.isNotEmpty) { - final CompilerOutput compilerOutput = await generator.recompile( - mainPath, - invalidatedFiles, - outputPath: dillOutputPath ?? fs.path.join(getBuildDirectory(), 'app.dill'), - packagesFilePath : _packagesFilePath, - ); + // No need to send source files because all compilation is done on the + // host and result of compilation is single kernel file. + filesUris.forEach(dirtyEntries.remove); + printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files'); + if (fullRestart) { + generator.reset(); + } + final CompilerOutput compilerOutput = + await generator.recompile(mainPath, invalidatedFiles, + outputPath: dillOutputPath ?? fs.path.join(getBuildDirectory(), 'app.dill'), + packagesFilePath : _packagesFilePath); final String compiledBinary = compilerOutput?.outputFilename; if (compiledBinary != null && compiledBinary.isNotEmpty) { final String entryUri = projectRootPath != null ? @@ -701,7 +697,7 @@ class DevFS { ); } - Future _scanPackages(Set fileFilter) async { + Future _scanPackages(Set fileFilter, bool previewDart2) async { StringBuffer sb; final PackageMap packageMap = new PackageMap(_packagesFilePath); @@ -734,6 +730,22 @@ class DevFS { sb.writeln('$packageName:$directoryUriOnDevice'); } } + if (previewDart2) { + // When in previewDart2 mode we don't update .packages-file entry + // so actual file will get invalidated in frontend. + // We don't need to synthesize device-correct .packages file because + // it is not going to be used on the device anyway - compilation + // is done on the host. + return; + } + if (sb != null) { + final DevFSContent content = _entries[fs.path.toUri('.packages')]; + if (content is DevFSStringContent && content.string == sb.toString()) { + content._exists = true; + return; + } + _entries[fs.path.toUri('.packages')] = new DevFSStringContent(sb.toString()); + } } } /// Converts a platform-specific file path to a platform-independent Uri path. diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index 5c8db0d0a6..44c4f14432 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -246,6 +246,7 @@ Future buildXcodeProject({ projectPath: fs.currentDirectory.path, buildInfo: buildInfo, targetOverride: targetOverride, + previewDart2: buildInfo.previewDart2, ); if (hasPlugins()) { @@ -427,7 +428,7 @@ Future buildXcodeProject({ outputDir = expectedOutputDirectory.replaceFirst('/$configuration-', '/'); if (fs.isDirectorySync(outputDir)) { // Previous output directory might have incompatible artifacts - // (for example, kernel binary files produced from previous run). + // (for example, kernel binary files produced from previous `--preview-dart-2` run). fs.directory(outputDir).deleteSync(recursive: true); } copyDirectorySync(fs.directory(expectedOutputDirectory), fs.directory(outputDir)); diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart index cf31675fbd..99be8fcc0a 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart @@ -362,6 +362,7 @@ class IOSSimulator extends Device { // The build mode for the simulator is always debug. final BuildInfo debugBuildInfo = new BuildInfo(BuildMode.debug, buildInfo.flavor, + previewDart2: buildInfo.previewDart2, trackWidgetCreation: buildInfo.trackWidgetCreation, extraFrontEndOptions: buildInfo.extraFrontEndOptions, extraGenSnapshotOptions: buildInfo.extraGenSnapshotOptions, @@ -389,10 +390,12 @@ class IOSSimulator extends Device { } Future _sideloadUpdatedAssetsForInstalledApplicationBundle(ApplicationPackage app, BuildInfo buildInfo, String mainPath) { - // Run compiler to produce kernel file for the application. + // When running in previewDart2 mode, we still need to run compiler to + // produce kernel file for the application. return bundle.build( mainPath: mainPath, - precompiledSnapshot: false, + precompiledSnapshot: !buildInfo.previewDart2, + previewDart2: buildInfo.previewDart2, trackWidgetCreation: buildInfo.trackWidgetCreation, ); } diff --git a/packages/flutter_tools/lib/src/ios/xcodeproj.dart b/packages/flutter_tools/lib/src/ios/xcodeproj.dart index 02cfd883ae..4dfd917ff6 100644 --- a/packages/flutter_tools/lib/src/ios/xcodeproj.dart +++ b/packages/flutter_tools/lib/src/ios/xcodeproj.dart @@ -42,6 +42,7 @@ Future generateXcodeProperties(String projectPath) async { projectPath: projectPath, buildInfo: BuildInfo.debug, targetOverride: bundle.defaultMainPath, + previewDart2: false, ); } } @@ -54,6 +55,7 @@ Future updateGeneratedXcodeProperties({ @required String projectPath, @required BuildInfo buildInfo, String targetOverride, + @required bool previewDart2, }) async { final StringBuffer localsBuffer = new StringBuffer(); @@ -111,6 +113,10 @@ Future updateGeneratedXcodeProperties({ localsBuffer.writeln('ARCHS=$arch'); } + if (previewDart2) { + localsBuffer.writeln('PREVIEW_DART_2=true'); + } + if (buildInfo.trackWidgetCreation) { localsBuffer.writeln('TRACK_WIDGET_CREATION=true'); } diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index 158c7ec5e5..f6da760f2a 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -34,7 +34,7 @@ class FlutterDevice { List vmServices; DevFS devFS; ApplicationPackage package; - final ResidentCompiler generator; + ResidentCompiler generator; String dillOutputPath; List fileSystemRoots; String fileSystemScheme; @@ -42,15 +42,20 @@ class FlutterDevice { StreamSubscription _loggingSubscription; FlutterDevice(this.device, { + @required bool previewDart2, @required bool trackWidgetCreation, this.dillOutputPath, this.fileSystemRoots, this.fileSystemScheme, - }) : generator = new ResidentCompiler( - artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath), - trackWidgetCreation: trackWidgetCreation, - fileSystemRoots: fileSystemRoots, - fileSystemScheme: fileSystemScheme); + }) { + if (previewDart2) { + generator = new ResidentCompiler( + artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath), + trackWidgetCreation: trackWidgetCreation, + fileSystemRoots: fileSystemRoots, fileSystemScheme: fileSystemScheme + ); + } + } String viewFilter; @@ -407,9 +412,9 @@ class FlutterDevice { void updateReloadStatus(bool wasReloadSuccessful) { if (wasReloadSuccessful) - generator.accept(); + generator?.accept(); else - generator.reject(); + generator?.reject(); } } diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index a451d8aaff..9eeb8dfde3 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -412,11 +412,15 @@ class HotRunner extends ResidentRunner { } // We are now running from source. _runningFromSnapshot = false; - - await _launchFromDevFS('$mainPath.dill'); + final String launchPath = debuggingOptions.buildInfo.previewDart2 + ? mainPath + '.dill' + : mainPath; + await _launchFromDevFS(launchPath); restartTimer.stop(); - printTrace('Restart performed in ${getElapsedAsMilliseconds(restartTimer.elapsed)}.'); - + printTrace('Restart performed in ' + '${getElapsedAsMilliseconds(restartTimer.elapsed)}.'); + // We are now running from sources. + _runningFromSnapshot = false; _addBenchmarkData('hotRestartMillisecondsToFrame', restartTimer.elapsed.inMilliseconds); flutterUsage.sendEvent('hot', 'restart'); @@ -506,6 +510,14 @@ class HotRunner extends ResidentRunner { } } + String _uriToRelativePath(Uri uri) { + final String path = uri.toString(); + final String base = new Uri.file(projectRootPath).toString(); + if (path.startsWith(base)) + return path.substring(base.length + 1); + return path; + } + Future _reloadSources({ bool pause = false }) async { for (FlutterDevice device in flutterDevices) { for (FlutterView view in device.views) { @@ -525,6 +537,7 @@ class HotRunner extends ResidentRunner { // change from host path to a device path). Subsequent reloads will // not be affected, so we resume reporting reload times on the second // reload. + final bool reportUnused = !debuggingOptions.buildInfo.previewDart2; final bool shouldReportReloadTime = !_runningFromSnapshot; final Stopwatch reloadTimer = new Stopwatch()..start(); @@ -538,7 +551,10 @@ class HotRunner extends ResidentRunner { String reloadMessage; final Stopwatch vmReloadTimer = new Stopwatch()..start(); try { - final String entryPath = fs.path.relative('$mainPath.dill', from: projectRootPath); + final String entryPath = fs.path.relative( + debuggingOptions.buildInfo.previewDart2 ? mainPath + '.dill' : mainPath, + from: projectRootPath, + ); final Completer> retrieveFirstReloadReport = new Completer>(); int countExpectedReports = 0; @@ -550,7 +566,10 @@ class HotRunner extends ResidentRunner { } // List has one report per Flutter view. - final List>> reports = device.reloadSources(entryPath, pause: pause); + final List>> reports = device.reloadSources( + entryPath, + pause: pause + ); countExpectedReports += reports.length; Future.wait(reports).catchError((dynamic error) { return >[error]; @@ -618,8 +637,8 @@ class HotRunner extends ResidentRunner { } // We are now running from source. _runningFromSnapshot = false; - // Check if the isolate is paused. + final List reassembleViews = []; for (FlutterDevice device in flutterDevices) { for (FlutterView view in device.views) { @@ -680,9 +699,36 @@ class HotRunner extends ResidentRunner { shouldReportReloadTime) flutterUsage.sendTiming('hot', 'reload', reloadTimer.elapsed); + String unusedElementMessage; + if (reportUnused && !reassembleAndScheduleErrors && !reassembleTimedOut) { + final List>> unusedReports = + >>[]; + for (FlutterDevice device in flutterDevices) + unusedReports.add(device.unusedChangesInLastReload()); + final List unusedElements = []; + for (Future> unusedReport in unusedReports) + unusedElements.addAll(await unusedReport); + + if (unusedElements.isNotEmpty) { + final String restartCommand = hostIsIde ? '' : ' (by pressing "R")'; + unusedElementMessage = + 'Some program elements were changed during reload but did not run when the view was reassembled;\n' + 'you may need to restart the app$restartCommand for the changes to have an effect.'; + for (ProgramElement unusedElement in unusedElements) { + final String name = unusedElement.qualifiedName; + final String path = _uriToRelativePath(unusedElement.uri); + final int line = unusedElement.line; + final String description = line == null ? '$name ($path)' : '$name ($path:$line)'; + unusedElementMessage += '\n • $description'; + } + } + } + return new OperationResult( reassembleAndScheduleErrors ? 1 : OperationResult.ok.code, reloadMessage, + hintMessage: unusedElementMessage, + hintId: unusedElementMessage != null ? 'restartRecommended' : null, ); } diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index 1cd2a5b125..ad85b9ce05 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart @@ -182,6 +182,10 @@ abstract class FlutterCommand extends Command { } BuildInfo getBuildInfo() { + final bool previewDart2 = argParser.options.containsKey('preview-dart-2') + ? argResults['preview-dart-2'] + : true; + TargetPlatform targetPlatform; if (argParser.options.containsKey('target-platform') && argResults['target-platform'] != 'default') { @@ -191,6 +195,10 @@ abstract class FlutterCommand extends Command { final bool trackWidgetCreation = argParser.options.containsKey('track-widget-creation') ? argResults['track-widget-creation'] : false; + if (trackWidgetCreation == true && previewDart2 == false) { + throw new UsageException( + '--track-widget-creation is valid only when --preview-dart-2 is specified.', null); + } int buildNumber; try { @@ -206,6 +214,7 @@ abstract class FlutterCommand extends Command { argParser.options.containsKey('flavor') ? argResults['flavor'] : null, + previewDart2: previewDart2, trackWidgetCreation: trackWidgetCreation, extraFrontEndOptions: argParser.options.containsKey(FlutterOptions.kExtraFrontEndOptions) ? argResults[FlutterOptions.kExtraFrontEndOptions] diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 5e39e3e493..81948aeb16 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -67,6 +67,7 @@ void installHook({ bool enableObservatory = false, bool machine = false, bool startPaused = false, + bool previewDart2 = false, int port = 0, String precompiledDillPath, bool trackWidgetCreation = false, @@ -85,6 +86,7 @@ void installHook({ startPaused: startPaused, explicitObservatoryPort: observatoryPort, host: _kHosts[serverType], + previewDart2: previewDart2, port: port, precompiledDillPath: precompiledDillPath, trackWidgetCreation: trackWidgetCreation, @@ -184,7 +186,7 @@ void main() { enum _InitialResult { crashed, timedOut, connected } enum _TestResult { crashed, harnessBailed, testBailed } -typedef _Finalizer = Future Function(); +typedef Future _Finalizer(); class _CompilationRequest { String path; @@ -304,6 +306,7 @@ class _FlutterPlatform extends PlatformPlugin { this.startPaused, this.explicitObservatoryPort, this.host, + this.previewDart2, this.port, this.precompiledDillPath, this.trackWidgetCreation, @@ -317,6 +320,7 @@ class _FlutterPlatform extends PlatformPlugin { final bool startPaused; final int explicitObservatoryPort; final InternetAddress host; + final bool previewDart2; final int port; final String precompiledDillPath; final bool trackWidgetCreation; @@ -404,15 +408,17 @@ class _FlutterPlatform extends PlatformPlugin { cancelOnError: true, ); - printTrace('test $ourTestCount: starting shell process'); + printTrace('test $ourTestCount: starting shell process${previewDart2? " in preview-dart-2 mode":""}'); + // [precompiledDillPath] can be set only if [previewDart2] is [true]. + assert(precompiledDillPath == null || previewDart2); // If a kernel file is given, then use that to launch the test. // Otherwise create a "listener" dart that invokes actual test. String mainDart = precompiledDillPath != null ? precompiledDillPath : _createListenerDart(finalizers, ourTestCount, testPath, server); - if (precompiledDillPath == null) { + if (previewDart2 && precompiledDillPath == null) { // Lazily instantiate compiler so it is built only if it is actually used. compiler ??= new _Compiler(trackWidgetCreation); mainDart = await compiler.compile(mainDart); @@ -669,6 +675,10 @@ class _FlutterPlatform extends PlatformPlugin { } String _getBundlePath(List<_Finalizer> finalizers, int ourTestCount) { + if (!previewDart2) { + return null; + } + if (precompiledDillPath != null) { return artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath); } diff --git a/packages/flutter_tools/lib/src/test/runner.dart b/packages/flutter_tools/lib/src/test/runner.dart index b59ad182a6..384d64c3d1 100644 --- a/packages/flutter_tools/lib/src/test/runner.dart +++ b/packages/flutter_tools/lib/src/test/runner.dart @@ -4,6 +4,7 @@ import 'dart:async'; +import 'package:args/command_runner.dart'; // ignore: implementation_imports import 'package:test/src/executable.dart' as test; @@ -28,10 +29,18 @@ Future runTests( bool startPaused = false, bool ipv6 = false, bool machine = false, + bool previewDart2 = false, bool trackWidgetCreation = false, bool updateGoldens = false, TestWatcher watcher, }) async { + if (trackWidgetCreation && !previewDart2) { + throw new UsageException( + '--track-widget-creation is valid only when --preview-dart-2 is specified.', + null, + ); + } + // Compute the command-line arguments for package:test. final List testArgs = []; if (!terminal.supportsColor) { @@ -78,6 +87,7 @@ Future runTests( machine: machine, startPaused: startPaused, serverType: serverType, + previewDart2: previewDart2, trackWidgetCreation: trackWidgetCreation, updateGoldens: updateGoldens, ); diff --git a/packages/flutter_tools/lib/src/tester/flutter_tester.dart b/packages/flutter_tools/lib/src/tester/flutter_tester.dart index c6bebb1e4d..53f67fafff 100644 --- a/packages/flutter_tools/lib/src/tester/flutter_tester.dart +++ b/packages/flutter_tools/lib/src/tester/flutter_tester.dart @@ -133,11 +133,20 @@ class FlutterTesterDevice extends Device { mainPath: mainPath, assetDirPath: assetDirPath, applicationKernelFilePath: applicationKernelFilePath, - precompiledSnapshot: false, + precompiledSnapshot: !buildInfo.previewDart2, + previewDart2: buildInfo.previewDart2, trackWidgetCreation: buildInfo.trackWidgetCreation, ); + if (buildInfo.previewDart2) { + mainPath = applicationKernelFilePath; + } + command.add('--flutter-assets-dir=$assetDirPath'); - command.add(applicationKernelFilePath); + + // TODO(scheglov): Either remove the check, or make it fail earlier. + if (mainPath != null) { + command.add(mainPath); + } try { printTrace(command.join(' ')); diff --git a/packages/flutter_tools/lib/src/vmservice.dart b/packages/flutter_tools/lib/src/vmservice.dart index 5434685049..ef6210d73f 100644 --- a/packages/flutter_tools/lib/src/vmservice.dart +++ b/packages/flutter_tools/lib/src/vmservice.dart @@ -21,7 +21,7 @@ import 'globals.dart'; import 'vmservice_record_replay.dart'; /// A function that opens a two-way communication channel to the specified [uri]. -typedef _OpenChannel = Future> Function(Uri uri); +typedef Future> _OpenChannel(Uri uri); _OpenChannel _openChannel = _defaultOpenChannel; @@ -36,13 +36,13 @@ _OpenChannel _openChannel = _defaultOpenChannel; /// hot mode. /// /// See: https://github.com/dart-lang/sdk/issues/30023 -typedef ReloadSources = Future Function( +typedef Future ReloadSources( String isolateId, { bool force, bool pause, }); -typedef CompileExpression = Future Function( +typedef Future CompileExpression( String isolateId, String expression, List definitions, diff --git a/packages/flutter_tools/test/base/build_test.dart b/packages/flutter_tools/test/base/build_test.dart index f13a8a7f60..08b54b2f37 100644 --- a/packages/flutter_tools/test/base/build_test.dart +++ b/packages/flutter_tools/test/base/build_test.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:convert' show json; import 'package:file/memory.dart'; import 'package:flutter_tools/src/android/android_sdk.dart'; @@ -84,6 +85,199 @@ void main() { }); }); + group('Snapshotter - Script Snapshots', () { + const String kVersion = '123456abcdef'; + const String kIsolateSnapshotData = 'isolate_snapshot.bin'; + const String kVmSnapshotData = 'vm_isolate_snapshot.bin'; + + _FakeGenSnapshot genSnapshot; + MemoryFileSystem fs; + MockFlutterVersion mockVersion; + ScriptSnapshotter snapshotter; + MockArtifacts mockArtifacts; + + setUp(() { + fs = new MemoryFileSystem(); + fs.file(kIsolateSnapshotData).writeAsStringSync('snapshot data'); + fs.file(kVmSnapshotData).writeAsStringSync('vm data'); + genSnapshot = new _FakeGenSnapshot(); + genSnapshot.outputs = { + 'output.snapshot': '', + 'output.snapshot.d': 'output.snapshot.d : main.dart', + }; + mockVersion = new MockFlutterVersion(); + when(mockVersion.frameworkRevision).thenReturn(kVersion); + snapshotter = new ScriptSnapshotter(); + mockArtifacts = new MockArtifacts(); + when(mockArtifacts.getArtifactPath(Artifact.isolateSnapshotData)).thenReturn(kIsolateSnapshotData); + when(mockArtifacts.getArtifactPath(Artifact.vmSnapshotData)).thenReturn(kVmSnapshotData); + }); + + final Map contextOverrides = { + Artifacts: () => mockArtifacts, + FileSystem: () => fs, + FlutterVersion: () => mockVersion, + GenSnapshot: () => genSnapshot, + }; + + Future writeFingerprint({ Map files = const {} }) { + return fs.file('output.snapshot.d.fingerprint').writeAsString(json.encode({ + 'version': kVersion, + 'properties': { + 'buildMode': BuildMode.debug.toString(), + 'targetPlatform': '', + 'entryPoint': 'main.dart', + }, + 'files': { + kVmSnapshotData: '2ec34912477a46c03ddef07e8b909b46', + kIsolateSnapshotData: '621b3844bb7d4d17d2cfc5edf9a91c4c', + }..addAll(files), + })); + } + + void expectFingerprintHas({ + String entryPoint = 'main.dart', + Map checksums = const {}, + }) { + final Map jsonObject = json.decode(fs.file('output.snapshot.d.fingerprint').readAsStringSync()); + expect(jsonObject['properties']['entryPoint'], entryPoint); + expect(jsonObject['files'], hasLength(checksums.length + 2)); + checksums.forEach((String filePath, String checksum) { + expect(jsonObject['files'][filePath], checksum); + }); + expect(jsonObject['files'][kVmSnapshotData], '2ec34912477a46c03ddef07e8b909b46'); + expect(jsonObject['files'][kIsolateSnapshotData], '621b3844bb7d4d17d2cfc5edf9a91c4c'); + } + + testUsingContext('builds snapshot and fingerprint when no fingerprint is present', () async { + await fs.file('main.dart').writeAsString('void main() {}'); + await fs.file('output.snapshot').create(); + await fs.file('output.snapshot.d').writeAsString('snapshot : main.dart'); + await snapshotter.build( + mainPath: 'main.dart', + snapshotPath: 'output.snapshot', + depfilePath: 'output.snapshot.d', + packagesPath: '.packages', + ); + + expect(genSnapshot.callCount, 1); + expect(genSnapshot.snapshotType.platform, isNull); + expect(genSnapshot.snapshotType.mode, BuildMode.debug); + expect(genSnapshot.packagesPath, '.packages'); + expect(genSnapshot.depfilePath, 'output.snapshot.d'); + expect(genSnapshot.additionalArgs, [ + '--snapshot_kind=script', + '--script_snapshot=output.snapshot', + '--vm_snapshot_data=vm_isolate_snapshot.bin', + '--isolate_snapshot_data=isolate_snapshot.bin', + '--enable-mirrors=false', + 'main.dart', + ]); + expectFingerprintHas(checksums: { + 'main.dart': '27f5ebf0f8c559b2af9419d190299a5e', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }); + }, overrides: contextOverrides); + + testUsingContext('builds snapshot and fingerprint when fingerprints differ', () async { + await fs.file('main.dart').writeAsString('void main() {}'); + await fs.file('output.snapshot').create(); + await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart'); + await writeFingerprint(files: { + 'main.dart': '27f5ebf0f8c559b2af9419d190299a5e', + 'output.snapshot': 'deadbeef000b204e9800998ecaaaaa', + }); + await snapshotter.build( + mainPath: 'main.dart', + snapshotPath: 'output.snapshot', + depfilePath: 'output.snapshot.d', + packagesPath: '.packages', + ); + + expect(genSnapshot.callCount, 1); + expectFingerprintHas(checksums: { + 'main.dart': '27f5ebf0f8c559b2af9419d190299a5e', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }); + }, overrides: contextOverrides); + + testUsingContext('builds snapshot and fingerprint when fingerprints match but previous snapshot not present', () async { + await fs.file('main.dart').writeAsString('void main() {}'); + await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart'); + await writeFingerprint(files: { + 'main.dart': '27f5ebf0f8c559b2af9419d190299a5e', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }); + await snapshotter.build( + mainPath: 'main.dart', + snapshotPath: 'output.snapshot', + depfilePath: 'output.snapshot.d', + packagesPath: '.packages', + ); + + expect(genSnapshot.callCount, 1); + expectFingerprintHas(checksums: { + 'main.dart': '27f5ebf0f8c559b2af9419d190299a5e', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }); + }, overrides: contextOverrides); + + testUsingContext('builds snapshot and fingerprint when main entry point changes to other dependency', () async { + await fs.file('main.dart').writeAsString('import "other.dart";\nvoid main() {}'); + await fs.file('other.dart').writeAsString('import "main.dart";\nvoid main() {}'); + await fs.file('output.snapshot').create(); + await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart'); + await writeFingerprint(files: { + 'main.dart': 'bc096b33f14dde5e0ffaf93a1d03395c', + 'other.dart': 'e0c35f083f0ad76b2d87100ec678b516', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }); + genSnapshot.outputs = { + 'output.snapshot': '', + 'output.snapshot.d': 'output.snapshot : main.dart other.dart', + }; + + await snapshotter.build( + mainPath: 'other.dart', + snapshotPath: 'output.snapshot', + depfilePath: 'output.snapshot.d', + packagesPath: '.packages', + ); + + expect(genSnapshot.callCount, 1); + expectFingerprintHas( + entryPoint: 'other.dart', + checksums: { + 'main.dart': 'bc096b33f14dde5e0ffaf93a1d03395c', + 'other.dart': 'e0c35f083f0ad76b2d87100ec678b516', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }, + ); + }, overrides: contextOverrides); + + testUsingContext('skips snapshot when fingerprints match and previous snapshot is present', () async { + await fs.file('main.dart').writeAsString('void main() {}'); + await fs.file('output.snapshot').create(); + await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart'); + await writeFingerprint(files: { + 'main.dart': '27f5ebf0f8c559b2af9419d190299a5e', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }); + await snapshotter.build( + mainPath: 'main.dart', + snapshotPath: 'output.snapshot', + depfilePath: 'output.snapshot.d', + packagesPath: '.packages', + ); + + expect(genSnapshot.callCount, 0); + expectFingerprintHas(checksums: { + 'main.dart': '27f5ebf0f8c559b2af9419d190299a5e', + 'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e', + }); + }, overrides: contextOverrides); + }); + group('Snapshotter - iOS AOT', () { const String kVmEntrypoints = 'dart_vm_entry_points.txt'; const String kIoEntries = 'dart_io_entries.txt'; @@ -146,6 +340,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, ), isNot(equals(0))); }, overrides: contextOverrides); @@ -158,6 +353,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, ), isNot(0)); }, overrides: contextOverrides); @@ -170,6 +366,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, ), isNot(0)); }, overrides: contextOverrides); @@ -195,6 +392,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, iosArch: IOSArch.armv7, ); @@ -241,6 +439,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, iosArch: IOSArch.arm64, ); @@ -288,6 +487,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, ); expect(genSnapshotExitCode, 0); @@ -339,6 +539,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, ); expect(genSnapshotExitCode, 0); @@ -385,6 +586,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, iosArch: IOSArch.armv7, ); @@ -431,6 +633,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, iosArch: IOSArch.arm64, ); @@ -465,6 +668,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: true, + previewDart2: true, ); expect(genSnapshotExitCode, isNot(0)); @@ -496,6 +700,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, ); expect(genSnapshotExitCode, 0); @@ -547,6 +752,7 @@ void main() { packagesPath: '.packages', outputPath: outputPath, buildSharedLibrary: false, + previewDart2: true, ); expect(genSnapshotExitCode, 0); diff --git a/packages/flutter_tools/test/base/flags_test.dart b/packages/flutter_tools/test/base/flags_test.dart index 0a148d9ff8..4074201a13 100644 --- a/packages/flutter_tools/test/base/flags_test.dart +++ b/packages/flutter_tools/test/base/flags_test.dart @@ -12,7 +12,7 @@ import 'package:test/test.dart'; import '../src/common.dart'; import '../src/context.dart'; -typedef _TestMethod = FutureOr Function(); +typedef FutureOr _TestMethod(); void main() { Cache.disableLocking(); diff --git a/packages/flutter_tools/test/commands/analyze_continuously_test.dart b/packages/flutter_tools/test/commands/analyze_continuously_test.dart index 4166ae82fd..850efb9222 100644 --- a/packages/flutter_tools/test/commands/analyze_continuously_test.dart +++ b/packages/flutter_tools/test/commands/analyze_continuously_test.dart @@ -70,10 +70,10 @@ void main() { OperatingSystemUtils: () => os }); - testUsingContext('Returns no errors when source is error-free', () async { + testUsingContext('--preview-dart-2', () async { const String contents = "StringBuffer bar = StringBuffer('baz');"; tempDir.childFile('main.dart').writeAsStringSync(contents); - server = new AnalysisServer(dartSdkPath, [tempDir.path]); + server = new AnalysisServer(dartSdkPath, [tempDir.path], previewDart2: true); int errorCount = 0; final Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; @@ -88,6 +88,25 @@ void main() { }, overrides: { OperatingSystemUtils: () => os }); + + testUsingContext('no --preview-dart-2 shows errors', () async { + const String contents = "StringBuffer bar = StringBuffer('baz');"; + tempDir.childFile('main.dart').writeAsStringSync(contents); + server = new AnalysisServer(dartSdkPath, [tempDir.path], previewDart2: false); + + int errorCount = 0; + final Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; + server.onErrors.listen((FileAnalysisErrors errors) { + errorCount += errors.errors.length; + }); + + await server.start(); + await onDone; + + expect(errorCount, 1); + }, overrides: { + OperatingSystemUtils: () => os + }); } void _createSampleProject(Directory directory, { bool brokenCode = false }) { diff --git a/packages/flutter_tools/test/commands/analyze_once_test.dart b/packages/flutter_tools/test/commands/analyze_once_test.dart index 63c97d373c..e721ac64d1 100644 --- a/packages/flutter_tools/test/commands/analyze_once_test.dart +++ b/packages/flutter_tools/test/commands/analyze_once_test.dart @@ -168,7 +168,7 @@ void bar() { } }); - testUsingContext('returns no issues when source is error-free', () async { + testUsingContext('--preview-dart-2', () async { const String contents = ''' StringBuffer bar = StringBuffer('baz'); '''; @@ -179,13 +179,33 @@ StringBuffer bar = StringBuffer('baz'); try { await runCommand( command: new AnalyzeCommand(workingDirectory: fs.directory(tempDir)), - arguments: ['analyze'], + arguments: ['analyze', '--preview-dart-2'], statusTextContains: ['No issues found!'], ); } finally { tempDir.deleteSync(recursive: true); } }); + + testUsingContext('no --preview-dart-2 shows errors', () async { + const String contents = ''' +StringBuffer bar = StringBuffer('baz'); +'''; + + final Directory tempDir = fs.systemTempDirectory.createTempSync(); + tempDir.childFile('main.dart').writeAsStringSync(contents); + + try { + await runCommand( + command: new AnalyzeCommand(workingDirectory: fs.directory(tempDir)), + arguments: ['analyze', '--no-preview-dart-2'], + statusTextContains: ['1 issue found.'], + toolExit: true, + ); + } finally { + tempDir.deleteSync(recursive: true); + } + }); }); } diff --git a/packages/flutter_tools/test/commands/drive_test.dart b/packages/flutter_tools/test/commands/drive_test.dart index 1e656049e1..d5543b6f72 100644 --- a/packages/flutter_tools/test/commands/drive_test.dart +++ b/packages/flutter_tools/test/commands/drive_test.dart @@ -54,7 +54,7 @@ void main() { appStarter = (DriveCommand command) { throw 'Unexpected call to appStarter'; }; - testRunner = (List testArgs, String observatoryUri) { + testRunner = (List testArgs, String observatoryUri, bool previewDart2) { throw 'Unexpected call to testRunner'; }; appStopper = (DriveCommand command) { @@ -169,7 +169,7 @@ void main() { appStarter = expectAsync1((DriveCommand command) async { return new LaunchResult.succeeded(); }); - testRunner = expectAsync2((List testArgs, String observatoryUri) async { + testRunner = expectAsync3((List testArgs, String observatoryUri, bool previewDart2) async { expect(testArgs, [testFile]); return null; }); @@ -200,7 +200,7 @@ void main() { appStarter = expectAsync1((DriveCommand command) async { return new LaunchResult.succeeded(); }); - testRunner = (List testArgs, String observatoryUri) async { + testRunner = (List testArgs, String observatoryUri, bool previewDart2) async { throwToolExit(null, exitCode: 123); }; appStopper = expectAsync1((DriveCommand command) async { diff --git a/packages/flutter_tools/test/dart/pub_get_test.dart b/packages/flutter_tools/test/dart/pub_get_test.dart index 951821a75f..f9c2b7a349 100644 --- a/packages/flutter_tools/test/dart/pub_get_test.dart +++ b/packages/flutter_tools/test/dart/pub_get_test.dart @@ -147,7 +147,7 @@ void main() { }); } -typedef StartCallback = void Function(List command); +typedef void StartCallback(List command); class MockProcessManager implements ProcessManager { MockProcessManager(this.fakeExitCode); diff --git a/packages/flutter_tools/test/devfs_test.dart b/packages/flutter_tools/test/devfs_test.dart index 7e6555e9fd..2f165a3ddc 100644 --- a/packages/flutter_tools/test/devfs_test.dart +++ b/packages/flutter_tools/test/devfs_test.dart @@ -11,7 +11,6 @@ import 'package:flutter_tools/src/asset.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/build_info.dart'; -import 'package:flutter_tools/src/compile.dart'; import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/vmservice.dart'; import 'package:json_rpc_2/json_rpc_2.dart' as rpc; @@ -68,7 +67,6 @@ void main() { group('devfs local', () { final MockDevFSOperations devFSOperations = new MockDevFSOperations(); - final MockResidentCompiler residentCompiler = new MockResidentCompiler(); setUpAll(() { tempDir = _newTempDir(fs); @@ -91,13 +89,22 @@ void main() { devFSOperations.expectMessages(['create test']); expect(devFS.assetPathsToEvict, isEmpty); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ - 'writeFile test lib/foo.txt.dill', + 'writeFile test .packages', + 'writeFile test lib/foo.txt', + 'writeFile test packages/somepkg/somefile.txt', ]); expect(devFS.assetPathsToEvict, isEmpty); - expect(bytes, 22); + final List packageSpecOnDevice = LineSplitter.split(utf8.decode( + await devFSOperations.devicePathToContent[fs.path.toUri('.packages')].contentsAsBytes() + )).toList(); + expect(packageSpecOnDevice, + unorderedEquals(['my_project:lib/', 'somepkg:packages/somepkg/']) + ); + + expect(bytes, 48); }, overrides: { FileSystem: () => fs, }); @@ -106,33 +113,48 @@ void main() { final File file = fs.file(fs.path.join(basePath, filePath2)); await file.parent.create(recursive: true); file.writeAsBytesSync([1, 2, 3, 4, 5, 6, 7]); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ - 'writeFile test lib/foo.txt.dill', + 'writeFile test foo/bar.txt', ]); expect(devFS.assetPathsToEvict, isEmpty); - expect(bytes, 22); + expect(bytes, 7); + }, overrides: { + FileSystem: () => fs, + }); + + testUsingContext('add new file to local file system and preserve unusual file name casing', () async { + final String filePathWithUnusualCasing = fs.path.join('FooBar', 'TEST.txt'); + final File file = fs.file(fs.path.join(basePath, filePathWithUnusualCasing)); + await file.parent.create(recursive: true); + file.writeAsBytesSync([1, 2, 3, 4, 5, 6, 7]); + final int bytes = await devFS.update(); + devFSOperations.expectMessages([ + 'writeFile test FooBar/TEST.txt', + ]); + expect(devFS.assetPathsToEvict, isEmpty); + expect(bytes, 7); }, overrides: { FileSystem: () => fs, }); testUsingContext('modify existing file on local file system', () async { - await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + await devFS.update(); final File file = fs.file(fs.path.join(basePath, filePath)); // Set the last modified time to 5 seconds in the past. updateFileModificationTime(file.path, new DateTime.now(), -5); - int bytes = await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + int bytes = await devFS.update(); devFSOperations.expectMessages([]); expect(devFS.assetPathsToEvict, isEmpty); expect(bytes, 0); await file.writeAsBytes([1, 2, 3, 4, 5, 6]); - bytes = await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + bytes = await devFS.update(); devFSOperations.expectMessages([ - 'writeFile test lib/foo.txt.dill', + 'writeFile test lib/foo.txt', ]); expect(devFS.assetPathsToEvict, isEmpty); - expect(bytes, 22); + expect(bytes, 6); }, overrides: { FileSystem: () => fs, }); @@ -140,7 +162,7 @@ void main() { testUsingContext('delete a file from the local file system', () async { final File file = fs.file(fs.path.join(basePath, filePath)); await file.delete(); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ 'deleteFile test lib/foo.txt', ]); @@ -152,12 +174,13 @@ void main() { testUsingContext('add new package', () async { await _createPackage(fs, 'newpkg', 'anotherfile.txt'); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ - 'writeFile test lib/foo.txt.dill', + 'writeFile test .packages', + 'writeFile test packages/newpkg/anotherfile.txt', ]); expect(devFS.assetPathsToEvict, isEmpty); - expect(bytes, 22); + expect(bytes, 69); }, overrides: { FileSystem: () => fs, }); @@ -178,19 +201,20 @@ void main() { .map((FileSystemEntity file) => canonicalizePath(file.path)) .toList()); } - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', fileFilter: fileFilter, generator: residentCompiler); + final int bytes = await devFS.update(fileFilter: fileFilter); devFSOperations.expectMessages([ - 'writeFile test lib/foo.txt.dill', + 'writeFile test .packages', + 'writeFile test packages/doubleslashpkg/somefile.txt', ]); expect(devFS.assetPathsToEvict, isEmpty); - expect(bytes, 22); + expect(bytes, 109); }, overrides: { FileSystem: () => fs, }); testUsingContext('add an asset bundle', () async { assetBundle.entries['a.txt'] = new DevFSStringContent('abc'); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', bundle: assetBundle, bundleDirty: true, generator: residentCompiler); + final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); devFSOperations.expectMessages([ 'writeFile test ${_inAssetBuildDirectory(fs, 'a.txt')}', ]); @@ -203,7 +227,7 @@ void main() { testUsingContext('add a file to the asset bundle - bundleDirty', () async { assetBundle.entries['b.txt'] = new DevFSStringContent('abcd'); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', bundle: assetBundle, bundleDirty: true, generator: residentCompiler); + final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); // Expect entire asset bundle written because bundleDirty is true devFSOperations.expectMessages([ 'writeFile test ${_inAssetBuildDirectory(fs, 'a.txt')}', @@ -219,7 +243,7 @@ void main() { testUsingContext('add a file to the asset bundle', () async { assetBundle.entries['c.txt'] = new DevFSStringContent('12'); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', bundle: assetBundle, generator: residentCompiler); + final int bytes = await devFS.update(bundle: assetBundle); devFSOperations.expectMessages([ 'writeFile test ${_inAssetBuildDirectory(fs, 'c.txt')}', ]); @@ -233,7 +257,7 @@ void main() { testUsingContext('delete a file from the asset bundle', () async { assetBundle.entries.remove('c.txt'); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', bundle: assetBundle, generator: residentCompiler); + final int bytes = await devFS.update(bundle: assetBundle); devFSOperations.expectMessages([ 'deleteFile test ${_inAssetBuildDirectory(fs, 'c.txt')}', ]); @@ -246,7 +270,7 @@ void main() { testUsingContext('delete all files from the asset bundle', () async { assetBundle.entries.clear(); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', bundle: assetBundle, bundleDirty: true, generator: residentCompiler); + final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); devFSOperations.expectMessages([ 'deleteFile test ${_inAssetBuildDirectory(fs, 'a.txt')}', 'deleteFile test ${_inAssetBuildDirectory(fs, 'b.txt')}', @@ -271,7 +295,6 @@ void main() { group('devfs remote', () { MockVMService vmService; - final MockResidentCompiler residentCompiler = new MockResidentCompiler(); setUpAll(() async { tempDir = _newTempDir(fs); @@ -298,12 +321,14 @@ void main() { vmService.expectMessages(['create test']); expect(devFS.assetPathsToEvict, isEmpty); - final int bytes = await devFS.update(mainPath: 'lib/foo.txt', generator: residentCompiler); + final int bytes = await devFS.update(); vmService.expectMessages([ - 'writeFile test lib/foo.txt.dill', + 'writeFile test .packages', + 'writeFile test lib/foo.txt', + 'writeFile test packages/somepkg/somefile.txt', ]); expect(devFS.assetPathsToEvict, isEmpty); - expect(bytes, 22); + expect(bytes, 48); }, overrides: { FileSystem: () => fs, }); @@ -346,38 +371,6 @@ void main() { }); } -class MockResidentCompiler extends BasicMock implements ResidentCompiler { - @override - void accept() {} - - @override - void reject() {} - - @override - void reset() {} - - @override - Future shutdown() async {} - - @override - Future compileExpression( - String expression, - List definitions, - List typeDefinitions, - String libraryUri, - String klass, - bool isStatic - ) async { - return null; - } - @override - Future recompile(String mainPath, List invalidatedFiles, {String outputPath, String packagesFilePath}) async { - fs.file(outputPath).createSync(recursive: true); - fs.file(outputPath).writeAsStringSync('compiled_kernel_output'); - return new CompilerOutput(outputPath, 0); - } -} - class MockVMService extends BasicMock implements VMService { Uri _httpAddress; HttpServer _server; diff --git a/packages/flutter_tools/test/ios/cocoapods_test.dart b/packages/flutter_tools/test/ios/cocoapods_test.dart index f399a7803c..14f6907118 100644 --- a/packages/flutter_tools/test/ios/cocoapods_test.dart +++ b/packages/flutter_tools/test/ios/cocoapods_test.dart @@ -17,7 +17,7 @@ import 'package:test/test.dart'; import '../src/context.dart'; -typedef InvokeProcess = Future Function(); +typedef Future InvokeProcess(); void main() { FileSystem fs; diff --git a/packages/flutter_tools/test/ios/xcodeproj_test.dart b/packages/flutter_tools/test/ios/xcodeproj_test.dart index 357e75dd20..31b1bccd43 100644 --- a/packages/flutter_tools/test/ios/xcodeproj_test.dart +++ b/packages/flutter_tools/test/ios/xcodeproj_test.dart @@ -284,10 +284,14 @@ Information about project "Runner": testUsingOsxContext('sets ARCHS=armv7 when armv7 local engine is set', () async { when(mockArtifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, typed(any))).thenReturn('engine'); when(mockArtifacts.engineOutPath).thenReturn(fs.path.join('out', 'ios_profile_arm')); - const BuildInfo buildInfo = const BuildInfo(BuildMode.debug, null, targetPlatform: TargetPlatform.ios); + const BuildInfo buildInfo = const BuildInfo(BuildMode.debug, null, + previewDart2: true, + targetPlatform: TargetPlatform.ios, + ); await updateGeneratedXcodeProperties( projectPath: 'path/to/project', buildInfo: buildInfo, + previewDart2: true, ); final File config = fs.file('path/to/project/ios/Flutter/Generated.xcconfig'); @@ -301,12 +305,14 @@ Information about project "Runner": when(mockArtifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, typed(any))).thenReturn('engine'); when(mockArtifacts.engineOutPath).thenReturn(fs.path.join('out', 'ios_profile_arm')); const BuildInfo buildInfo = const BuildInfo(BuildMode.debug, null, + previewDart2: true, trackWidgetCreation: true, targetPlatform: TargetPlatform.ios, ); await updateGeneratedXcodeProperties( projectPath: 'path/to/project', buildInfo: buildInfo, + previewDart2: true, ); final File config = fs.file('path/to/project/ios/Flutter/Generated.xcconfig'); @@ -319,10 +325,14 @@ Information about project "Runner": testUsingOsxContext('does not set TRACK_WIDGET_CREATION when trackWidgetCreation is false', () async { when(mockArtifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, typed(any))).thenReturn('engine'); when(mockArtifacts.engineOutPath).thenReturn(fs.path.join('out', 'ios_profile_arm')); - const BuildInfo buildInfo = const BuildInfo(BuildMode.debug, null, targetPlatform: TargetPlatform.ios); + const BuildInfo buildInfo = const BuildInfo(BuildMode.debug, null, + previewDart2: true, + targetPlatform: TargetPlatform.ios, + ); await updateGeneratedXcodeProperties( projectPath: 'path/to/project', buildInfo: buildInfo, + previewDart2: true, ); final File config = fs.file('path/to/project/ios/Flutter/Generated.xcconfig'); @@ -335,10 +345,14 @@ Information about project "Runner": testUsingOsxContext('sets ARCHS=armv7 when armv7 local engine is set', () async { when(mockArtifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, typed(any))).thenReturn('engine'); when(mockArtifacts.engineOutPath).thenReturn(fs.path.join('out', 'ios_profile')); - const BuildInfo buildInfo = const BuildInfo(BuildMode.debug, null, targetPlatform: TargetPlatform.ios); + const BuildInfo buildInfo = const BuildInfo(BuildMode.debug, null, + previewDart2: true, + targetPlatform: TargetPlatform.ios, + ); await updateGeneratedXcodeProperties( projectPath: 'path/to/project', buildInfo: buildInfo, + previewDart2: true, ); final File config = fs.file('path/to/project/ios/Flutter/Generated.xcconfig'); @@ -391,6 +405,7 @@ Information about project "Runner": projectPath: projectPath, buildInfo: buildInfo, targetOverride: bundle.defaultMainPath, + previewDart2: false, ); final String propertiesPath = fs.path.join(projectPath, 'ios', 'Flutter', 'Generated.xcconfig'); diff --git a/packages/flutter_tools/test/resident_runner_test.dart b/packages/flutter_tools/test/resident_runner_test.dart index 2007e450b6..ebe65cd8be 100644 --- a/packages/flutter_tools/test/resident_runner_test.dart +++ b/packages/flutter_tools/test/resident_runner_test.dart @@ -44,11 +44,14 @@ class TestRunner extends ResidentRunner { void main() { TestRunner createTestRunner() { - // TODO(jacobr): make these tests run with `trackWidgetCreation: true` as - // well as the default flags. + // TODO(jacobr): make these tests run with `previewDart2: true` and + // `trackWidgetCreation: true` as well as the default flags. + // Currently the TestRunner is not properly configured to be able to run + // with `previewDart2: true` due to missing resources. return new TestRunner( [new FlutterDevice( new MockDevice(), + previewDart2: false, trackWidgetCreation: false, )], ); diff --git a/packages/flutter_tools/test/runner/flutter_command_test.dart b/packages/flutter_tools/test/runner/flutter_command_test.dart index 12790a4781..6aa663eed7 100644 --- a/packages/flutter_tools/test/runner/flutter_command_test.dart +++ b/packages/flutter_tools/test/runner/flutter_command_test.dart @@ -157,7 +157,7 @@ void main() { } -typedef CommandFunction = Future Function(); +typedef Future CommandFunction(); class DummyFlutterCommand extends FlutterCommand { diff --git a/packages/flutter_tools/test/src/context.dart b/packages/flutter_tools/test/src/context.dart index 1dd0383088..32a5e230a5 100644 --- a/packages/flutter_tools/test/src/context.dart +++ b/packages/flutter_tools/test/src/context.dart @@ -36,7 +36,7 @@ BufferLogger get testLogger => context[Logger]; MockDeviceManager get testDeviceManager => context[DeviceManager]; MockDoctor get testDoctor => context[Doctor]; -typedef ContextInitializer = void Function(AppContext testContext); +typedef void ContextInitializer(AppContext testContext); @isTest void testUsingContext(String description, dynamic testMethod(), { diff --git a/packages/flutter_tools/test/src/mocks.dart b/packages/flutter_tools/test/src/mocks.dart index f155db710a..fe732a9870 100644 --- a/packages/flutter_tools/test/src/mocks.dart +++ b/packages/flutter_tools/test/src/mocks.dart @@ -104,7 +104,7 @@ ro.build.version.codename=REL } /// A strategy for creating Process objects from a list of commands. -typedef ProcessFactory = Process Function(List command); +typedef Process ProcessFactory(List command); /// A ProcessManager that starts Processes by delegating to a ProcessFactory. class MockProcessManager implements ProcessManager { diff --git a/packages/flutter_tools/test/tester/flutter_tester_test.dart b/packages/flutter_tools/test/tester/flutter_tester_test.dart index 4ae579d8a6..af38a1ba9a 100644 --- a/packages/flutter_tools/test/tester/flutter_tester_test.dart +++ b/packages/flutter_tools/test/tester/flutter_tester_test.dart @@ -6,14 +6,11 @@ import 'dart:async'; import 'package:file/file.dart'; import 'package:file/memory.dart'; -import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/cache.dart'; -import 'package:flutter_tools/src/compile.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/tester/flutter_tester.dart'; -import 'package:mockito/mockito.dart'; import 'package:process/process.dart'; import 'package:test/test.dart'; @@ -100,8 +97,6 @@ void main() { String projectPath; String mainPath; - MockArtifacts mockArtifacts; - MockKernelCompiler mockKernelCompiler; MockProcessManager mockProcessManager; MockProcess mockProcess; @@ -110,8 +105,6 @@ void main() { FileSystem: () => fs, Cache: () => new Cache(rootOverride: fs.directory(flutterRoot)), ProcessManager: () => mockProcessManager, - KernelCompiler: () => mockKernelCompiler, - Artifacts: () => mockArtifacts, }; setUp(() { @@ -129,13 +122,6 @@ void main() { mockProcessManager = new MockProcessManager(); mockProcessManager.processFactory = (List commands) => mockProcess; - - mockArtifacts = new MockArtifacts(); - final String artifactPath = fs.path.join(flutterRoot, 'artifact'); - fs.file(artifactPath).createSync(recursive: true); - when(mockArtifacts.getArtifactPath(any)).thenReturn(artifactPath); - - mockKernelCompiler = new MockKernelCompiler(); }); testUsingContext('not debug', () async { @@ -167,22 +153,6 @@ Hello! .codeUnits ])); - when(mockKernelCompiler.compile( - sdkRoot: anyNamed('sdkRoot'), - incrementalCompilerByteStorePath: anyNamed('incrementalCompilerByteStorePath'), - mainPath: anyNamed('mainPath'), - outputFilePath: anyNamed('outputFilePath'), - depFilePath: anyNamed('depFilePath'), - trackWidgetCreation: anyNamed('trackWidgetCreation'), - extraFrontEndOptions: anyNamed('extraFrontEndOptions'), - fileSystemRoots: anyNamed('fileSystemRoots'), - fileSystemScheme: anyNamed('fileSystemScheme'), - packagesPath: anyNamed('packagesPath'), - )).thenAnswer((_) async { - fs.file('$mainPath.dill').createSync(recursive: true); - return new CompilerOutput('$mainPath.dill', 0); - }); - final LaunchResult result = await device.startApp(null, mainPath: mainPath, debuggingOptions: new DebuggingOptions.enabled( @@ -195,6 +165,3 @@ Hello! }); }); } - -class MockArtifacts extends Mock implements Artifacts {} -class MockKernelCompiler extends Mock implements KernelCompiler {} diff --git a/packages/fuchsia_remote_debug_protocol/lib/src/common/logging.dart b/packages/fuchsia_remote_debug_protocol/lib/src/common/logging.dart index b753bcdea3..196643f83e 100644 --- a/packages/fuchsia_remote_debug_protocol/lib/src/common/logging.dart +++ b/packages/fuchsia_remote_debug_protocol/lib/src/common/logging.dart @@ -43,7 +43,7 @@ enum LoggingLevel { } /// Signature of a function that logs a [LogMessage]. -typedef LoggingFunction = void Function(LogMessage log); +typedef void LoggingFunction(LogMessage log); /// The default logging function. /// diff --git a/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart b/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart index 58284b52bb..98df7e6336 100644 --- a/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart +++ b/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart @@ -20,7 +20,7 @@ final Logger _log = new Logger('DartVm'); /// Signature of an asynchronous function for astablishing a JSON RPC-2 /// connection to a [Uri]. -typedef RpcPeerConnectionFunction = Future Function(Uri uri); +typedef Future RpcPeerConnectionFunction(Uri uri); /// [DartVm] uses this function to connect to the Dart VM on Fuchsia. /// diff --git a/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart b/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart index ae460df543..c9fe1cfb5f 100644 --- a/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart +++ b/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart @@ -30,7 +30,7 @@ final Logger _log = new Logger('FuchsiaRemoteConnection'); /// Takes a remote `address`, the target device's port, and an optional /// `interface` and `configFile`. The config file is used primarily for the /// default SSH port forwarding configuration. -typedef PortForwardingFunction = Future Function( +typedef Future PortForwardingFunction( String address, int remotePort, [String interface, String configFile]);