From 568924c216f33abfeaa163e6688a36ea5dd4e671 Mon Sep 17 00:00:00 2001 From: Parker Lougheed Date: Wed, 12 Feb 2025 10:52:57 -0600 Subject: [PATCH] Format and analyze excerpts with 3.7 (#6401) --- examples/analysis/pubspec.yaml | 2 +- examples/analysis_alt/pubspec.yaml | 2 +- examples/async_await/bin/futures_intro.dart | 1 + examples/async_await/bin/get_order.dart | 7 +- .../async_await/bin/get_order_sync_bad.dart | 8 +- examples/async_await/bin/try_catch.dart | 7 +- .../lib/practice_errors/solution.dart | 1 + .../async_await/lib/practice_errors/test.dart | 24 ++-- .../lib/practice_using/solution.dart | 1 + .../async_await/lib/practice_using/test.dart | 33 +++-- .../lib/putting_together/solution.dart | 1 + .../lib/putting_together/test.dart | 59 +++++--- examples/async_await/pubspec.yaml | 2 +- .../async_await/test/async_await_test.dart | 11 +- examples/build_runner_usage/pubspec.yaml | 2 +- examples/cli/bin/dcat.dart | 1 + examples/cli/pubspec.yaml | 2 +- .../concurrency/lib/async_number_of_keys.dart | 1 + .../lib/basic_ports_example/complete.dart | 1 + .../handle_response_from_isolate.dart | 4 +- .../lib/basic_ports_example/parse_json.dart | 4 +- .../lib/basic_ports_example/start.dart | 1 + examples/concurrency/lib/future_syntax.dart | 1 + .../concurrency/lib/isolate_run_syntax.dart | 1 + .../lib/robust_ports_example/complete.dart | 5 +- .../lib/robust_ports_example/spawn_1.dart | 9 +- .../lib/robust_ports_example/spawn_2.dart | 5 +- .../lib/robust_ports_example/start.dart | 1 + .../lib/robust_ports_example/step_4.dart | 32 +++-- .../step_5_add_completers.dart | 30 ++-- .../step_6_close_ports.dart | 7 +- .../lib/simple_isolate_closure.dart | 1 + .../lib/simple_worker_isolate.dart | 1 + .../concurrency/lib/sync_number_of_keys.dart | 1 + examples/concurrency/pubspec.yaml | 2 +- examples/create_libraries/lib/hw_mp.dart | 1 + examples/create_libraries/pubspec.yaml | 2 +- .../lib/string_extensions/string_apis.dart | 2 + .../lib/string_extensions/usage_explicit.dart | 10 +- .../lib/string_extensions/usage_import.dart | 7 +- .../lib/string_extensions/usage_prefix.dart | 6 +- .../usage_simple_extension.dart | 11 +- examples/extension_methods/pubspec.yaml | 2 +- .../fetch_data/bin/fetch_http_package.dart | 2 + examples/fetch_data/lib/fetch_data.dart | 7 +- examples/fetch_data/pubspec.yaml | 2 +- .../bin/mixing_errors_problematic.dart | 1 + .../futures/lib/early_error_handlers.dart | 1 + examples/futures/lib/long_chain.dart | 11 +- examples/futures/lib/simple.dart | 31 +++-- examples/futures/lib/when_complete.dart | 9 +- examples/futures/pubspec.yaml | 2 +- examples/html/lib/html.dart | 15 +- examples/html/pubspec.yaml | 2 +- examples/html/test/html_test.dart | 35 ++--- examples/iterables/pubspec.yaml | 2 +- examples/iterables/test/iterables_test.dart | 76 +++++++---- .../language/lib/class_modifiers/ex1/b.dart | 1 + .../sealed_exhaustiveness.dart | 8 +- .../language/lib/control_flow/branches.dart | 2 +- .../lib/patterns/algebraic_datatypes.dart | 6 +- examples/language/lib/patterns/for_in.dart | 5 +- examples/language/lib/patterns/json.dart | 2 +- .../language/lib/patterns/pattern_types.dart | 6 +- examples/language/lib/patterns/switch.dart | 2 +- examples/language/pubspec.yaml | 2 +- examples/language/test/records_test.dart | 12 +- examples/misc/bin/try_dart/classes.dart | 5 +- .../bin/try_dart/collection_literals.dart | 12 +- examples/misc/bin/try_dart/strings.dart | 5 +- .../line_stream_generator.dart | 15 +- .../creating-streams/stream_controller.dart | 78 ++++++----- .../stream_controller_bad.dart | 5 +- .../lib/cheatsheet/initializer_lists.dart | 4 +- .../lib/cheatsheet/named_constructor.dart | 5 +- .../cheatsheet/optional_positional_args2.dart | 1 + .../cheatsheet/redirecting_constructors.dart | 1 + .../misc/lib/effective_dart/design_bad.dart | 16 ++- .../misc/lib/effective_dart/design_good.dart | 63 +++++---- .../misc/lib/effective_dart/docs_bad.dart | 8 +- .../misc/lib/effective_dart/docs_good.dart | 22 +-- .../lib/effective_dart/some/other/file_2.dart | 1 + .../misc/lib/effective_dart/style_good.dart | 49 ++++--- .../lib/effective_dart/style_lib_bad.dart | 1 + .../lib/effective_dart/style_lib_good.dart | 1 + .../misc/lib/effective_dart/usage_bad.dart | 83 +++++++----- .../misc/lib/effective_dart/usage_good.dart | 56 +++++--- examples/misc/lib/language_tour/async.dart | 3 + .../lib/language_tour/built_in_types.dart | 21 +-- examples/misc/lib/language_tour/cascades.dart | 9 +- .../lib/language_tour/classes/employee.dart | 3 +- .../misc/lib/language_tour/classes/enum.dart | 1 + .../lib/language_tour/classes/extends.dart | 1 + .../misc/lib/language_tour/classes/misc.dart | 5 +- .../language_tour/classes/no_such_method.dart | 7 +- .../lib/language_tour/classes/orchestra.dart | 2 +- .../misc/lib/language_tour/classes/point.dart | 10 +- .../lib/language_tour/classes/point_alt.dart | 7 +- .../classes/point_with_distance_field.dart | 6 +- .../classes/point_with_main.dart | 3 +- .../super_initializer_named_parameters.dart | 5 +- .../classes/super_initializer_parameters.dart | 5 +- ...per_initializer_positional_parameters.dart | 1 + examples/misc/lib/language_tour/comments.dart | 2 + .../misc/lib/language_tour/functions.dart | 10 +- .../language_tour/generics/base_class.dart | 5 +- .../lib/language_tour/generics/cache.dart | 1 + .../misc/lib/language_tour/generics/misc.dart | 3 +- .../lib/language_tour/libraries/greeter.dart | 1 + .../misc/lib/language_tour/metadata/misc.dart | 1 + .../language_tour/metadata/television.dart | 13 +- .../misc/lib/language_tour/operators.dart | 24 ++-- .../misc/lib/language_tour/typedefs/misc.dart | 1 + .../misc/lib/library_tour/async/basic.dart | 13 +- .../misc/lib/library_tour/async/future.dart | 14 +- .../misc/lib/library_tour/async/stream.dart | 30 ++-- .../misc/lib/library_tour/core/iterator.dart | 1 + .../misc/lib/library_tour/io/http_server.dart | 6 +- examples/misc/lib/samples/spacecraft.dart | 8 +- examples/misc/lib/tutorial/misc.dart | 1 + .../misc/lib/tutorial/stream_interface.dart | 21 ++- examples/misc/pubspec.yaml | 2 +- examples/misc/test/bin_test.dart | 6 +- .../test/cheatsheet/collections_test.dart | 10 +- .../misc/test/language_tour/browser_test.dart | 3 +- .../language_tour/built_in_types_test.dart | 29 ++-- .../test/language_tour/characters_test.dart | 8 +- .../misc/test/language_tour/classes_test.dart | 55 ++++---- .../test/language_tour/control_flow_test.dart | 6 +- .../test/language_tour/exceptions_test.dart | 11 +- .../test/language_tour/functions_test.dart | 14 +- .../test/language_tour/operators_test.dart | 30 ++-- .../misc/test/library_tour/convert_test.dart | 14 +- .../misc/test/library_tour/core_test.dart | 26 ++-- examples/misc/test/library_tour/io_test.dart | 34 +++-- examples/misc/test/samples_test.dart | 49 ++++--- examples/misc/test/try_dart_test.dart | 4 +- examples/misc/test/tutorial/streams_test.dart | 6 +- examples/non_promotion/lib/non_promotion.dart | 29 +++- examples/non_promotion/pubspec.yaml | 2 +- examples/pubspec.yaml | 2 +- examples/type_system/lib/animal.dart | 28 +++- .../lib/common_fixes_analysis.dart | 33 +++-- examples/type_system/lib/covariant.dart | 12 +- .../type_system/lib/incorrect_animal.dart | 9 +- examples/type_system/pubspec.yaml | 2 +- examples/type_system/test/strong_test.dart | 12 +- examples/util/pubspec.yaml | 2 +- examples/vector_victor/pubspec.yaml | 2 +- pubspec.yaml | 2 +- src/_data/site.yml | 2 +- src/content/deprecated/sound-problems.md | 34 +++-- src/content/effective-dart/design.md | 68 ++++++---- src/content/effective-dart/documentation.md | 4 +- src/content/effective-dart/style.md | 28 +++- src/content/effective-dart/usage.md | 116 +++++++++------- src/content/language/branches.md | 8 +- src/content/language/built-in-types.md | 31 +++-- .../language/class-modifiers-for-apis.md | 8 +- src/content/language/classes.md | 4 +- src/content/language/collections.md | 20 +-- src/content/language/constructors.md | 14 +- src/content/language/error-handling.md | 6 +- src/content/language/extend.md | 14 +- src/content/language/extension-methods.md | 61 +++++---- src/content/language/functions.md | 28 ++-- src/content/language/generics.md | 6 +- src/content/language/index.md | 12 +- src/content/language/isolates.md | 29 ++-- src/content/language/metadata.md | 4 +- src/content/language/methods.md | 1 + src/content/language/operators.md | 38 ++++-- src/content/language/pattern-types.md | 4 +- src/content/language/patterns.md | 15 +- src/content/language/records.md | 6 +- src/content/language/type-system.md | 40 ++++-- src/content/libraries/async/async-await.md | 30 ++-- .../libraries/async/creating-streams.md | 24 ++-- .../libraries/async/futures-error-handling.md | 51 ++++--- src/content/libraries/async/using-streams.md | 14 +- .../libraries/collections/iterables.md | 5 +- src/content/libraries/dart-async.md | 57 +++++--- src/content/libraries/dart-convert.md | 14 +- src/content/libraries/dart-core.md | 20 +-- src/content/libraries/dart-html.md | 21 ++- src/content/libraries/dart-io.md | 5 +- src/content/resources/dart-cheatsheet.md | 18 +-- src/content/tools/non-promotion-reasons.md | 19 +-- src/content/tutorials/server/cmdline.md | 2 +- src/content/tutorials/server/fetch-data.md | 7 +- tool/dart_site/bin/dart_site.dart | 9 +- tool/dart_site/lib/dart_site.dart | 8 +- .../lib/src/commands/analyze_dart.dart | 16 +-- tool/dart_site/lib/src/commands/build.dart | 4 +- .../dart_site/lib/src/commands/check_all.dart | 9 +- .../src/commands/check_link_references.dart | 3 +- .../lib/src/commands/check_links.dart | 20 ++- .../lib/src/commands/format_dart.dart | 8 +- .../dart_site/lib/src/commands/freshness.dart | 47 ++++--- .../commands/generate_effective_dart_toc.dart | 39 +++--- .../lib/src/commands/refresh_excerpts.dart | 25 ++-- tool/dart_site/lib/src/commands/serve.dart | 6 +- .../dart_site/lib/src/commands/test_dart.dart | 23 ++-- .../src/commands/verify_firebase_json.dart | 7 +- .../lib/src/diagnostics/diagnostics.dart | 35 +++-- .../error_code_documentation_info.dart | 55 +++++--- .../lib/src/diagnostics/error_code_info.dart | 102 ++++++++------ .../dart_site/lib/src/diagnostics/linter.dart | 21 +-- tool/dart_site/lib/src/utils.dart | 29 ++-- tool/dart_site/pubspec.yaml | 2 +- tool/get-dart/archive/pubspec.yaml | 2 +- .../dart_sdk_archive/lib/src/generator.dart | 15 +- .../lib/src/operating_system.dart | 42 +++--- .../lib/src/svn_versions.dart | 2 +- .../lib/src/version_selector.dart | 128 +++++++++++------- tool/get-dart/dart_sdk_archive/pubspec.yaml | 2 +- tool/get-dart/pubspec.yaml | 2 +- .../sdk_builds/lib/src/dart_downloads.dart | 64 +++++---- tool/get-dart/sdk_builds/pubspec.yaml | 2 +- .../sdk_builds/test/sdk_builds_test.dart | 17 ++- 220 files changed, 1919 insertions(+), 1384 deletions(-) diff --git a/examples/analysis/pubspec.yaml b/examples/analysis/pubspec.yaml index 8402c6b490..f12c5b6156 100644 --- a/examples/analysis/pubspec.yaml +++ b/examples/analysis/pubspec.yaml @@ -3,7 +3,7 @@ description: dart.dev example code. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: examples_util: {path: ../util} diff --git a/examples/analysis_alt/pubspec.yaml b/examples/analysis_alt/pubspec.yaml index 9dff9e7dbd..894c087cb9 100644 --- a/examples/analysis_alt/pubspec.yaml +++ b/examples/analysis_alt/pubspec.yaml @@ -3,4 +3,4 @@ description: dart.dev example code. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 diff --git a/examples/async_await/bin/futures_intro.dart b/examples/async_await/bin/futures_intro.dart index f86e3ef7f9..ddfd8f7504 100644 --- a/examples/async_await/bin/futures_intro.dart +++ b/examples/async_await/bin/futures_intro.dart @@ -19,4 +19,5 @@ void main() { fetchUserOrder(); print('Fetching user order...'); } + // #enddocregion no-error, error diff --git a/examples/async_await/bin/get_order.dart b/examples/async_await/bin/get_order.dart index 10c5bce27e..f9b6c9d4da 100644 --- a/examples/async_await/bin/get_order.dart +++ b/examples/async_await/bin/get_order.dart @@ -4,11 +4,8 @@ Future createOrderMessage() async { } Future fetchUserOrder() => - // Imagine that this function is more complex and slow. - Future.delayed( - const Duration(seconds: 2), - () => 'Large Latte', - ); +// Imagine that this function is more complex and slow. +Future.delayed(const Duration(seconds: 2), () => 'Large Latte'); // #docregion main-sig Future main() async { diff --git a/examples/async_await/bin/get_order_sync_bad.dart b/examples/async_await/bin/get_order_sync_bad.dart index 1247fc47e0..4f266a8d85 100644 --- a/examples/async_await/bin/get_order_sync_bad.dart +++ b/examples/async_await/bin/get_order_sync_bad.dart @@ -7,11 +7,8 @@ String createOrderMessage() { } Future fetchUserOrder() => - // Imagine that this function is more complex and slow. - Future.delayed( - const Duration(seconds: 2), - () => 'Large Latte', - ); +// Imagine that this function is more complex and slow. +Future.delayed(const Duration(seconds: 2), () => 'Large Latte'); // #docregion main-sig void main() { @@ -19,4 +16,5 @@ void main() { print('Fetching user order...'); print(createOrderMessage()); } + // #enddocregion no-warning diff --git a/examples/async_await/bin/try_catch.dart b/examples/async_await/bin/try_catch.dart index 99d0e29946..1260fb8baf 100644 --- a/examples/async_await/bin/try_catch.dart +++ b/examples/async_await/bin/try_catch.dart @@ -13,9 +13,10 @@ Future printOrderMessage() async { Future fetchUserOrder() { // Imagine that this function is more complex. var str = Future.delayed( - const Duration(seconds: 4), - // ignore: only_throw_errors - () => throw 'Cannot locate user order'); + const Duration(seconds: 4), + // ignore: only_throw_errors + () => throw 'Cannot locate user order', + ); return str; } diff --git a/examples/async_await/lib/practice_errors/solution.dart b/examples/async_await/lib/practice_errors/solution.dart index 19ba318e03..97dfb35cd8 100644 --- a/examples/async_await/lib/practice_errors/solution.dart +++ b/examples/async_await/lib/practice_errors/solution.dart @@ -8,4 +8,5 @@ Future changeUsername() async { return err.toString(); } } + // #enddocregion diff --git a/examples/async_await/lib/practice_errors/test.dart b/examples/async_await/lib/practice_errors/test.dart index b5fec94ba2..1817181f6f 100644 --- a/examples/async_await/lib/practice_errors/test.dart +++ b/examples/async_await/lib/practice_errors/test.dart @@ -24,22 +24,28 @@ Future fetchNewUsername() { void main() async { try { messages - ..add(makeReadable( + ..add( + makeReadable( testLabel: '', testResult: await asyncDidCatchException(changeUsername), readableErrors: { typoMessage: typoMessage, noCatch: 'Did you remember to call fetchNewUsername within a try/catch block?', - })) - ..add(makeReadable( + }, + ), + ) + ..add( + makeReadable( testLabel: '', testResult: await asyncErrorEquals(changeUsername), readableErrors: { typoMessage: typoMessage, noCatch: 'Did you remember to call fetchNewUsername within a try/catch block?', - })) + }, + ), + ) ..removeWhere((m) => m.contains(passed)) ..toList(); @@ -73,10 +79,11 @@ void passIfNoMessages(List messages, Map readable) { if (messages.isEmpty) { _result(true); } else { - final userMessages = messages - .where((message) => readable.containsKey(message)) - .map((message) => readable[message]!) - .toList(); + final userMessages = + messages + .where((message) => readable.containsKey(message)) + .map((message) => readable[message]!) + .toList(); print(messages); _result(false, userMessages); @@ -109,4 +116,5 @@ Future asyncDidCatchException(Function fn) async { return passed; } } + // #enddocregion diff --git a/examples/async_await/lib/practice_using/solution.dart b/examples/async_await/lib/practice_using/solution.dart index 84327a2b0d..c15f1981e5 100644 --- a/examples/async_await/lib/practice_using/solution.dart +++ b/examples/async_await/lib/practice_using/solution.dart @@ -10,4 +10,5 @@ Future reportLogins() async { var logins = await fetchLoginAmount(); return 'Total number of logins: $logins'; } + // #enddocregion diff --git a/examples/async_await/lib/practice_using/test.dart b/examples/async_await/lib/practice_using/test.dart index ea2fb8da26..778463c19f 100644 --- a/examples/async_await/lib/practice_using/test.dart +++ b/examples/async_await/lib/practice_using/test.dart @@ -20,12 +20,14 @@ Future fetchLoginAmount() => Future.delayed(oneSecond, () => logins); void main() async { try { messages - ..add(makeReadable( + ..add( + makeReadable( testLabel: 'Part 1', testResult: await asyncEquals( - expected: 'User role: administrator', - actual: await reportUserRole(), - typoKeyword: role), + expected: 'User role: administrator', + actual: await reportUserRole(), + typoKeyword: role, + ), readableErrors: { typoMessage: typoMessage, 'null': '$didNotImplement reportUserRole?', @@ -39,13 +41,17 @@ void main() async { '$testFailedMessage reportUserRole. Did you return a user role?', 'User role: tester': '$testFailedMessage reportUserRole. Did you invoke fetchRole to fetch the user\'s role?', - })) - ..add(makeReadable( + }, + ), + ) + ..add( + makeReadable( testLabel: 'Part 2', testResult: await asyncEquals( - expected: 'Total number of logins: 42', - actual: await reportLogins(), - typoKeyword: logins.toString()), + expected: 'Total number of logins: 42', + actual: await reportLogins(), + typoKeyword: logins.toString(), + ), readableErrors: { typoMessage: typoMessage, 'null': '$didNotImplement reportLogins?', @@ -59,7 +65,9 @@ void main() async { '$testFailedMessage reportLogins. Did you return the number of logins?', 'Total number of logins: 57': '$testFailedMessage reportLogins. Did you invoke fetchLoginAmount to fetch the number of user logins?', - })) + }, + ), + ) ..removeWhere((m) => m.contains(passed)) ..toList(); @@ -69,9 +77,7 @@ void main() async { _result(false, messages); } } on UnimplementedError { - _result(false, [ - '$didNotImplement reportUserRole?', - ]); + _result(false, ['$didNotImplement reportUserRole?']); } catch (e) { _result(false, ['Tried to run solution, but received an exception: $e']); } @@ -114,4 +120,5 @@ Future asyncEquals({ return e.toString(); } } + // #enddocregion diff --git a/examples/async_await/lib/putting_together/solution.dart b/examples/async_await/lib/putting_together/solution.dart index 516ef5c082..924ed06a19 100644 --- a/examples/async_await/lib/putting_together/solution.dart +++ b/examples/async_await/lib/putting_together/solution.dart @@ -16,4 +16,5 @@ Future sayGoodbye() async { return 'Failed to logout user: $e'; } } + // #enddocregion diff --git a/examples/async_await/lib/putting_together/test.dart b/examples/async_await/lib/putting_together/test.dart index 4e513f4026..89a59e3879 100644 --- a/examples/async_await/lib/putting_together/test.dart +++ b/examples/async_await/lib/putting_together/test.dart @@ -29,12 +29,14 @@ Future logoutUser() => Future.delayed(oneSecond, failOnce); void main() async { try { messages - ..add(makeReadable( + ..add( + makeReadable( testLabel: 'Part 1', testResult: await asyncEquals( - expected: 'Hello Jerry', - actual: addHello('Jerry'), - typoKeyword: 'Jerry'), + expected: 'Hello Jerry', + actual: addHello('Jerry'), + typoKeyword: 'Jerry', + ), readableErrors: { typoMessage: typoMessage, 'null': '$didNotImplement addHello?', @@ -42,13 +44,17 @@ void main() async { 'Looks like you forgot to use the \'await\' keyword!', 'Hello Instance of \'_Future\'': 'Looks like you forgot to use the \'await\' keyword!', - })) - ..add(makeReadable( + }, + ), + ) + ..add( + makeReadable( testLabel: 'Part 2', testResult: await asyncEquals( - expected: 'Hello Jean', - actual: await greetUser(), - typoKeyword: 'Jean'), + expected: 'Hello Jean', + actual: await greetUser(), + typoKeyword: 'Jean', + ), readableErrors: { typoMessage: typoMessage, 'null': '$didNotImplement greetUser?', @@ -62,8 +68,11 @@ void main() async { 'Did you place the \'\$\' character correctly?', '{Closure \'addHello\'(await fetchUsername())}': 'Did you place the \'\$\' character correctly?', - })) - ..add(makeReadable( + }, + ), + ) + ..add( + makeReadable( testLabel: 'Part 3', testResult: await asyncDidCatchException(sayGoodbye), readableErrors: { @@ -76,13 +85,17 @@ void main() async { 'Did you remember to use the \'await\' keyword in the sayGoodbye function?', 'Instance of \'_Future\' Thanks, see you next time': 'Did you remember to use the \'await\' keyword in the sayGoodbye function?', - })) - ..add(makeReadable( + }, + ), + ) + ..add( + makeReadable( testLabel: 'Part 3', testResult: await asyncEquals( - expected: 'Success! Thanks, see you next time', - actual: await sayGoodbye(), - typoKeyword: 'Success'), + expected: 'Success! Thanks, see you next time', + actual: await sayGoodbye(), + typoKeyword: 'Success', + ), readableErrors: { typoMessage: '$typoMessage. Did you add the text \'Thanks, see you next time\'?', @@ -95,7 +108,9 @@ void main() async { 'Did you remember to use the \'await\' keyword in the sayGoodbye function?', 'Instance of \'_Exception\'': 'CAUGHT Did you remember to return a string?', - })) + }, + ), + ) ..removeWhere((m) => m.contains(passed)) ..toList(); @@ -133,10 +148,11 @@ void passIfNoMessages(List messages, Map readable) { if (messages.isEmpty) { _result(true); } else { - final userMessages = messages - .where((message) => readable.containsKey(message)) - .map((message) => readable[message]!) - .toList(); + final userMessages = + messages + .where((message) => readable.containsKey(message)) + .map((message) => readable[message]!) + .toList(); print(messages); _result(false, userMessages); @@ -179,4 +195,5 @@ Future asyncDidCatchException(Function fn) async { return noCatch; } } + // #enddocregion diff --git a/examples/async_await/pubspec.yaml b/examples/async_await/pubspec.yaml index ea6a98bc96..a11c5bb7bc 100644 --- a/examples/async_await/pubspec.yaml +++ b/examples/async_await/pubspec.yaml @@ -3,7 +3,7 @@ description: dart.dev example code. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: examples_util: {path: ../util} diff --git a/examples/async_await/test/async_await_test.dart b/examples/async_await/test/async_await_test.dart index d0b90085f5..1f4411879d 100644 --- a/examples/async_await/test/async_await_test.dart +++ b/examples/async_await/test/async_await_test.dart @@ -26,11 +26,12 @@ void main() { Large Latte '''; expect( - () => Future.wait([ - Future.delayed(const Duration(seconds: 4)), - Future.sync(futures_intro.main), - ]), - m.printsLines(output)); + () => Future.wait([ + Future.delayed(const Duration(seconds: 4)), + Future.sync(futures_intro.main), + ]), + m.printsLines(output), + ); }); test('get_order_sync_bad', () { diff --git a/examples/build_runner_usage/pubspec.yaml b/examples/build_runner_usage/pubspec.yaml index faec233805..3a69d2203c 100644 --- a/examples/build_runner_usage/pubspec.yaml +++ b/examples/build_runner_usage/pubspec.yaml @@ -3,7 +3,7 @@ description: dart.dev build_runner example code. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dev_dependencies: args: ^2.5.0 diff --git a/examples/cli/bin/dcat.dart b/examples/cli/bin/dcat.dart index 7c5ddfe077..46bac3186c 100644 --- a/examples/cli/bin/dcat.dart +++ b/examples/cli/bin/dcat.dart @@ -68,5 +68,6 @@ Future _handleError(String path) async { } // #enddocregion await-entity } + // #enddocregion handle-error // #enddocregion dcat-app diff --git a/examples/cli/pubspec.yaml b/examples/cli/pubspec.yaml index ec0ffbca1a..cd0f8929d7 100644 --- a/examples/cli/pubspec.yaml +++ b/examples/cli/pubspec.yaml @@ -3,7 +3,7 @@ description: Examples for CLI tutorials on dart.dev resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: args: ^2.5.0 diff --git a/examples/concurrency/lib/async_number_of_keys.dart b/examples/concurrency/lib/async_number_of_keys.dart index 82da3a2758..b7d4351d5c 100644 --- a/examples/concurrency/lib/async_number_of_keys.dart +++ b/examples/concurrency/lib/async_number_of_keys.dart @@ -18,4 +18,5 @@ Future _readFileAsync() async { final contents = await file.readAsString(); return contents.trim(); } + // #enddocregion non-blocking diff --git a/examples/concurrency/lib/basic_ports_example/complete.dart b/examples/concurrency/lib/basic_ports_example/complete.dart index 96171c3035..1f6d7bb69a 100644 --- a/examples/concurrency/lib/basic_ports_example/complete.dart +++ b/examples/concurrency/lib/basic_ports_example/complete.dart @@ -50,5 +50,6 @@ class Worker { await _isolateReady.future; _sendPort.send(message); } + // #enddocregion parse-json } diff --git a/examples/concurrency/lib/basic_ports_example/handle_response_from_isolate.dart b/examples/concurrency/lib/basic_ports_example/handle_response_from_isolate.dart index ad7bd7cb48..058d12cc44 100644 --- a/examples/concurrency/lib/basic_ports_example/handle_response_from_isolate.dart +++ b/examples/concurrency/lib/basic_ports_example/handle_response_from_isolate.dart @@ -18,8 +18,8 @@ class Worker { } } -// rest of class.. -// #enddocregion + // rest of class.. + // #enddocregion Future spawn() async { final receivePort = ReceivePort(); diff --git a/examples/concurrency/lib/basic_ports_example/parse_json.dart b/examples/concurrency/lib/basic_ports_example/parse_json.dart index 75b8dab15b..559a1d0c16 100644 --- a/examples/concurrency/lib/basic_ports_example/parse_json.dart +++ b/examples/concurrency/lib/basic_ports_example/parse_json.dart @@ -23,8 +23,8 @@ class Worker { await _isolateReady.future; _sendPort.send(message); } -// rest of class.. -// #enddocregion + // rest of class.. + // #enddocregion Future spawn() async { final receivePort = ReceivePort(); diff --git a/examples/concurrency/lib/basic_ports_example/start.dart b/examples/concurrency/lib/basic_ports_example/start.dart index f7b5983d27..e8968b77fb 100644 --- a/examples/concurrency/lib/basic_ports_example/start.dart +++ b/examples/concurrency/lib/basic_ports_example/start.dart @@ -20,4 +20,5 @@ class Worker { // be used to send messages to the worker isolate. } } + // #enddocregion worker diff --git a/examples/concurrency/lib/future_syntax.dart b/examples/concurrency/lib/future_syntax.dart index 4a65d83375..8a8218447e 100644 --- a/examples/concurrency/lib/future_syntax.dart +++ b/examples/concurrency/lib/future_syntax.dart @@ -11,4 +11,5 @@ Future _readFileAsync(String filename) { return contents.trim(); }); } + // #enddocregion read-async diff --git a/examples/concurrency/lib/isolate_run_syntax.dart b/examples/concurrency/lib/isolate_run_syntax.dart index 4f3cd6663e..2dd29a57c8 100644 --- a/examples/concurrency/lib/isolate_run_syntax.dart +++ b/examples/concurrency/lib/isolate_run_syntax.dart @@ -8,4 +8,5 @@ void fib40() async { var result = await Isolate.run(() => slowFib(40)); print('Fib(40) = $result'); } + // #enddocregion slow diff --git a/examples/concurrency/lib/robust_ports_example/complete.dart b/examples/concurrency/lib/robust_ports_example/complete.dart index 660c1dcc06..371ee28b2e 100644 --- a/examples/concurrency/lib/robust_ports_example/complete.dart +++ b/examples/concurrency/lib/robust_ports_example/complete.dart @@ -8,7 +8,8 @@ void main() async { print(await worker.parseJson('"banana"')); print(await worker.parseJson('[true, false, null, 1, "string"]')); print( - await Future.wait([worker.parseJson('"yes"'), worker.parseJson('"no"')])); + await Future.wait([worker.parseJson('"yes"'), worker.parseJson('"no"')]), + ); worker.close(); } @@ -16,7 +17,7 @@ void main() async { class Worker { final SendPort _commands; final ReceivePort _responses; -// #enddocregion constructor + // #enddocregion constructor final Map> _activeRequests = {}; int _idCounter = 0; bool _closed = false; diff --git a/examples/concurrency/lib/robust_ports_example/spawn_1.dart b/examples/concurrency/lib/robust_ports_example/spawn_1.dart index 194cbc197a..500df3b98f 100644 --- a/examples/concurrency/lib/robust_ports_example/spawn_1.dart +++ b/examples/concurrency/lib/robust_ports_example/spawn_1.dart @@ -19,11 +19,11 @@ class Worker { commandPort, )); }; -// #enddocregion worker-spawn + // #enddocregion worker-spawn throw UnimplementedError(); -// #docregion worker-spawn + // #docregion worker-spawn } -// #enddocregion worker-spawn + // #enddocregion worker-spawn Future parseJson(String message) async { // TODO: Ensure the port is still open. @@ -45,4 +45,7 @@ class Worker { static void _startRemoteIsolate(SendPort sp) { // TODO: Initialize worker isolate's ports. } + // #docregion worker-spawn } + +// #enddocregion worker-spawn diff --git a/examples/concurrency/lib/robust_ports_example/spawn_2.dart b/examples/concurrency/lib/robust_ports_example/spawn_2.dart index 643d70c431..b642dbd87d 100644 --- a/examples/concurrency/lib/robust_ports_example/spawn_2.dart +++ b/examples/concurrency/lib/robust_ports_example/spawn_2.dart @@ -32,7 +32,7 @@ class Worker { return Worker._(receivePort, sendPort); } -// #enddocregion worker-spawn + // #enddocregion worker-spawn Future parseJson(String message) async { // TODO: Ensure the port is still open. @@ -54,4 +54,7 @@ class Worker { static void _startRemoteIsolate(SendPort sp) { // TODO: Initialize worker isolate's ports. } + // #docregion worker-spawn } + +// #enddocregion worker-spawn diff --git a/examples/concurrency/lib/robust_ports_example/start.dart b/examples/concurrency/lib/robust_ports_example/start.dart index b84baf8579..54ea814122 100644 --- a/examples/concurrency/lib/robust_ports_example/start.dart +++ b/examples/concurrency/lib/robust_ports_example/start.dart @@ -34,4 +34,5 @@ class Worker { // TODO: Initialize worker isolate's ports. } } + // #enddocregion worker diff --git a/examples/concurrency/lib/robust_ports_example/step_4.dart b/examples/concurrency/lib/robust_ports_example/step_4.dart index 233b14f7c5..8a99bcc09e 100644 --- a/examples/concurrency/lib/robust_ports_example/step_4.dart +++ b/examples/concurrency/lib/robust_ports_example/step_4.dart @@ -8,7 +8,8 @@ import 'dart:isolate'; class Worker { final SendPort _commands; final ReceivePort _responses; -// #enddocregion constructor + // #enddocregion constructor + static Future spawn() async { // Create a receive port and add its initial message handler final initPort = RawReceivePort(); @@ -34,19 +35,20 @@ class Worker { return Worker._(receivePort, sendPort); } -// #docregion parse-json + // #docregion parse-json Future parseJson(String message) async { _commands.send(message); } -// #enddocregion parse-json + // #enddocregion parse-json + + // #docregion constructor -// #docregion constructor Worker._(this._responses, this._commands) { _responses.listen(_handleResponsesFromIsolate); } -// #enddocregion constructor + // #enddocregion constructor -// #docregion handle-response + // #docregion handle-response void _handleResponsesFromIsolate(dynamic message) { if (message is RemoteError) { throw message; @@ -54,11 +56,13 @@ class Worker { print(message); } } -// #enddocregion handle-response + // #enddocregion handle-response -// #docregion handle-commands + // #docregion handle-commands static void _handleCommandsToIsolate( - ReceivePort receivePort, SendPort sendPort) { + ReceivePort receivePort, + SendPort sendPort, + ) { receivePort.listen((message) { try { final jsonData = jsonDecode(message as String); @@ -68,13 +72,17 @@ class Worker { } }); } -// #enddocregion handle-commands + // #enddocregion handle-commands -// #docregion start-isolate + // #docregion start-isolate static void _startRemoteIsolate(SendPort sendPort) { final receivePort = ReceivePort(); sendPort.send(receivePort.sendPort); _handleCommandsToIsolate(receivePort, sendPort); } -// #enddocregion start-isolate + + // #enddocregion start-isolate + // #docregion constructor } + +// #enddocregion constructor diff --git a/examples/concurrency/lib/robust_ports_example/step_5_add_completers.dart b/examples/concurrency/lib/robust_ports_example/step_5_add_completers.dart index b39edb26d6..356cd9aee7 100644 --- a/examples/concurrency/lib/robust_ports_example/step_5_add_completers.dart +++ b/examples/concurrency/lib/robust_ports_example/step_5_add_completers.dart @@ -10,7 +10,7 @@ class Worker { final ReceivePort _responses; final Map> _activeRequests = {}; int _idCounter = 0; -// #enddocregion vars + // #enddocregion vars static Future spawn() async { // Create a receive port and add its initial message handler @@ -37,7 +37,7 @@ class Worker { return Worker._(receivePort, sendPort); } -// #docregion parse-json + // #docregion parse-json Future parseJson(String message) async { final completer = Completer.sync(); final id = _idCounter++; @@ -45,15 +45,15 @@ class Worker { _commands.send((id, message)); return await completer.future; } -// #enddocregion parse-json + // #enddocregion parse-json -// #docregion constructor + // #docregion constructor Worker._(this._responses, this._commands) { _responses.listen(_handleResponsesFromIsolate); } -// #enddocregion constructor + // #enddocregion constructor -// #docregion handle-response + // #docregion handle-response void _handleResponsesFromIsolate(dynamic message) { final (int id, Object? response) = message as (int, Object?); // New final completer = _activeRequests.remove(id)!; // New @@ -64,11 +64,13 @@ class Worker { completer.complete(response); // Updated } } -// #enddocregion handle-response + // #enddocregion handle-response -// #docregion handle-commands + // #docregion handle-commands static void _handleCommandsToIsolate( - ReceivePort receivePort, SendPort sendPort) { + ReceivePort receivePort, + SendPort sendPort, + ) { receivePort.listen((message) { final (int id, String jsonText) = message as (int, String); // New try { @@ -79,13 +81,17 @@ class Worker { } }); } -// #enddocregion handle-commands + // #enddocregion handle-commands -// #docregion start-isolate + // #docregion start-isolate static void _startRemoteIsolate(SendPort sendPort) { final receivePort = ReceivePort(); sendPort.send(receivePort.sendPort); _handleCommandsToIsolate(receivePort, sendPort); } -// #enddocregion start-isolate + + // #enddocregion start-isolate + // #docregion vars } + +// #enddocregion vars diff --git a/examples/concurrency/lib/robust_ports_example/step_6_close_ports.dart b/examples/concurrency/lib/robust_ports_example/step_6_close_ports.dart index 759c70dc94..fa5b53d3ab 100644 --- a/examples/concurrency/lib/robust_ports_example/step_6_close_ports.dart +++ b/examples/concurrency/lib/robust_ports_example/step_6_close_ports.dart @@ -6,7 +6,7 @@ import 'dart:isolate'; // #docregion close class Worker { bool _closed = false; -// #enddocregion close + // #enddocregion close final SendPort _commands; final ReceivePort _responses; @@ -92,7 +92,7 @@ class Worker { _handleCommandsToIsolate(receivePort, sendPort); } -// #docregion close + // #docregion close void close() { if (!_closed) { _closed = true; @@ -101,5 +101,6 @@ class Worker { print('--- port closed --- '); } } -// #enddocregion close } + +// #enddocregion close diff --git a/examples/concurrency/lib/simple_isolate_closure.dart b/examples/concurrency/lib/simple_isolate_closure.dart index b01a84dd5e..987c85eab5 100644 --- a/examples/concurrency/lib/simple_isolate_closure.dart +++ b/examples/concurrency/lib/simple_isolate_closure.dart @@ -16,4 +16,5 @@ void main() async { // Use that data. print('Number of JSON keys: ${jsonData.length}'); } + // #enddocregion worker diff --git a/examples/concurrency/lib/simple_worker_isolate.dart b/examples/concurrency/lib/simple_worker_isolate.dart index 9d73c9e31d..3bc7c07ad3 100644 --- a/examples/concurrency/lib/simple_worker_isolate.dart +++ b/examples/concurrency/lib/simple_worker_isolate.dart @@ -20,4 +20,5 @@ Future> _readAndParseJson() async { final jsonData = jsonDecode(fileData) as Map; return jsonData; } + // #enddocregion spawned diff --git a/examples/concurrency/lib/sync_number_of_keys.dart b/examples/concurrency/lib/sync_number_of_keys.dart index a39afd35f0..926419cc96 100644 --- a/examples/concurrency/lib/sync_number_of_keys.dart +++ b/examples/concurrency/lib/sync_number_of_keys.dart @@ -18,4 +18,5 @@ String _readFileSync() { final contents = file.readAsStringSync(); return contents.trim(); } + // #enddocregion blocking diff --git a/examples/concurrency/pubspec.yaml b/examples/concurrency/pubspec.yaml index 056667349f..034eebdeb2 100644 --- a/examples/concurrency/pubspec.yaml +++ b/examples/concurrency/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: http: any diff --git a/examples/create_libraries/lib/hw_mp.dart b/examples/create_libraries/lib/hw_mp.dart index 979d04e46c..28d74a62ae 100644 --- a/examples/create_libraries/lib/hw_mp.dart +++ b/examples/create_libraries/lib/hw_mp.dart @@ -5,4 +5,5 @@ library; export 'src/hw_none.dart' // Stub implementation if (dart.library.io) 'src/hw_io.dart' // dart:io implementation if (dart.library.js_interop) 'src/hw_web.dart'; // package:web implementation + // #enddocregion export diff --git a/examples/create_libraries/pubspec.yaml b/examples/create_libraries/pubspec.yaml index e159258fe5..32e861fea3 100644 --- a/examples/create_libraries/pubspec.yaml +++ b/examples/create_libraries/pubspec.yaml @@ -4,7 +4,7 @@ version: 1.0.0 resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: web: ^1.1.0 diff --git a/examples/extension_methods/lib/string_extensions/string_apis.dart b/examples/extension_methods/lib/string_extensions/string_apis.dart index b1230cd163..affddeddad 100644 --- a/examples/extension_methods/lib/string_extensions/string_apis.dart +++ b/examples/extension_methods/lib/string_extensions/string_apis.dart @@ -8,6 +8,8 @@ extension NumberParsing on String { double parseDouble() { return double.parse(this); } + // #docregion parseInt } + // #enddocregion parseInt diff --git a/examples/extension_methods/lib/string_extensions/usage_explicit.dart b/examples/extension_methods/lib/string_extensions/usage_explicit.dart index a388b4b9cd..75541fa312 100644 --- a/examples/extension_methods/lib/string_extensions/usage_explicit.dart +++ b/examples/extension_methods/lib/string_extensions/usage_explicit.dart @@ -4,12 +4,14 @@ import 'string_apis.dart'; // Contains NumberParsing extension. import 'string_apis_2.dart'; // Contains NumberParsing2 extension. -// #enddocregion conflicts-explicit void main() { -// #docregion conflicts-explicit -// print('42'.parseInt()); // Doesn't work. + // #docregion conflicts-explicit + // print('42'.parseInt()); // Doesn't work. print(NumberParsing('42').parseInt()); print(NumberParsing2('42').parseInt()); -// #enddocregion conflicts-explicit + // #enddocregion conflicts-explicit print('42'.parseDouble()); + // #docregion conflicts-explicit } + +// #enddocregion conflicts-explicit diff --git a/examples/extension_methods/lib/string_extensions/usage_import.dart b/examples/extension_methods/lib/string_extensions/usage_import.dart index b50afe3081..32f7138e46 100644 --- a/examples/extension_methods/lib/string_extensions/usage_import.dart +++ b/examples/extension_methods/lib/string_extensions/usage_import.dart @@ -6,16 +6,17 @@ import 'string_apis.dart'; // hides that extension method. import 'string_apis_2.dart' hide NumberParsing2; -// #enddocregion hide-conflicts void main() { -// #docregion hide-conflicts // Uses the parseInt() defined in 'string_apis.dart'. print('42'.parseInt()); -// #enddocregion hide-conflicts + // #enddocregion hide-conflicts // Uses parseHexInt(), defined in 'string_apis_2.dart'. print('42'.parseHexInt()); // Uses the parseDouble() defined in 'string_apis.dart'. print('42'.parseDouble()); + // #docregion hide-conflicts } + +// #enddocregion hide-conflicts diff --git a/examples/extension_methods/lib/string_extensions/usage_prefix.dart b/examples/extension_methods/lib/string_extensions/usage_prefix.dart index f363da6c8c..c5c70642a7 100644 --- a/examples/extension_methods/lib/string_extensions/usage_prefix.dart +++ b/examples/extension_methods/lib/string_extensions/usage_prefix.dart @@ -1,14 +1,11 @@ -// #docregion conflicts-prefix // Both libraries define extensions named NumberParsing // that contain the extension method parseInt(). One NumberParsing // extension (in 'string_apis_3.dart') also defines parseNum(). import 'string_apis.dart'; import 'string_apis_3.dart' as rad; -// #enddocregion conflicts-prefix void main() { -// #docregion conflicts-prefix -// print('42'.parseInt()); // Doesn't work. + // print('42'.parseInt()); // Doesn't work. // Use the ParseNumbers extension from string_apis.dart. print(NumberParsing('42').parseInt()); @@ -18,5 +15,4 @@ void main() { // Only string_apis_3.dart has parseNum(). print('42'.parseNum()); -// #enddocregion conflicts-prefix } diff --git a/examples/extension_methods/lib/string_extensions/usage_simple_extension.dart b/examples/extension_methods/lib/string_extensions/usage_simple_extension.dart index df4e090183..ecc7ecf680 100644 --- a/examples/extension_methods/lib/string_extensions/usage_simple_extension.dart +++ b/examples/extension_methods/lib/string_extensions/usage_simple_extension.dart @@ -3,19 +3,19 @@ // Import a library that contains an extension on String. // #docregion basic import 'string_apis.dart'; -// #enddocregion basic, import-and-use void main() { + // #enddocregion basic, import-and-use // WithOUT extension methods. print(int.parse('42')); print(double.parse('42')); // WITH extension methods. -// #docregion import-and-use + // #docregion import-and-use print('42'.padLeft(5)); // Use a String method. -// #docregion basic + // #docregion basic print('42'.parseInt()); // Use an extension method. -// #enddocregion basic, import-and-use + // #enddocregion basic, import-and-use print('42'.parseDouble()); // var vs. dynamic. @@ -35,4 +35,7 @@ void main() { // #enddocregion dynamic } print(d); // Avoid unused_local_variable hint. + // #docregion basic, import-and-use } + +// #enddocregion basic, import-and-use diff --git a/examples/extension_methods/pubspec.yaml b/examples/extension_methods/pubspec.yaml index fefda9e294..6a30a3f7fe 100644 --- a/examples/extension_methods/pubspec.yaml +++ b/examples/extension_methods/pubspec.yaml @@ -4,7 +4,7 @@ version: 1.0.0 resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dev_dependencies: test: ^1.25.8 diff --git a/examples/fetch_data/bin/fetch_http_package.dart b/examples/fetch_data/bin/fetch_http_package.dart index 5ed11f0b0a..423516c409 100644 --- a/examples/fetch_data/bin/fetch_http_package.dart +++ b/examples/fetch_data/bin/fetch_http_package.dart @@ -102,6 +102,8 @@ class PackageRetrievalException implements Exception { buf.write('!'); return buf.toString(); } + // #docregion get-package } + // #enddocregion get-package diff --git a/examples/fetch_data/lib/fetch_data.dart b/examples/fetch_data/lib/fetch_data.dart index ed764f3520..fd9376128a 100644 --- a/examples/fetch_data/lib/fetch_data.dart +++ b/examples/fetch_data/lib/fetch_data.dart @@ -40,8 +40,10 @@ void getMain() async { void headers() async { // #docregion http-headers - await http.get(Uri.https('dart.dev', '/f/packages/http.json'), - headers: {'User-Agent': '/'}); + await http.get( + Uri.https('dart.dev', '/f/packages/http.json'), + headers: {'User-Agent': '/'}, + ); // #enddocregion http-headers } @@ -79,4 +81,5 @@ void retryMain() async { client.close(); } } + // #enddocregion http-retry diff --git a/examples/fetch_data/pubspec.yaml b/examples/fetch_data/pubspec.yaml index 88a9404566..d3be3e0337 100644 --- a/examples/fetch_data/pubspec.yaml +++ b/examples/fetch_data/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.1 resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: http: ^1.2.2 diff --git a/examples/futures/bin/mixing_errors_problematic.dart b/examples/futures/bin/mixing_errors_problematic.dart index 6d93c52f27..51a3f1ec26 100644 --- a/examples/futures/bin/mixing_errors_problematic.dart +++ b/examples/futures/bin/mixing_errors_problematic.dart @@ -39,4 +39,5 @@ Future fragileFunc() { ellipsis(); }); } + // #enddocregion fragile diff --git a/examples/futures/lib/early_error_handlers.dart b/examples/futures/lib/early_error_handlers.dart index ad285832f8..a195074541 100644 --- a/examples/futures/lib/early_error_handlers.dart +++ b/examples/futures/lib/early_error_handlers.dart @@ -22,4 +22,5 @@ void mainGood() { .catchError(ellipsis()); // We get here. }); } + // #enddocregion good diff --git a/examples/futures/lib/long_chain.dart b/examples/futures/lib/long_chain.dart index f8b1eece90..86b2365dc8 100644 --- a/examples/futures/lib/long_chain.dart +++ b/examples/futures/lib/long_chain.dart @@ -10,11 +10,12 @@ void main() { .then((_) => four()) // Future completes with two()'s error. .then((value) => value.length) // Future completes with two()'s error. .catchError((e) { - print('Got error: $e'); // Finally, callback fires. - return 42; // Future completes with 42. - }).then((value) { - print('The value is $value'); - }); + print('Got error: $e'); // Finally, callback fires. + return 42; // Future completes with 42. + }) + .then((value) { + print('The value is $value'); + }); } // Output of this program: diff --git a/examples/futures/lib/simple.dart b/examples/futures/lib/simple.dart index 809e033171..54c825b3cc 100644 --- a/examples/futures/lib/simple.dart +++ b/examples/futures/lib/simple.dart @@ -14,20 +14,27 @@ void simpleCallbacks() { { // #docregion comprehensive-errors - myFunc().then((value) { - doSomethingWith(value); - ellipsis(); - throw Exception('Some arbitrary error'); - }).catchError(handleError); + myFunc() + .then((value) { + doSomethingWith(value); + ellipsis(); + throw Exception('Some arbitrary error'); + }) + .catchError(handleError); // #enddocregion comprehensive-errors } { // #docregion throws-then-catch - asyncErrorFunction().then(successCallback, onError: (e) { - handleError(e); // Original error. - anotherAsyncErrorFunction(); // Oops, new error. - }).catchError(handleError); // Error from within then() handled. + asyncErrorFunction() + .then( + successCallback, + onError: (e) { + handleError(e); // Original error. + anotherAsyncErrorFunction(); // Oops, new error. + }, + ) + .catchError(handleError); // Error from within then() handled. // #enddocregion throws-then-catch } @@ -62,8 +69,10 @@ void main() { handleAuthResponse(const {'username': 'dash', 'age': 3}) .then((_) => ellipsis()) .catchError(handleFormatException, test: (e) => e is FormatException) - .catchError(handleAuthorizationException, - test: (e) => e is AuthorizationException); + .catchError( + handleAuthorizationException, + test: (e) => e is AuthorizationException, + ); } // #enddocregion auth-response diff --git a/examples/futures/lib/when_complete.dart b/examples/futures/lib/when_complete.dart index ead2a44918..3dcaff6cfe 100644 --- a/examples/futures/lib/when_complete.dart +++ b/examples/futures/lib/when_complete.dart @@ -21,10 +21,11 @@ void withObjectMain() { // Future completes with an error: .then((_) => ellipsis()) .catchError((e) { - handleError(e); - printErrorMessage(); - return someObject; // Future completes with someObject - }).whenComplete(() => print('Done!')); // Future completes with someObject + handleError(e); + printErrorMessage(); + return someObject; // Future completes with someObject + }) + .whenComplete(() => print('Done!')); // Future completes with someObject } // #enddocregion with-object diff --git a/examples/futures/pubspec.yaml b/examples/futures/pubspec.yaml index 090a8f6ac3..734826d2c2 100644 --- a/examples/futures/pubspec.yaml +++ b/examples/futures/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: examples_util: {path: ../util} diff --git a/examples/html/lib/html.dart b/examples/html/lib/html.dart index a956bc9154..1073fd78b5 100644 --- a/examples/html/lib/html.dart +++ b/examples/html/lib/html.dart @@ -16,9 +16,7 @@ void miscDeclAnalyzedButNotTested() { List divElements = querySelectorAll('div'); // Find all text inputs. - List textInputElements = querySelectorAll( - 'input[type="text"]', - ); + List textInputElements = querySelectorAll('input[type="text"]'); // Find all elements with the CSS class 'class' // inside of a

that is inside an element with @@ -41,9 +39,7 @@ void miscDeclAnalyzedButNotTested() { // #enddocregion creating-elements // #docregion creating-from-html - var elem2 = Element.html( - '

Creating is easy!

', - ); + var elem2 = Element.html('

Creating is easy!

'); // #enddocregion creating-from-html // #docregion body-children-add @@ -79,9 +75,10 @@ void miscDeclAnalyzedButNotTested() { { // #docregion elem-set-cascade - var message = DivElement() - ..id = 'message2' - ..text = 'Please subscribe to the Dart mailing list.'; + var message = + DivElement() + ..id = 'message2' + ..text = 'Please subscribe to the Dart mailing list.'; // #enddocregion elem-set-cascade // #docregion set-style diff --git a/examples/html/pubspec.yaml b/examples/html/pubspec.yaml index bb026b5323..32522bffba 100644 --- a/examples/html/pubspec.yaml +++ b/examples/html/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.1 resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dev_dependencies: test: ^1.25.8 diff --git a/examples/html/test/html_test.dart b/examples/html/test/html_test.dart index f9f6f110f3..2f37dc7b7d 100644 --- a/examples/html/test/html_test.dart +++ b/examples/html/test/html_test.dart @@ -70,10 +70,7 @@ void main() { String pageHtml = await HttpRequest.getString(url); // Do something with pageHtml... // #enddocregion get-string - expect( - pageHtml.substring(0, 250), - contains('httpbin'), - ); + expect(pageHtml.substring(0, 250), contains('<title>httpbin')); // #docregion get-string } // #enddocregion get-string @@ -85,10 +82,7 @@ void main() { final url = 'https://httpbin.org/headers'; // #docregion request Future<void> main() async { - HttpRequest req = await HttpRequest.request( - url, - method: 'HEAD', - ); + HttpRequest req = await HttpRequest.request(url, method: 'HEAD'); if (req.status == 200) { // Successful URL access... } @@ -105,8 +99,10 @@ void main() { const url = 'https://httpbin.org/post'; // #docregion POST String encodeMap(Map<String, String> data) => data.entries - .map((e) => - '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}') + .map( + (e) => + '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}', + ) .join('&'); void main() async { @@ -115,10 +111,7 @@ void main() { var request = HttpRequest(); request ..open('POST', url) - ..setRequestHeader( - 'Content-type', - 'application/x-www-form-urlencoded', - ) + ..setRequestHeader('Content-type', 'application/x-www-form-urlencoded') ..send(encodeMap(data)); await request.onLoadEnd.first; @@ -152,8 +145,10 @@ void main() { void scheduleReconnect() { if (!reconnectScheduled) { - Timer(Duration(seconds: retrySeconds), - () => initWebSocket(retrySeconds * 2)); + Timer( + Duration(seconds: retrySeconds), + () => initWebSocket(retrySeconds * 2), + ); } reconnectScheduled = true; } @@ -196,11 +191,9 @@ void main() { try { initWebSocket(); expect( - await t.first, - anyOf([ - contains('Received message'), - contains('Timeout'), - ])); + await t.first, + anyOf([contains('Received message'), contains('Timeout')]), + ); } finally { await wsStream.close(); } diff --git a/examples/iterables/pubspec.yaml b/examples/iterables/pubspec.yaml index c052135eda..c4e49a1a02 100644 --- a/examples/iterables/pubspec.yaml +++ b/examples/iterables/pubspec.yaml @@ -3,7 +3,7 @@ description: dart.dev example code. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dev_dependencies: examples_util: {path: ../util} diff --git a/examples/iterables/test/iterables_test.dart b/examples/iterables/test/iterables_test.dart index 23ae6ac7c3..11ddf5f2b1 100644 --- a/examples/iterables/test/iterables_test.dart +++ b/examples/iterables/test/iterables_test.dart @@ -64,9 +64,9 @@ void main() { // #enddocregion any-every expect( - main, - prints( - 'At least one item contains "a"\nAll items have length >= 5\n')); + main, + prints('At least one item contains "a"\nAll items have length >= 5\n'), + ); }); test('firstWhere_example', () { @@ -113,13 +113,21 @@ void main() { expect(predicate('Soda'), isFalse); expect( - main, - prints(allOf( - stringContainsInOrder( - ['Popcorn\n', 'Popcorn\n', 'Popcorn\n', 'None!\n']), - isNot(contains('Lasagne')), - isNot(contains('Salad')), - isNot(contains('Toast'))))); + main, + prints( + allOf( + stringContainsInOrder([ + 'Popcorn\n', + 'Popcorn\n', + 'Popcorn\n', + 'None!\n', + ]), + isNot(contains('Lasagne')), + isNot(contains('Salad')), + isNot(contains('Toast')), + ), + ), + ); }); test('iterable_example', () { @@ -151,8 +159,9 @@ void main() { test('takeWhile_example', () { const numbers = [1, 2, 3, -1, 4, 5]; // #docregion takewhile - var numbersUntilNegative = - numbers.takeWhile((number) => !number.isNegative); + var numbersUntilNegative = numbers.takeWhile( + (number) => !number.isNegative, + ); // #enddocregion takewhile expect(numbersUntilNegative, [1, 2, 3]); }); @@ -171,9 +180,14 @@ void main() { // #enddocregion take-while-long expect( - main, - prints(allOf(contains('Numbers until 0: (1, 3, -2)'), - contains('Numbers starting at 0: (0, 4, 5)')))); + main, + prints( + allOf( + contains('Numbers until 0: (1, 3, -2)'), + contains('Numbers starting at 0: (0, 4, 5)'), + ), + ), + ); }); test('where_example', () { @@ -212,9 +226,15 @@ void main() { // #enddocregion first-last expect( - main, - prints(allOf(contains('Salad'), contains('Toast'), - isNot(contains('Popcorn'))))); + main, + prints( + allOf( + contains('Salad'), + contains('Toast'), + isNot(contains('Popcorn')), + ), + ), + ); }); test('numbers_where', () { @@ -239,14 +259,18 @@ void main() { // #enddocregion numbers-where expect( - main, - prints(allOf( - isNot(contains('1 is even.\n')), - contains('-2 is even.\n'), - contains('42 is even.\n'), - isNot(contains('3 is even')), - contains('evenNumbers contains negative'), - contains('largeNumbers is empty')))); + main, + prints( + allOf( + isNot(contains('1 is even.\n')), + contains('-2 is even.\n'), + contains('42 is even.\n'), + isNot(contains('3 is even')), + contains('evenNumbers contains negative'), + contains('largeNumbers is empty'), + ), + ), + ); }); test('numbers_by_two', () { diff --git a/examples/language/lib/class_modifiers/ex1/b.dart b/examples/language/lib/class_modifiers/ex1/b.dart index 9460230f02..1d6f7480fb 100644 --- a/examples/language/lib/class_modifiers/ex1/b.dart +++ b/examples/language/lib/class_modifiers/ex1/b.dart @@ -23,4 +23,5 @@ class MockVehicle implements Vehicle { // ... } } + // #enddocregion abstract-usages diff --git a/examples/language/lib/class_modifiers/sealed_exhaustiveness.dart b/examples/language/lib/class_modifiers/sealed_exhaustiveness.dart index 8fb033f4ab..91134168d9 100644 --- a/examples/language/lib/class_modifiers/sealed_exhaustiveness.dart +++ b/examples/language/lib/class_modifiers/sealed_exhaustiveness.dart @@ -7,7 +7,7 @@ class Dusty extends Amigo {} class Ned extends Amigo {} String lastName(Amigo amigo) => switch (amigo) { - Lucky _ => 'Day', - Dusty _ => 'Bottoms', - Ned _ => 'Nederlander', - }; + Lucky _ => 'Day', + Dusty _ => 'Bottoms', + Ned _ => 'Nederlander', +}; diff --git a/examples/language/lib/control_flow/branches.dart b/examples/language/lib/control_flow/branches.dart index 5915f4d147..052c238322 100644 --- a/examples/language/lib/control_flow/branches.dart +++ b/examples/language/lib/control_flow/branches.dart @@ -123,7 +123,7 @@ dynamic miscDeclAnalyzedButNotTested() { slash || star || plus || minus => operator(charCode), comma || semicolon => punctuation(charCode), >= digit0 && <= digit9 => number(), - _ => throw FormatException('Invalid') + _ => throw FormatException('Invalid'), }; // #enddocregion switch-exp } diff --git a/examples/language/lib/patterns/algebraic_datatypes.dart b/examples/language/lib/patterns/algebraic_datatypes.dart index b93af84fbb..9a83e27b1f 100644 --- a/examples/language/lib/patterns/algebraic_datatypes.dart +++ b/examples/language/lib/patterns/algebraic_datatypes.dart @@ -14,7 +14,7 @@ class Circle implements Shape { } double calculateArea(Shape shape) => switch (shape) { - Square(length: var l) => l * l, - Circle(radius: var r) => math.pi * r * r - }; + Square(length: var l) => l * l, + Circle(radius: var r) => math.pi * r * r, +}; // #enddocregion algebraic-datatypes diff --git a/examples/language/lib/patterns/for_in.dart b/examples/language/lib/patterns/for_in.dart index 56eab4aba5..457f434144 100644 --- a/examples/language/lib/patterns/for_in.dart +++ b/examples/language/lib/patterns/for_in.dart @@ -1,9 +1,6 @@ void main() { // #docregion for-in-pattern - Map<String, int> hist = { - 'a': 23, - 'b': 100, - }; + Map<String, int> hist = {'a': 23, 'b': 100}; for (var MapEntry(key: key, value: count) in hist.entries) { print('$key occurred $count times'); diff --git a/examples/language/lib/patterns/json.dart b/examples/language/lib/patterns/json.dart index 08e4ad6e08..cc47e171a9 100644 --- a/examples/language/lib/patterns/json.dart +++ b/examples/language/lib/patterns/json.dart @@ -3,7 +3,7 @@ void main() { // #docregion json-1 var json = { - 'user': ['Lily', 13] + 'user': ['Lily', 13], }; var {'user': [name, age]} = json; // #enddocregion json-1 diff --git a/examples/language/lib/patterns/pattern_types.dart b/examples/language/lib/patterns/pattern_types.dart index 095c91ebbd..a3ae25ffd2 100644 --- a/examples/language/lib/patterns/pattern_types.dart +++ b/examples/language/lib/patterns/pattern_types.dart @@ -110,7 +110,7 @@ void miscDeclAnalyzedButNotTested() { // #docregion logical-or var isPrimary = switch (color) { Color.red || Color.yellow || Color.blue => true, - _ => false + _ => false, }; // #enddocregion logical-or } @@ -211,7 +211,7 @@ void miscDeclAnalyzedButNotTested() { == space => 'space', > space && < zero => 'punctuation', >= zero && <= nine => 'digit', - _ => '' + _ => '', }; } // #enddocregion relational @@ -271,7 +271,7 @@ void miscDeclAnalyzedButNotTested() { (x || y) && z => 'matches nothing', // ... // #enddocregion parens - _ => throw FormatException('Invalid') + _ => throw FormatException('Invalid'), }; } diff --git a/examples/language/lib/patterns/switch.dart b/examples/language/lib/patterns/switch.dart index 5ec3ca3b3c..37754adce0 100644 --- a/examples/language/lib/patterns/switch.dart +++ b/examples/language/lib/patterns/switch.dart @@ -70,7 +70,7 @@ void main() { // #docregion or-share-body var isPrimary = switch (color) { Color.red || Color.yellow || Color.blue => true, - _ => false + _ => false, }; // #enddocregion or-share-body print(isPrimary); diff --git a/examples/language/pubspec.yaml b/examples/language/pubspec.yaml index 6247b1a996..5e12c46fe6 100644 --- a/examples/language/pubspec.yaml +++ b/examples/language/pubspec.yaml @@ -3,7 +3,7 @@ description: dart.dev example code. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: examples_util: { path: ../util } diff --git a/examples/language/test/records_test.dart b/examples/language/test/records_test.dart index 218c1aa4c7..aec68e78bd 100644 --- a/examples/language/test/records_test.dart +++ b/examples/language/test/records_test.dart @@ -119,11 +119,7 @@ void main() { return (json['name'] as String, json['age'] as int); } - final json = <String, dynamic>{ - 'name': 'Dash', - 'age': 10, - 'color': 'blue', - }; + final json = <String, dynamic>{'name': 'Dash', 'age': 10, 'color': 'blue'}; // Destructures using a record pattern with positional fields: var (name, age) = userInfo(json); @@ -146,11 +142,7 @@ void main() { return (name: json['name'] as String, age: json['age'] as int); } - final json = <String, dynamic>{ - 'name': 'Dash', - 'age': 10, - 'color': 'blue', - }; + final json = <String, dynamic>{'name': 'Dash', 'age': 10, 'color': 'blue'}; // #docregion record-name-destructure // Destructures using a record pattern with named fields: final (:name, :age) = userInfo(json); diff --git a/examples/misc/bin/try_dart/classes.dart b/examples/misc/bin/try_dart/classes.dart index 6dc43af511..5293f622da 100644 --- a/examples/misc/bin/try_dart/classes.dart +++ b/examples/misc/bin/try_dart/classes.dart @@ -30,10 +30,7 @@ class DiamondSword extends Sword { void main() { // The 'new' keyword is optional. - var chest = Chest<Item>([ - DiamondSword(), - Sword(), - ]); + var chest = Chest<Item>([DiamondSword(), Sword()]); chest.use(); diff --git a/examples/misc/bin/try_dart/collection_literals.dart b/examples/misc/bin/try_dart/collection_literals.dart index e59b33a5ab..9510b64f29 100644 --- a/examples/misc/bin/try_dart/collection_literals.dart +++ b/examples/misc/bin/try_dart/collection_literals.dart @@ -3,18 +3,10 @@ const lostNumbers = [4, 8, 15, 16, 23, 42]; // A map literal. -const nobleGases = { - 'He': 'Helium', - 'Ne': 'Neon', - 'Ar': 'Argon', -}; +const nobleGases = {'He': 'Helium', 'Ne': 'Neon', 'Ar': 'Argon'}; // A set literal. -const frogs = { - 'Tree', - 'Poison dart', - 'Glass', -}; +const frogs = {'Tree', 'Poison dart', 'Glass'}; void main() { print(lostNumbers.last); diff --git a/examples/misc/bin/try_dart/strings.dart b/examples/misc/bin/try_dart/strings.dart index e01ac3942c..6d2ea17da5 100644 --- a/examples/misc/bin/try_dart/strings.dart +++ b/examples/misc/bin/try_dart/strings.dart @@ -6,7 +6,10 @@ void main() { print("a double quoted string"); // Strings can be combined by placing them adjacent to each other. - print('cat' 'dog'); + print( + 'cat' + 'dog', + ); // Triple quotes define a multi-line string. print('''triple quoted strings diff --git a/examples/misc/lib/articles/creating-streams/line_stream_generator.dart b/examples/misc/lib/articles/creating-streams/line_stream_generator.dart index 1fb3b4e959..3da8ffe50a 100755 --- a/examples/misc/lib/articles/creating-streams/line_stream_generator.dart +++ b/examples/misc/lib/articles/creating-streams/line_stream_generator.dart @@ -43,12 +43,15 @@ ex ea commodi consequatur? var text = StreamController<String>(); var lineStream = lines(text.stream); int lineCount = 0; - lineStream.listen((String line) { - lineCount++; - print('$lineCount: $line'); - }, onDone: () { - print('Lines received: $lineCount'); - }); + lineStream.listen( + (String line) { + lineCount++; + print('$lineCount: $line'); + }, + onDone: () { + print('Lines received: $lineCount'); + }, + ); text.add(part1); text.add(part2); text.add(part3); diff --git a/examples/misc/lib/articles/creating-streams/stream_controller.dart b/examples/misc/lib/articles/creating-streams/stream_controller.dart index 0de81dd0a4..4fd72822a6 100755 --- a/examples/misc/lib/articles/creating-streams/stream_controller.dart +++ b/examples/misc/lib/articles/creating-streams/stream_controller.dart @@ -47,22 +47,23 @@ Stream<int> timedCounter(Duration interval, [int? maxCount]) { } controller = StreamController<int>( - onListen: startTimer, - onPause: stopTimer, - onResume: startTimer, - onCancel: stopTimer); + onListen: startTimer, + onPause: stopTimer, + onResume: startTimer, + onCancel: stopTimer, + ); return controller.stream; } // #enddocregion better-stream void main() { -// showBasicUsage(); -// useMap(); -// useWhere(); -// useTransform(); -// useExpand(); -// useGenerator(); + // showBasicUsage(); + // useMap(); + // useWhere(); + // useTransform(); + // useExpand(); + // useGenerator(); useStreamFromFutureGenerator(); // useTake(); // demoPause(); @@ -82,8 +83,10 @@ void onListenHint() { void showBasicUsage() { // #docregion basic-usage - var counterStream = - Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15); + var counterStream = Stream<int>.periodic( + const Duration(seconds: 1), + (x) => x, + ).take(15); // #enddocregion basic-usage // #docregion basic-for-each @@ -92,8 +95,10 @@ void showBasicUsage() { } void demoPause() { - var counterStream = - Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15); + var counterStream = Stream<int>.periodic( + const Duration(seconds: 1), + (x) => x, + ).take(15); late StreamSubscription<int> subscription; subscription = counterStream.listen((int counter) { @@ -108,8 +113,10 @@ void demoPause() { } void useMap() { - var counterStream = - Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15); + var counterStream = Stream<int>.periodic( + const Duration(seconds: 1), + (x) => x, + ).take(15); // #docregion use-map // Double the integer in each event. @@ -119,16 +126,18 @@ void useMap() { } void useWhere() { - var counterStream = - Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15); + var counterStream = Stream<int>.periodic( + const Duration(seconds: 1), + (x) => x, + ).take(15); var mappedStream = counterStream - // #docregion use-where - .where((int x) => x.isEven) // Retain only even integer events. - .expand((var x) => [x, x]) // Duplicate each event. - .take(5) // Stop after the first five events. - // #enddocregion use-where - ; + // #docregion use-where + .where((int x) => x.isEven) // Retain only even integer events. + .expand((var x) => [x, x]) // Duplicate each event. + .take(5) // Stop after the first five events. + // #enddocregion use-where + ; mappedStream.forEach(print); } @@ -136,10 +145,11 @@ void useWhere() { void useTransform() async { // #docregion use-transform Stream<List<int>> content = File('someFile.txt').openRead(); - List<String> lines = await content - .transform(utf8.decoder) - .transform(const LineSplitter()) - .toList(); + List<String> lines = + await content + .transform(utf8.decoder) + .transform(const LineSplitter()) + .toList(); // #enddocregion use-transform print(lines); @@ -168,13 +178,17 @@ void useStreamFromFutureGenerator() { } void useExpand() { - var counterStream2 = timedCounterGenerator(const Duration(seconds: 1), 15) - .expand((var x) => [x, x]); // Duplicate each event. + var counterStream2 = timedCounterGenerator( + const Duration(seconds: 1), + 15, + ).expand((var x) => [x, x]); // Duplicate each event. counterStream2.listen(print); } void useTake() { - var counterStream2 = timedCounterGenerator(const Duration(seconds: 1), 15) - .take(5); // Stop after the first five events. + var counterStream2 = timedCounterGenerator( + const Duration(seconds: 1), + 15, + ).take(5); // Stop after the first five events. counterStream2.listen(print); } diff --git a/examples/misc/lib/articles/creating-streams/stream_controller_bad.dart b/examples/misc/lib/articles/creating-streams/stream_controller_bad.dart index ba87732e31..59fa6d7805 100755 --- a/examples/misc/lib/articles/creating-streams/stream_controller_bad.dart +++ b/examples/misc/lib/articles/creating-streams/stream_controller_bad.dart @@ -22,8 +22,8 @@ Stream<int> timedCounter(Duration interval, [int? maxCount]) { // #enddocregion flawed-stream void main() { -// showBasicUsage(); -// listenAfterDelay(); + // showBasicUsage(); + // listenAfterDelay(); listenWithPause(); } @@ -59,4 +59,5 @@ void listenWithPause() { } }); } + // #enddocregion pause-problem diff --git a/examples/misc/lib/cheatsheet/initializer_lists.dart b/examples/misc/lib/cheatsheet/initializer_lists.dart index 9437ba83ba..544a5e51cf 100644 --- a/examples/misc/lib/cheatsheet/initializer_lists.dart +++ b/examples/misc/lib/cheatsheet/initializer_lists.dart @@ -3,9 +3,7 @@ class NonNegativePoint { final int y; // #docregion assert - NonNegativePoint(this.x, this.y) - : assert(x >= 0), - assert(y >= 0) { + NonNegativePoint(this.x, this.y) : assert(x >= 0), assert(y >= 0) { print('I just made a NonNegativePoint: ($x, $y)'); } // #enddocregion assert diff --git a/examples/misc/lib/cheatsheet/named_constructor.dart b/examples/misc/lib/cheatsheet/named_constructor.dart index e357d71a53..3369ebc3e5 100644 --- a/examples/misc/lib/cheatsheet/named_constructor.dart +++ b/examples/misc/lib/cheatsheet/named_constructor.dart @@ -4,8 +4,7 @@ class Point { Point(this.x, this.y); - Point.origin() - : x = 0, - y = 0; + Point.origin() : x = 0, y = 0; } + // #enddocregion point-class diff --git a/examples/misc/lib/cheatsheet/optional_positional_args2.dart b/examples/misc/lib/cheatsheet/optional_positional_args2.dart index 1dbf7f6fb3..aaa2c3fda3 100644 --- a/examples/misc/lib/cheatsheet/optional_positional_args2.dart +++ b/examples/misc/lib/cheatsheet/optional_positional_args2.dart @@ -9,4 +9,5 @@ void main() { int newTotal = sumUpToFive(1); print(newTotal); // <-- prints 15 } + // #enddocregion sum-no-impl diff --git a/examples/misc/lib/cheatsheet/redirecting_constructors.dart b/examples/misc/lib/cheatsheet/redirecting_constructors.dart index 4927ae1440..39467ef6ae 100644 --- a/examples/misc/lib/cheatsheet/redirecting_constructors.dart +++ b/examples/misc/lib/cheatsheet/redirecting_constructors.dart @@ -24,4 +24,5 @@ class ImmutablePoint { const ImmutablePoint(this.x, this.y); } + // #enddocregion const-constructors diff --git a/examples/misc/lib/effective_dart/design_bad.dart b/examples/misc/lib/effective_dart/design_bad.dart index 6bc8f279e5..3d2f96c432 100644 --- a/examples/misc/lib/effective_dart/design_bad.dart +++ b/examples/misc/lib/effective_dart/design_bad.dart @@ -20,7 +20,9 @@ void miscDeclAnalyzedButNotTested() { (errors, monsters, subscription) { // #docregion code-like-prose // Telling errors to empty itself, or asking if it is? - if (errors.empty as bool) {/*-...-*/} + if (errors.empty as bool) { + // ... + } // Toggle what? To what? subscription.toggle(); @@ -31,7 +33,9 @@ void miscDeclAnalyzedButNotTested() { Iterable theCollectionOfErrors = []; // #docregion code-like-prose-overdone - if (theCollectionOfErrors.isEmpty) {/*-...-*/} + if (theCollectionOfErrors.isEmpty) { + // ... + } monsters.producesANewSequenceWhereEach((monster) => monster.hasClaws); // #enddocregion code-like-prose-overdone @@ -78,6 +82,7 @@ void miscDeclAnalyzedButNotTested() { return desserts; } + // #enddocregion omit-types-on-locals } @@ -86,6 +91,7 @@ void miscDeclAnalyzedButNotTested() { makeGreeting(String who) { return 'Hello, $who!'; } + // #enddocregion annotate-return-types } @@ -98,6 +104,7 @@ void miscDeclAnalyzedButNotTested() { print(message); } } + // #enddocregion annotate-parameters } @@ -247,7 +254,9 @@ class Color { class C<Foo> { // #docregion avoid_return_types_on_setters - void set foo(Foo value) {/* ... */} + void set foo(Foo value) { + /* ... */ + } // #enddocregion avoid_return_types_on_setters } @@ -267,4 +276,5 @@ class Person1 { bool operator ==(Object? other) => other != null && other is Person && name == other.name; } + // #enddocregion eq-dont-check-for-null diff --git a/examples/misc/lib/effective_dart/design_good.dart b/examples/misc/lib/effective_dart/design_good.dart index cac0ddcc4c..e15a2f0879 100644 --- a/examples/misc/lib/effective_dart/design_good.dart +++ b/examples/misc/lib/effective_dart/design_good.dart @@ -46,7 +46,9 @@ void miscDeclAnalyzedButNotTested() { (Iterable errors, Iterable<Monster> monsters) { // #docregion code-like-prose // "If errors is empty..." - if (errors.isEmpty) {/*-...-*/} + if (errors.isEmpty) { + // ... + } // "Hey, subscription, cancel!" subscription.cancel(); @@ -138,10 +140,11 @@ void miscDeclAnalyzedButNotTested() { () { // #docregion cascades - var buffer = StringBuffer() //!<br> - ..write('one') - ..write('two') - ..write('three'); + var buffer = + StringBuffer() //!<br> + ..write('one') + ..write('two') + ..write('three'); // #enddocregion cascades }; @@ -201,6 +204,7 @@ void miscDeclAnalyzedButNotTested() { return desserts; } + // #enddocregion omit-types-on-locals } @@ -215,6 +219,7 @@ void miscDeclAnalyzedButNotTested() { } return result; } + // #enddocregion upcast-local } @@ -223,6 +228,7 @@ void miscDeclAnalyzedButNotTested() { String makeGreeting(String who) { return 'Hello, $who!'; } + // #enddocregion annotate-return-types } @@ -233,6 +239,7 @@ void miscDeclAnalyzedButNotTested() { print(message); } } + // #enddocregion annotate-parameters } @@ -285,6 +292,7 @@ void miscDeclAnalyzedButNotTested() { var users = json['users']; print(users); } + // #enddocregion infer-dynamic } @@ -317,6 +325,7 @@ void miscDeclAnalyzedButNotTested() { if (arg is String) return arg.toLowerCase() == 'true'; throw ArgumentError('Cannot convert $arg to a bool.'); } + // #enddocregion object-vs-dynamic }; @@ -326,7 +335,9 @@ void miscDeclAnalyzedButNotTested() { // #docregion future-or-contra Stream<S> asyncMap<T, S>( - Iterable<T> iterable, FutureOr<S> Function(T) callback) async* { + Iterable<T> iterable, + FutureOr<S> Function(T) callback, + ) async* { for (final element in iterable) { yield await callback(element); } @@ -531,8 +542,10 @@ typedef Predicate<E> = bool Function(E element); class C<Foo> { // #docregion avoid_return_types_on_setters - set foo(Foo value) {/* ... */} -// #enddocregion avoid_return_types_on_setters + set foo(Foo value) { + /* ... */ + } + // #enddocregion avoid_return_types_on_setters } //---------------------------------------------------------------------------- @@ -546,27 +559,30 @@ class String0 { class DateTime0 { // #docregion omit-optional-positional - DateTime0(int year, - [int month = 1, - int day = 1, - int hour = 0, - int minute = 0, - int second = 0, - int millisecond = 0, - int microsecond = 0]); + DateTime0( + int year, [ + int month = 1, + int day = 1, + int hour = 0, + int minute = 0, + int second = 0, + int millisecond = 0, + int microsecond = 0, + ]); // #enddocregion omit-optional-positional } class Duration0 { // #docregion omit-optional-positional - Duration0( - {int days = 0, - int hours = 0, - int minutes = 0, - int seconds = 0, - int milliseconds = 0, - int microseconds = 0}); + Duration0({ + int days = 0, + int hours = 0, + int minutes = 0, + int seconds = 0, + int milliseconds = 0, + int microseconds = 0, + }); // #enddocregion omit-optional-positional } @@ -584,4 +600,5 @@ class Person { bool operator ==(Object other) => other is Person && name == other.name; } + // #enddocregion eq-dont-check-for-null diff --git a/examples/misc/lib/effective_dart/docs_bad.dart b/examples/misc/lib/effective_dart/docs_bad.dart index 690885f9e2..35659f9349 100644 --- a/examples/misc/lib/effective_dart/docs_bad.dart +++ b/examples/misc/lib/effective_dart/docs_bad.dart @@ -18,6 +18,7 @@ void miscDeclAnalyzedButNotTested() { void delete(String path) { ellipsis(); } + // #enddocregion first-sentence } @@ -29,6 +30,7 @@ void miscDeclAnalyzedButNotTested() { void delete(String path) { ellipsis(); } + // #enddocregion first-sentence-a-paragraph } } @@ -69,13 +71,13 @@ class C<ChunkBuilder, Flag, LineWriter> { //---------------------------------------------------------------------------- class Pool { -// #docregion getter-and-setter + // #docregion getter-and-setter /// The depth of the water in the pool, in meters. int get waterDepth => ellipsis(); /// Updates the water depth to a total of [meters] in height. set waterDepth(int meters) => ellipsis(); -// #enddocregion getter-and-setter + // #enddocregion getter-and-setter } //---------------------------------------------------------------------------- @@ -86,7 +88,7 @@ class Component { // #docregion doc-before-meta @Component(selector: 'toggle') - /// A button that can be flipped on and off. class ToggleComponent {} + // #enddocregion doc-before-meta diff --git a/examples/misc/lib/effective_dart/docs_good.dart b/examples/misc/lib/effective_dart/docs_good.dart index ca24a9b65f..13485480b1 100644 --- a/examples/misc/lib/effective_dart/docs_good.dart +++ b/examples/misc/lib/effective_dart/docs_good.dart @@ -45,6 +45,7 @@ void miscDeclAnalyzedButNotTested() { void delete(String path) { ellipsis(); } + // #enddocregion first-sentence } @@ -57,6 +58,7 @@ void miscDeclAnalyzedButNotTested() { void delete(String path) { ellipsis(); } + // #enddocregion first-sentence-a-paragraph } @@ -69,6 +71,7 @@ void miscDeclAnalyzedButNotTested() { void start() { ellipsis(); } + // #enddocregion third-person }; @@ -183,7 +186,7 @@ class C0 { // #docregion use-doc-comments /// The number of characters in this chunk when unsplit. int get length => ellipsis(); -// #enddocregion use-doc-comments + // #enddocregion use-doc-comments } //---------------------------------------------------------------------------- @@ -191,13 +194,13 @@ class C0 { class C1 { C1(this.weekday); -// #docregion noun-phrases-for-non-boolean-var-etc + // #docregion noun-phrases-for-non-boolean-var-etc /// The current day of the week, where `0` is Sunday. int weekday; /// The number of checked buttons on the page. int get checkedCount => ellipsis(); -// #enddocregion noun-phrases-for-non-boolean-var-etc + // #enddocregion noun-phrases-for-non-boolean-var-etc } //---------------------------------------------------------------------------- @@ -205,7 +208,7 @@ class C1 { class Modal { Modal(this.isVisible); -// #docregion noun-phrases-for-boolean-var-etc + // #docregion noun-phrases-for-boolean-var-etc /// Whether the modal is currently displayed to the user. bool isVisible; @@ -214,19 +217,19 @@ class Modal { /// Whether resizing the current browser window will also resize the modal. bool get canResize => ellipsis(); -// #enddocregion noun-phrases-for-boolean-var-etc + // #enddocregion noun-phrases-for-boolean-var-etc } //---------------------------------------------------------------------------- class Pool { -// #docregion getter-and-setter + // #docregion getter-and-setter /// The pH level of the water in the pool. /// /// Ranges from 0-14, representing acidic to basic, with 7 being neutral. int get phLevel => ellipsis(); set phLevel(int level) => ellipsis(); -// #enddocregion getter-and-setter + // #enddocregion getter-and-setter } //---------------------------------------------------------------------------- @@ -235,7 +238,9 @@ class Pool { /// A chunk of non-breaking output text terminated by a hard or soft newline. /// /// ... -class Chunk {/* ... */} +class Chunk { + /* ... */ +} // #enddocregion noun-phrases-for-type-or-lib //---------------------------------------------------------------------------- @@ -260,4 +265,5 @@ class Box { /// True if this box contains a value. bool get hasValue => _value != null; } + // #enddocregion this diff --git a/examples/misc/lib/effective_dart/some/other/file_2.dart b/examples/misc/lib/effective_dart/some/other/file_2.dart index a8ba90059c..343c0b1cc7 100644 --- a/examples/misc/lib/effective_dart/some/other/file_2.dart +++ b/examples/misc/lib/effective_dart/some/other/file_2.dart @@ -2,4 +2,5 @@ // #docregion part-of part of my_library; + // #enddocregion part-of diff --git a/examples/misc/lib/effective_dart/style_good.dart b/examples/misc/lib/effective_dart/style_good.dart index 9f039ffbee..426d7ad2e7 100644 --- a/examples/misc/lib/effective_dart/style_good.dart +++ b/examples/misc/lib/effective_dart/style_good.dart @@ -16,16 +16,16 @@ void miscDeclAnalyzedButNotTested() { } <IOStream, Id, DBIOPort, TVVcr>(uiHandler) => [ - // #docregion acronyms-and-abbreviations - HttpConnectionInfo, - uiHandler, - IOStream, - HttpRequest, - Id, - DBIOPort, - TVVcr - // #enddocregion acronyms-and-abbreviations - ]; + // #docregion acronyms-and-abbreviations + HttpConnectionInfo, + uiHandler, + IOStream, + HttpRequest, + Id, + DBIOPort, + TVVcr, + // #enddocregion acronyms-and-abbreviations + ]; (bool isWeekDay) { // #docregion curly-braces @@ -59,9 +59,13 @@ class SomeType {} //---------------------------------------------------------------------------- // #docregion type-names -class SliderMenu {/* ... */} +class SliderMenu { + /* ... */ +} -class HttpRequest {/* ... */} +class HttpRequest { + /* ... */ +} typedef Predicate<T> = bool Function(T value); // #enddocregion type-names @@ -76,10 +80,14 @@ class Foo { } @Foo(anArg) -class A {/* ... */} +class A { + /* ... */ +} @Foo() -class B {/* ... */} +class B { + /* ... */ +} // #enddocregion annotation-type-names //---------------------------------------------------------------------------- @@ -88,7 +96,9 @@ class B {/* ... */} const foo = Foo(); @foo -class C {/* ... */} +class C { + /* ... */ +} // #enddocregion annotation-const //---------------------------------------------------------------------------- @@ -117,7 +127,12 @@ void unusedCallbackParams() { //---------------------------------------------------------------------------- // #docregion extension-names -extension MyFancyList<T> on List<T> {/* ... */} +extension MyFancyList<T> on List<T> { + /* ... */ +} + +extension SmartIterable<T> on Iterable<T> { + /* ... */ +} -extension SmartIterable<T> on Iterable<T> {/* ... */} // #enddocregion extension-names diff --git a/examples/misc/lib/effective_dart/style_lib_bad.dart b/examples/misc/lib/effective_dart/style_lib_bad.dart index 2aeb41a22c..094c624e69 100644 --- a/examples/misc/lib/effective_dart/style_lib_bad.dart +++ b/examples/misc/lib/effective_dart/style_lib_bad.dart @@ -13,4 +13,5 @@ import 'package:examples/effective_dart/bar/bar.dart'; import 'foo/foo.dart'; import 'foo.dart'; + // #enddocregion sorted diff --git a/examples/misc/lib/effective_dart/style_lib_good.dart b/examples/misc/lib/effective_dart/style_lib_good.dart index 4e159df5cc..6445284070 100644 --- a/examples/misc/lib/effective_dart/style_lib_good.dart +++ b/examples/misc/lib/effective_dart/style_lib_good.dart @@ -34,4 +34,5 @@ import 'src/error.dart'; import 'src/foo_bar.dart'; export 'src/error.dart'; + // #enddocregion export diff --git a/examples/misc/lib/effective_dart/usage_bad.dart b/examples/misc/lib/effective_dart/usage_bad.dart index 99532733d2..4c734a033a 100644 --- a/examples/misc/lib/effective_dart/usage_bad.dart +++ b/examples/misc/lib/effective_dart/usage_bad.dart @@ -29,24 +29,34 @@ void miscDeclAnalyzedButNotTested() { bool? nullableBool = null; // #docregion non-null-boolean-expression - if (nonNullableBool == true) {/* ... */} + if (nonNullableBool == true) { + /* ... */ + } - if (nonNullableBool == false) {/* ... */} + if (nonNullableBool == false) { + /* ... */ + } // #enddocregion non-null-boolean-expression // #docregion nullable-boolean-expression // Static error if null: - if (nullableBool) {/* ... */} + if (nullableBool) { + /* ... */ + } // If you want null to be false: - if (nullableBool == true) {/* ... */} + if (nullableBool == true) { + /* ... */ + } // #enddocregion nullable-boolean-expression } { // #docregion adjacent-strings-literals - raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' + - 'parts are overrun by martians. Unclear which are which.'); + raiseAlarm( + 'ERROR: Parts of the spaceship are on fire. Other ' + + 'parts are overrun by martians. Unclear which are which.', + ); // #enddocregion adjacent-strings-literals } @@ -81,9 +91,11 @@ void miscDeclAnalyzedButNotTested() { arguments.addAll(options); arguments.add(command); if (modeFlags != null) arguments.addAll(modeFlags); - arguments.addAll(filePaths - .where((path) => path.endsWith('.dart')) - .map((path) => path.replaceAll('.dart', '.js'))); + arguments.addAll( + filePaths + .where((path) => path.endsWith('.dart')) + .map((path) => path.replaceAll('.dart', '.js')), + ); // #enddocregion spread-etc } @@ -164,6 +176,7 @@ void miscDeclAnalyzedButNotTested() { /*...*/ }; } + // #enddocregion func-decl } @@ -195,6 +208,7 @@ void miscDeclAnalyzedButNotTested() { void error([String? message = null]) { stderr.write(message ?? '\n'); } + // #enddocregion default-value-null } @@ -208,6 +222,7 @@ void miscDeclAnalyzedButNotTested() { return 0; } + // #enddocregion null-aware-promote } @@ -228,6 +243,7 @@ void miscDeclAnalyzedButNotTested() { Future<int> fastestBranch(Future<int> left, Future<int> right) async { return Future.any([left, right]); } + // #enddocregion unnecessary-async } @@ -242,6 +258,7 @@ void miscDeclAnalyzedButNotTested() { return completer.future; } + // #enddocregion avoid-completer } @@ -260,9 +277,10 @@ void miscDeclAnalyzedButNotTested() { (Map<Chest, Treasure> _opened) { // #docregion arrow-long - Treasure? openChest(Chest chest, Point where) => _opened.containsKey(chest) - ? null - : _opened[chest] = (Treasure(where)..addAll(chest.contents)); + Treasure? openChest(Chest chest, Point where) => + _opened.containsKey(chest) + ? null + : _opened[chest] = (Treasure(where)..addAll(chest.contents)); // #enddocregion arrow-long }; } @@ -289,17 +307,20 @@ class BadTeam extends Team { @override // #docregion async-await Future<int> countActivePlayers(String teamName) { - return downloadTeam(teamName).then((team) { - if (team == null) return Future.value(0); - - return team.roster.then((players) { - return players.where((player) => player.isActive).length; - }); - }).catchError((e) { - log.error(e); - return 0; - }); + return downloadTeam(teamName) + .then((team) { + if (team == null) return Future.value(0); + + return team.roster.then((players) { + return players.where((player) => player.isActive).length; + }); + }) + .catchError((e) { + log.error(e); + return 0; + }); } + // #enddocregion async-await } @@ -352,9 +373,9 @@ class Circle1 { double circumference; Circle1(double radius) - : radius = radius, - area = pi * radius * radius, - circumference = pi * 2.0 * radius; + : radius = radius, + area = pi * radius * radius, + circumference = pi * 2.0 * radius; } // #enddocregion calc-vs-store1 @@ -431,9 +452,7 @@ class ProfileMark { final DateTime start; ProfileMark(this.name) : start = DateTime.now(); - ProfileMark.unnamed() - : name = '', - start = DateTime.now(); + ProfileMark.unnamed() : name = '', start = DateTime.now(); } // #enddocregion field-init-at-decl @@ -442,9 +461,7 @@ class ProfileMark { // #docregion field-init-as-param class Point0 { double x, y; - Point0(double x, double y) - : x = x, - y = y; + Point0(double x, double y) : x = x, y = y; } // #enddocregion field-init-as-param @@ -477,9 +494,7 @@ void unnecessaryNewOrConst() { Widget build(BuildContext context) { return new Row( children: [ - new RaisedButton( - child: new Text('Increment'), - ), + new RaisedButton(child: new Text('Increment')), new Text('Click!'), ], ); diff --git a/examples/misc/lib/effective_dart/usage_good.dart b/examples/misc/lib/effective_dart/usage_good.dart index bcbd24b236..08cd773258 100644 --- a/examples/misc/lib/effective_dart/usage_good.dart +++ b/examples/misc/lib/effective_dart/usage_good.dart @@ -25,25 +25,35 @@ void miscDeclAnalyzedButNotTested() { bool? nullableBool = somethingNullable<bool>(); // #docregion non-null-boolean-expression - if (nonNullableBool) {/* ... */} + if (nonNullableBool) { + /* ... */ + } - if (!nonNullableBool) {/* ... */} + if (!nonNullableBool) { + /* ... */ + } // #enddocregion non-null-boolean-expression // #docregion nullable-boolean-expression // If you want null to result in false: - if (nullableBool ?? false) {/* ... */} + if (nullableBool ?? false) { + /* ... */ + } // If you want null to result in false // and you want the variable to type promote: - if (nullableBool != null && nullableBool) {/* ... */} + if (nullableBool != null && nullableBool) { + /* ... */ + } // #enddocregion nullable-boolean-expression } { // #docregion adjacent-strings-literals - raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' - 'parts are overrun by martians. Unclear which are which.'); + raiseAlarm( + 'ERROR: Parts of the spaceship are on fire. Other ' + 'parts are overrun by martians. Unclear which are which.', + ); // #enddocregion adjacent-strings-literals } @@ -81,7 +91,7 @@ void miscDeclAnalyzedButNotTested() { command, ...?modeFlags, for (var path in filePaths) - if (path.endsWith('.dart')) path.replaceAll('.dart', '.js') + if (path.endsWith('.dart')) path.replaceAll('.dart', '.js'), ]; // #enddocregion spread-etc } @@ -152,6 +162,7 @@ void miscDeclAnalyzedButNotTested() { /*...*/ } } + // #enddocregion func-decl } @@ -176,7 +187,9 @@ void miscDeclAnalyzedButNotTested() { { // #docregion default-separator - void insert(Object item, {int at = 0}) {/* ... */} + void insert(Object item, {int at = 0}) { + /* ... */ + } // #enddocregion default-separator } @@ -185,6 +198,7 @@ void miscDeclAnalyzedButNotTested() { void error([String? message]) { stderr.write(message ?? '\n'); } + // #enddocregion default-value-null } @@ -198,6 +212,7 @@ void miscDeclAnalyzedButNotTested() { return 0; } + // #enddocregion null-aware-promote } @@ -217,6 +232,7 @@ void miscDeclAnalyzedButNotTested() { Future<int> fastestBranch(Future<int> left, Future<int> right) { return Future.any([left, right]); } + // #enddocregion unnecessary-async } @@ -242,6 +258,7 @@ void miscDeclAnalyzedButNotTested() { return contents.contains('bear'); }); } + // #enddocregion avoid-completer } @@ -264,6 +281,7 @@ void miscDeclAnalyzedButNotTested() { var contents = await File(path).readAsString(); return contents.contains('bear'); } + // #enddocregion avoid-completer-alt } @@ -319,6 +337,7 @@ class Team { return 0; } } + // #enddocregion async-await } @@ -363,8 +382,8 @@ class UploadException { return 'Could not complete upload to ${response.url} ' '(error code ${response.errorCode}): ${response.reason}.'; } -// #enddocregion null-check-promo -// #docregion shadow-nullable-field + // #enddocregion null-check-promo + // #docregion shadow-nullable-field final response = this.response; if (response != null) { return 'Could not complete upload to ${response.url} ' @@ -443,6 +462,7 @@ class C { _opened[chest] = treasure; return treasure; } + // #enddocregion arrow-long } @@ -487,9 +507,7 @@ class BaseBox { class Box3 extends BaseBox { Object? value; - Box3(Object? value) - : value = value, - super(value); + Box3(Object? value) : value = value, super(value); } // #enddocregion param-dont-shadow-field-ctr-init @@ -522,8 +540,8 @@ class Point0 { class Point1 { double x, y; Point1.polar(double theta, double radius) - : x = cos(theta) * radius, - y = sin(theta) * radius; + : x = cos(theta) * radius, + y = sin(theta) * radius; } // #enddocregion late-init-list @@ -555,12 +573,8 @@ class Text { // #docregion no-new Widget build(BuildContext context) { return Row( - children: [ - RaisedButton( - child: Text('Increment'), - ), - Text('Click!'), - ], + children: [RaisedButton(child: Text('Increment')), Text('Click!')], ); } + // #enddocregion no-new diff --git a/examples/misc/lib/language_tour/async.dart b/examples/misc/lib/language_tour/async.dart index c9fb20b6d5..022ec43788 100644 --- a/examples/misc/lib/language_tour/async.dart +++ b/examples/misc/lib/language_tour/async.dart @@ -17,6 +17,7 @@ Future<void> miscDeclAnalyzedButNotTested() async { var version = await lookUpVersion(); // Do something with version } + // #enddocregion checkVersion } @@ -56,6 +57,7 @@ Future<void> miscDeclAnalyzedButNotTested() async { checkVersion(); print('In main: version is ${await lookUpVersion()}'); } + // #enddocregion main } @@ -70,6 +72,7 @@ Future<void> miscDeclAnalyzedButNotTested() async { } // ... } + // #enddocregion number-thinker } diff --git a/examples/misc/lib/language_tour/built_in_types.dart b/examples/misc/lib/language_tour/built_in_types.dart index 0410e76283..8929bd8c78 100644 --- a/examples/misc/lib/language_tour/built_in_types.dart +++ b/examples/misc/lib/language_tour/built_in_types.dart @@ -107,11 +107,7 @@ void miscDeclAnalyzedButNotTested() { { // #docregion trailing-commas - var list = [ - 'Car', - 'Boat', - 'Plane', - ]; + var list = ['Car', 'Boat', 'Plane']; // #enddocregion trailing-commas } @@ -159,14 +155,10 @@ void miscDeclAnalyzedButNotTested() { // Key: Value 'first': 'partridge', 'second': 'turtledoves', - 'fifth': 'golden rings' + 'fifth': 'golden rings', }; - var nobleGases = { - 2: 'helium', - 10: 'neon', - 18: 'argon', - }; + var nobleGases = {2: 'helium', 10: 'neon', 18: 'argon'}; // #enddocregion map-literal } @@ -193,11 +185,7 @@ void miscDeclAnalyzedButNotTested() { { // #docregion const-map - final constantMap = const { - 2: 'helium', - 10: 'neon', - 18: 'argon', - }; + final constantMap = const {2: 'helium', 10: 'neon', 18: 'argon'}; // constantMap[2] = 'Helium'; // This line will cause an error. // #enddocregion const-map @@ -221,5 +209,6 @@ class SymbolExampleNotUsedYet { print(Function.apply(int.parse, ['11'])); print(Function.apply(int.parse, ['11'], {#radix: 16})); } + // #enddocregion symbols } diff --git a/examples/misc/lib/language_tour/cascades.dart b/examples/misc/lib/language_tour/cascades.dart index 53af93bb7a..4a5d53a45c 100644 --- a/examples/misc/lib/language_tour/cascades.dart +++ b/examples/misc/lib/language_tour/cascades.dart @@ -19,10 +19,11 @@ void main() { void showCascade() { // #docregion cascade - var paint = Paint() - ..color = Colors.black - ..strokeCap = StrokeCap.round - ..strokeWidth = 5.0; + var paint = + Paint() + ..color = Colors.black + ..strokeCap = StrokeCap.round + ..strokeWidth = 5.0; // #enddocregion cascade print(paint); } diff --git a/examples/misc/lib/language_tour/classes/employee.dart b/examples/misc/lib/language_tour/classes/employee.dart index 94026222ff..39aca87857 100644 --- a/examples/misc/lib/language_tour/classes/employee.dart +++ b/examples/misc/lib/language_tour/classes/employee.dart @@ -44,6 +44,7 @@ void main() { // #docregion emp-as-person (employee as Person).firstName = 'Bob'; // #enddocregion emp-as-person -// #docregion super + // #docregion super } + // #enddocregion super diff --git a/examples/misc/lib/language_tour/classes/enum.dart b/examples/misc/lib/language_tour/classes/enum.dart index 2a7a9fffe8..731254c3d0 100644 --- a/examples/misc/lib/language_tour/classes/enum.dart +++ b/examples/misc/lib/language_tour/classes/enum.dart @@ -67,4 +67,5 @@ enum Vehicle implements Comparable<Vehicle> { @override int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint; } + // #enddocregion enhanced diff --git a/examples/misc/lib/language_tour/classes/extends.dart b/examples/misc/lib/language_tour/classes/extends.dart index 7953fe1fac..f40c88b2f3 100644 --- a/examples/misc/lib/language_tour/classes/extends.dart +++ b/examples/misc/lib/language_tour/classes/extends.dart @@ -26,4 +26,5 @@ class SmartTelevision extends Television { void _upgradeApps() {} // #docregion smart-tv } + // #enddocregion smart-tv diff --git a/examples/misc/lib/language_tour/classes/misc.dart b/examples/misc/lib/language_tour/classes/misc.dart index f63aed91dc..e1d3d2f095 100644 --- a/examples/misc/lib/language_tour/classes/misc.dart +++ b/examples/misc/lib/language_tour/classes/misc.dart @@ -14,7 +14,9 @@ class Comparable {} class Location {} // #docregion point-interfaces -class Point implements Comparable, Location {/*...*/} +class Point implements Comparable, Location { + /*...*/ +} // #enddocregion point-interfaces // #docregion static-field @@ -27,4 +29,5 @@ class Queue { void main() { assert(Queue.initialCapacity == 16); } + // #enddocregion static-field diff --git a/examples/misc/lib/language_tour/classes/no_such_method.dart b/examples/misc/lib/language_tour/classes/no_such_method.dart index b49859abfa..53afd79465 100644 --- a/examples/misc/lib/language_tour/classes/no_such_method.dart +++ b/examples/misc/lib/language_tour/classes/no_such_method.dart @@ -9,8 +9,11 @@ class A { // non-existent member results in a NoSuchMethodError. @override void noSuchMethod(Invocation invocation) { - print('You tried to use a non-existent member: ' - '${invocation.memberName}'); + print( + 'You tried to use a non-existent member: ' + '${invocation.memberName}', + ); } } + // #enddocregion no-such-method-impl diff --git a/examples/misc/lib/language_tour/classes/orchestra.dart b/examples/misc/lib/language_tour/classes/orchestra.dart index 0085189d6a..ca8d6a1333 100644 --- a/examples/misc/lib/language_tour/classes/orchestra.dart +++ b/examples/misc/lib/language_tour/classes/orchestra.dart @@ -87,7 +87,7 @@ class SingerDancer extends Musician2 with MusicalPerformer { // ... // #enddocregion mixin-on SingerDancer(super.name) : super.withName(); -// #docregion mixin-on + // #docregion mixin-on } // #enddocregion mixin-on diff --git a/examples/misc/lib/language_tour/classes/point.dart b/examples/misc/lib/language_tour/classes/point.dart index f3a69704c9..46fa3410fb 100644 --- a/examples/misc/lib/language_tour/classes/point.dart +++ b/examples/misc/lib/language_tour/classes/point.dart @@ -19,16 +19,12 @@ class Point { // #docregion named-constructor // Named constructor - Point.origin() - : x = xOrigin, - y = yOrigin; + Point.origin() : x = xOrigin, y = yOrigin; // #enddocregion named-constructor // Initializer list sets instance variables before // the constructor body runs. - Point.fromJson(Map<String, double> json) - : x = json['x']!, - y = json['y']!; + Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']!; // #docregion class-with-distance-to double distanceTo(Point other) { @@ -36,6 +32,8 @@ class Point { var dy = y - other.y; return sqrt(dx * dx + dy * dy); } + // #docregion constructor-initializer, named-constructor } + // #enddocregion class-with-distance-to, constructor-initializer, named-constructor diff --git a/examples/misc/lib/language_tour/classes/point_alt.dart b/examples/misc/lib/language_tour/classes/point_alt.dart index f148a7decc..2893b0908d 100644 --- a/examples/misc/lib/language_tour/classes/point_alt.dart +++ b/examples/misc/lib/language_tour/classes/point_alt.dart @@ -18,9 +18,7 @@ class Point { // Initializer list sets instance variables before // the constructor body runs. // #docregion initializer-list-no-comment - Point.fromJson(Map<String, double> json) - : x = json['x']!, - y = json['y']! { + Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']! { print('In Point.fromJson(): ($x, $y)'); } // #enddocregion initializer-list-no-comment @@ -32,7 +30,7 @@ class Point { } // #enddocregion initializer-list-with-assert -// #docregion idiomatic-constructor + // #docregion idiomatic-constructor } // #enddocregion idiomatic-constructor @@ -97,4 +95,5 @@ class PointD { return 'PointD($x,$y)'; } } + // #enddocregion initialize-null diff --git a/examples/misc/lib/language_tour/classes/point_with_distance_field.dart b/examples/misc/lib/language_tour/classes/point_with_distance_field.dart index 233df0b699..ceb1303761 100644 --- a/examples/misc/lib/language_tour/classes/point_with_distance_field.dart +++ b/examples/misc/lib/language_tour/classes/point_with_distance_field.dart @@ -7,9 +7,9 @@ class Point { final double distanceFromOrigin; Point(double x, double y) - : x = x, - y = y, - distanceFromOrigin = sqrt(x * x + y * y); + : x = x, + y = y, + distanceFromOrigin = sqrt(x * x + y * y); } void main() { diff --git a/examples/misc/lib/language_tour/classes/point_with_main.dart b/examples/misc/lib/language_tour/classes/point_with_main.dart index 18ece0065a..c35ded4e83 100644 --- a/examples/misc/lib/language_tour/classes/point_with_main.dart +++ b/examples/misc/lib/language_tour/classes/point_with_main.dart @@ -4,7 +4,7 @@ class Point { double? y; // Declare y, initially null. // #enddocregion class-main double z = 0; // Declare z, initially 0. -// #docregion class-main + // #docregion class-main } // #enddocregion class @@ -14,4 +14,5 @@ void main() { assert(point.x == 4); // Use the getter method for x. assert(point.y == null); // Values default to null. } + // #enddocregion class-main diff --git a/examples/misc/lib/language_tour/classes/super_initializer_named_parameters.dart b/examples/misc/lib/language_tour/classes/super_initializer_named_parameters.dart index 686cf351f0..d1441e8f8d 100644 --- a/examples/misc/lib/language_tour/classes/super_initializer_named_parameters.dart +++ b/examples/misc/lib/language_tour/classes/super_initializer_named_parameters.dart @@ -1,11 +1,11 @@ // #docregion named class Vector2d { -// #enddocregion named + // #enddocregion named final double x; final double y; Vector2d(this.x, this.y); -// #docregion named + // #docregion named // ... Vector2d.named({required this.x, required this.y}); } @@ -18,4 +18,5 @@ class Vector3d extends Vector2d { // : super.named(x: 0, y: y); Vector3d.yzPlane({required super.y, required this.z}) : super.named(x: 0); } + // #enddocregion named diff --git a/examples/misc/lib/language_tour/classes/super_initializer_parameters.dart b/examples/misc/lib/language_tour/classes/super_initializer_parameters.dart index 42c3c311e0..3570cb9711 100644 --- a/examples/misc/lib/language_tour/classes/super_initializer_parameters.dart +++ b/examples/misc/lib/language_tour/classes/super_initializer_parameters.dart @@ -13,7 +13,7 @@ class Vector2d { // #docregion named Vector2d.named({required this.x, required this.y}); -// #docregion positional + // #docregion positional } class Vector3d extends Vector2d { @@ -34,6 +34,7 @@ class Vector3d extends Vector2d { // Vector3d.yzPlane({required double y, required this.z}) // : super.named(x: 0, y: y); Vector3d.yzPlane({required super.y, required this.z}) : super.named(x: 0); -// #docregion positional + // #docregion positional } + // #enddocregion positional, named diff --git a/examples/misc/lib/language_tour/classes/super_initializer_positional_parameters.dart b/examples/misc/lib/language_tour/classes/super_initializer_positional_parameters.dart index 4301c5c01c..dd28336fd5 100644 --- a/examples/misc/lib/language_tour/classes/super_initializer_positional_parameters.dart +++ b/examples/misc/lib/language_tour/classes/super_initializer_positional_parameters.dart @@ -13,4 +13,5 @@ class Vector3d extends Vector2d { // Vector3d(final double x, final double y, this.z) : super(x, y); Vector3d(super.x, super.y, this.z); } + // #enddocregion positional diff --git a/examples/misc/lib/language_tour/comments.dart b/examples/misc/lib/language_tour/comments.dart index 38ee681a91..33abb0fdb5 100644 --- a/examples/misc/lib/language_tour/comments.dart +++ b/examples/misc/lib/language_tour/comments.dart @@ -7,6 +7,7 @@ void miscDeclAnalyzedButNotTested() { // TODO: refactor into an AbstractLlamaGreetingFactory? print('Welcome to my Llama farm!'); } + // #enddocregion single-line-comments } @@ -54,4 +55,5 @@ class Llama { // ... } } + // #enddocregion doc-comments diff --git a/examples/misc/lib/language_tour/functions.dart b/examples/misc/lib/language_tour/functions.dart index c098eac018..a684a0c940 100644 --- a/examples/misc/lib/language_tour/functions.dart +++ b/examples/misc/lib/language_tour/functions.dart @@ -9,6 +9,7 @@ void miscDeclAnalyzedButNotTested() { bool isNoble(int atomicNumber) { return _nobleGases[atomicNumber] != null; } + // #enddocregion function } @@ -17,6 +18,7 @@ void miscDeclAnalyzedButNotTested() { isNoble(atomicNumber) { return _nobleGases[atomicNumber] != null; } + // #enddocregion function-omitting-types } @@ -40,7 +42,9 @@ void miscDeclAnalyzedButNotTested() { { // #docregion specify-named-parameters /// Sets the [bold] and [hidden] flags ... - void enableFlags({bool? bold, bool? hidden}) {/*...*/} + void enableFlags({bool? bold, bool? hidden}) { + /*...*/ + } // #enddocregion specify-named-parameters // #docregion use-named-parameters @@ -59,7 +63,9 @@ void miscDeclAnalyzedButNotTested() { { // #docregion named-parameter-default-values /// Sets the [bold] and [hidden] flags ... - void enableFlags({bool bold = false, bool hidden = false}) {/*...*/} + void enableFlags({bool bold = false, bool hidden = false}) { + /*...*/ + } // bold will be true; hidden will be false. enableFlags(bold: true); diff --git a/examples/misc/lib/language_tour/generics/base_class.dart b/examples/misc/lib/language_tour/generics/base_class.dart index 2acde3ccc6..93db05f409 100644 --- a/examples/misc/lib/language_tour/generics/base_class.dart +++ b/examples/misc/lib/language_tour/generics/base_class.dart @@ -6,5 +6,8 @@ class Foo<T extends SomeBaseClass> { String toString() => "Instance of 'Foo<$T>'"; // ignore: annotate_overrides } -class Extender extends SomeBaseClass {/*...*/} +class Extender extends SomeBaseClass { + /*...*/ +} + // #enddocregion generic diff --git a/examples/misc/lib/language_tour/generics/cache.dart b/examples/misc/lib/language_tour/generics/cache.dart index 0be7e1bea4..d9ae7d5b35 100644 --- a/examples/misc/lib/language_tour/generics/cache.dart +++ b/examples/misc/lib/language_tour/generics/cache.dart @@ -17,4 +17,5 @@ abstract class Cache<T> { T getByKey(String key); void setByKey(String key, T value); } + // #enddocregion cache diff --git a/examples/misc/lib/language_tour/generics/misc.dart b/examples/misc/lib/language_tour/generics/misc.dart index 50ea715266..f0fb52bbc0 100644 --- a/examples/misc/lib/language_tour/generics/misc.dart +++ b/examples/misc/lib/language_tour/generics/misc.dart @@ -7,7 +7,7 @@ void miscDeclAnalyzedButNotTested() { var pages = <String, String>{ 'index.html': 'Homepage', 'robots.txt': 'Hints for web robots', - 'humans.txt': 'We are people, not machines' + 'humans.txt': 'We are people, not machines', }; // #enddocregion collection-literals } @@ -17,4 +17,5 @@ void miscDeclAnalyzedButNotTested() { class Foo<T extends Object> { // Any type provided to Foo for T must be non-nullable. } + // #enddocregion non-nullable diff --git a/examples/misc/lib/language_tour/libraries/greeter.dart b/examples/misc/lib/language_tour/libraries/greeter.dart index 4512d0e7a3..32df07016c 100644 --- a/examples/misc/lib/language_tour/libraries/greeter.dart +++ b/examples/misc/lib/language_tour/libraries/greeter.dart @@ -7,4 +7,5 @@ Future<void> greet() async { await hello.loadLibrary(); hello.printGreeting(); } + // #enddocregion load-library diff --git a/examples/misc/lib/language_tour/metadata/misc.dart b/examples/misc/lib/language_tour/metadata/misc.dart index bd45e1ab3b..102f3434e7 100644 --- a/examples/misc/lib/language_tour/metadata/misc.dart +++ b/examples/misc/lib/language_tour/metadata/misc.dart @@ -5,4 +5,5 @@ import 'todo.dart'; void doSomething() { print('Do something'); } + // #enddocregion usage diff --git a/examples/misc/lib/language_tour/metadata/television.dart b/examples/misc/lib/language_tour/metadata/television.dart index 4fa5f7eeeb..505e89875b 100644 --- a/examples/misc/lib/language_tour/metadata/television.dart +++ b/examples/misc/lib/language_tour/metadata/television.dart @@ -9,19 +9,26 @@ class Television { } /// Turns the TV's power on. - void turnOn() {/*...*/} + void turnOn() { + /*...*/ + } // #enddocregion deprecated // #docregion override - set contrast(int value) {/*...*/} + set contrast(int value) { + /*...*/ + } // #docregion deprecated } // #enddocregion deprecated class SmartTelevision extends Television { @override - set contrast(num value) {/*...*/} + set contrast(num value) { + /*...*/ + } // #enddocregion override // #docregion override } + // #enddocregion override diff --git a/examples/misc/lib/language_tour/operators.dart b/examples/misc/lib/language_tour/operators.dart index fffc54ec35..237637b64f 100644 --- a/examples/misc/lib/language_tour/operators.dart +++ b/examples/misc/lib/language_tour/operators.dart @@ -18,14 +18,16 @@ void miscDeclAnalyzedButNotTested() { { // #docregion nested-cascades - final addressBook = (AddressBookBuilder() - ..name = 'jenny' - ..email = 'jenny@example.com' - ..phone = (PhoneNumberBuilder() - ..number = '415-555-0100' - ..label = 'home') - .build()) - .build(); + final addressBook = + (AddressBookBuilder() + ..name = 'jenny' + ..email = 'jenny@example.com' + ..phone = + (PhoneNumberBuilder() + ..number = '415-555-0100' + ..label = 'home') + .build()) + .build(); // #enddocregion nested-cascades } @@ -33,13 +35,13 @@ void miscDeclAnalyzedButNotTested() { // #docregion cannot-cascade-on-void var sb = StringBuffer(); sb.write('foo') - // #enddocregion cannot-cascade-on-void - /* + // #enddocregion cannot-cascade-on-void + /* // #docregion cannot-cascade-on-void ..write('bar'); // Error: method 'write' isn't defined for 'void'. // #enddocregion cannot-cascade-on-void */ - ; + ; } } diff --git a/examples/misc/lib/language_tour/typedefs/misc.dart b/examples/misc/lib/language_tour/typedefs/misc.dart index 14f3db5bc9..7bb45215f4 100644 --- a/examples/misc/lib/language_tour/typedefs/misc.dart +++ b/examples/misc/lib/language_tour/typedefs/misc.dart @@ -18,4 +18,5 @@ void main() { // ignore: unnecessary_type_check assert(sort is Compare<int>); // True! } + // #enddocregion compare diff --git a/examples/misc/lib/library_tour/async/basic.dart b/examples/misc/lib/library_tour/async/basic.dart index 57518c1151..a6dbe3ec59 100644 --- a/examples/misc/lib/library_tour/async/basic.dart +++ b/examples/misc/lib/library_tour/async/basic.dart @@ -14,11 +14,14 @@ void miscDeclAnalyzedButNotTested() { { // #docregion catch-error - httpClient.read(url).then((String result) { - print(result); - }).catchError((e) { - // Handle or ignore the error. - }); + httpClient + .read(url) + .then((String result) { + print(result); + }) + .catchError((e) { + // Handle or ignore the error. + }); // #enddocregion catch-error } } diff --git a/examples/misc/lib/library_tour/async/future.dart b/examples/misc/lib/library_tour/async/future.dart index c9faeee014..3a05852366 100644 --- a/examples/misc/lib/library_tour/async/future.dart +++ b/examples/misc/lib/library_tour/async/future.dart @@ -13,10 +13,13 @@ void miscDeclAnalyzedButNotTested() { // #docregion run-using-future void runUsingFuture() { // ... - findEntryPoint().then((entryPoint) { - return runExecutable(entryPoint, args); - }).then(flushThenExit); + findEntryPoint() + .then((entryPoint) { + return runExecutable(entryPoint, args); + }) + .then(flushThenExit); } + // #enddocregion run-using-future } @@ -28,6 +31,7 @@ void miscDeclAnalyzedButNotTested() { var exitCode = await runExecutable(entryPoint, args); await flushThenExit(exitCode); } + // #enddocregion run-using-async-await } @@ -59,8 +63,8 @@ void miscDeclAnalyzedButNotTested() { .then((_) => lengthyComputation()) .then((_) => print('Done!')) .catchError((exception) { - /* Handle exception... */ - }); + /* Handle exception... */ + }); // #enddocregion then-chain return Future.value(); } diff --git a/examples/misc/lib/library_tour/async/stream.dart b/examples/misc/lib/library_tour/async/stream.dart index 1538717123..ed3c0ebd68 100644 --- a/examples/misc/lib/library_tour/async/stream.dart +++ b/examples/misc/lib/library_tour/async/stream.dart @@ -25,6 +25,7 @@ void miscDeclAnalyzedButNotTested() { } }); } + // #enddocregion listen } @@ -43,6 +44,7 @@ void miscDeclAnalyzedButNotTested() { searchFile(File(searchPath), searchTerms); } } + // #enddocregion await-for } @@ -53,8 +55,9 @@ void miscDeclAnalyzedButNotTested() { Stream<List<int>> inputStream = config.openRead(); // #docregion transform - var lines = - inputStream.transform(utf8.decoder).transform(const LineSplitter()); + var lines = inputStream + .transform(utf8.decoder) + .transform(const LineSplitter()); // #enddocregion transform try { await for (final line in lines) { @@ -65,6 +68,7 @@ void miscDeclAnalyzedButNotTested() { print(e); } } + // #enddocregion read-file-await-for } @@ -73,14 +77,20 @@ void miscDeclAnalyzedButNotTested() { var config = File('config.txt'); Stream<List<int>> inputStream = config.openRead(); - inputStream.transform(utf8.decoder).transform(const LineSplitter()).listen( - (String line) { - print('Got ${line.length} characters from stream'); - }, onDone: () { - print('file is now closed'); - }, onError: (e) { - print(e); - }); + inputStream + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen( + (String line) { + print('Got ${line.length} characters from stream'); + }, + onDone: () { + print('file is now closed'); + }, + onError: (e) { + print(e); + }, + ); // #enddocregion on-done } } diff --git a/examples/misc/lib/library_tour/core/iterator.dart b/examples/misc/lib/library_tour/core/iterator.dart index 3def45876c..d8d0e24335 100644 --- a/examples/misc/lib/library_tour/core/iterator.dart +++ b/examples/misc/lib/library_tour/core/iterator.dart @@ -40,4 +40,5 @@ void main() { // #docregion structure } } + // #enddocregion structure diff --git a/examples/misc/lib/library_tour/io/http_server.dart b/examples/misc/lib/library_tour/io/http_server.dart index 04ce62c642..59cd2ba499 100644 --- a/examples/misc/lib/library_tour/io/http_server.dart +++ b/examples/misc/lib/library_tour/io/http_server.dart @@ -18,14 +18,12 @@ void processRequest(HttpRequest request) { final response = request.response; if (request.uri.path == '/dart') { response - ..headers.contentType = ContentType( - 'text', - 'plain', - ) + ..headers.contentType = ContentType('text', 'plain') ..write('Hello from the server'); } else { response.statusCode = HttpStatus.notFound; } response.close(); } + // #enddocregion process-requests diff --git a/examples/misc/lib/samples/spacecraft.dart b/examples/misc/lib/samples/spacecraft.dart index 4fc8da8794..413b67b4b7 100644 --- a/examples/misc/lib/samples/spacecraft.dart +++ b/examples/misc/lib/samples/spacecraft.dart @@ -107,8 +107,11 @@ enum Planet { neptune(planetType: PlanetType.ice, moons: 14, hasRings: true); /// A constant generating constructor - const Planet( - {required this.planetType, required this.moons, required this.hasRings}); + const Planet({ + required this.planetType, + required this.moons, + required this.hasRings, + }); /// All instance variables are final final PlanetType planetType; @@ -119,4 +122,5 @@ enum Planet { bool get isGiant => planetType == PlanetType.gas || planetType == PlanetType.ice; } + // #enddocregion enhanced-enum diff --git a/examples/misc/lib/tutorial/misc.dart b/examples/misc/lib/tutorial/misc.dart index c964ffe894..296460f5ac 100644 --- a/examples/misc/lib/tutorial/misc.dart +++ b/examples/misc/lib/tutorial/misc.dart @@ -41,6 +41,7 @@ void streamsTutorial() { yield convert(event); } } + // #enddocregion map-log-errors } diff --git a/examples/misc/lib/tutorial/stream_interface.dart b/examples/misc/lib/tutorial/stream_interface.dart index fc1f3d45a8..e1f401fdbb 100644 --- a/examples/misc/lib/tutorial/stream_interface.dart +++ b/examples/misc/lib/tutorial/stream_interface.dart @@ -38,19 +38,26 @@ abstract class MyStream<T> implements Stream<T> { bool get isBroadcast; - Stream<T> asBroadcastStream( - {void Function(StreamSubscription<T> subscription)? onListen, - void Function(StreamSubscription<T> subscription)? onCancel}); + Stream<T> asBroadcastStream({ + void Function(StreamSubscription<T> subscription)? onListen, + void Function(StreamSubscription<T> subscription)? onCancel, + }); // #docregion special-stream-members Stream<T> handleError(Function onError, {bool Function(dynamic error)? test}); - Stream<T> timeout(Duration timeLimit, - {void Function(EventSink<T> sink)? onTimeout}); + Stream<T> timeout( + Duration timeLimit, { + void Function(EventSink<T> sink)? onTimeout, + }); Stream<S> transform<S>(StreamTransformer<T, S> streamTransformer); // #enddocregion special-stream-members // #docregion listen - StreamSubscription<T> listen(void Function(T event)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}); + StreamSubscription<T> listen( + void Function(T event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }); // #enddocregion listen } diff --git a/examples/misc/pubspec.yaml b/examples/misc/pubspec.yaml index ab4d117ddc..ede0e460ee 100644 --- a/examples/misc/pubspec.yaml +++ b/examples/misc/pubspec.yaml @@ -3,7 +3,7 @@ description: dart.dev example code. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: args: ^2.5.0 diff --git a/examples/misc/test/bin_test.dart b/examples/misc/test/bin_test.dart index 5e3bbf3637..0b25c0685c 100644 --- a/examples/misc/test/bin_test.dart +++ b/examples/misc/test/bin_test.dart @@ -11,10 +11,6 @@ void main() { final quotes = File(pathToQuotes); expect(quotes.readAsStringSync(), contains('#')); - expect( - () => cat_no_hash.main([quotes.path]), - prints( - isNot(contains('#')), - )); + expect(() => cat_no_hash.main([quotes.path]), prints(isNot(contains('#')))); }); } diff --git a/examples/misc/test/cheatsheet/collections_test.dart b/examples/misc/test/cheatsheet/collections_test.dart index 47df9b5530..63835624fc 100644 --- a/examples/misc/test/cheatsheet/collections_test.dart +++ b/examples/misc/test/cheatsheet/collections_test.dart @@ -5,11 +5,7 @@ void main() { // #docregion collection-literals-inferred final aListOfStrings = ['one', 'two', 'three']; final aSetOfStrings = {'one', 'two', 'three'}; - final aMapOfStringsToInts = { - 'one': 1, - 'two': 2, - 'three': 3, - }; + final aMapOfStringsToInts = {'one': 1, 'two': 2, 'three': 3}; // #enddocregion collection-literals-inferred expect(aListOfStrings, isA<List<String>>()); @@ -44,7 +40,9 @@ void main() { expect(aListOfBaseType, isA<List<BaseType>>()); expect( - aListOfBaseType, containsAllInOrder([isA<SubType>(), isA<SubType>()])); + aListOfBaseType, + containsAllInOrder([isA<SubType>(), isA<SubType>()]), + ); }); } diff --git a/examples/misc/test/language_tour/browser_test.dart b/examples/misc/test/language_tour/browser_test.dart index 9216b56377..328267761f 100644 --- a/examples/misc/test/language_tour/browser_test.dart +++ b/examples/misc/test/language_tour/browser_test.dart @@ -17,7 +17,8 @@ void main() { // #docregion cascade-operator document.querySelector('#confirm') // Get an object. - ?..textContent = 'Confirm' // Use its members. + ?..textContent = + 'Confirm' // Use its members. ..classList.add('important') ..onClick.listen((e) => window.alert('Confirmed!')) ..scrollIntoView(); diff --git a/examples/misc/test/language_tour/built_in_types_test.dart b/examples/misc/test/language_tour/built_in_types_test.dart index 6e130b5dac..756af9234d 100644 --- a/examples/misc/test/language_tour/built_in_types_test.dart +++ b/examples/misc/test/language_tour/built_in_types_test.dart @@ -35,24 +35,31 @@ void main() { // #docregion string-interpolation var s = 'string interpolation'; - assert('Dart has $s, which is very handy.' == - 'Dart has string interpolation, ' - 'which is very handy.'); - assert('That deserves all caps. ' - '${s.toUpperCase()} is very handy!' == - 'That deserves all caps. ' - 'STRING INTERPOLATION is very handy!'); + assert( + 'Dart has $s, which is very handy.' == + 'Dart has string interpolation, ' + 'which is very handy.', + ); + assert( + 'That deserves all caps. ' + '${s.toUpperCase()} is very handy!' == + 'That deserves all caps. ' + 'STRING INTERPOLATION is very handy!', + ); // #enddocregion string-interpolation }); test('adjacent-string-literals', () { // #docregion adjacent-string-literals - var s1 = 'String ' + var s1 = + 'String ' 'concatenation' " works even over line breaks."; - assert(s1 == - 'String concatenation works even over ' - 'line breaks.'); + assert( + s1 == + 'String concatenation works even over ' + 'line breaks.', + ); var s2 = 'The + operator ' + 'works, as well.'; assert(s2 == 'The + operator works, as well.'); diff --git a/examples/misc/test/language_tour/characters_test.dart b/examples/misc/test/language_tour/characters_test.dart index bc8916d07d..f9213b9520 100644 --- a/examples/misc/test/language_tour/characters_test.dart +++ b/examples/misc/test/language_tour/characters_test.dart @@ -4,8 +4,10 @@ import 'package:examples/language_tour/characters.dart' as characters; void main() { test('characters_usage', () { expect( - characters.main, - prints( - 'Hi 🇩🇰\nThe end of the string: \u{DDF0}\nThe last character: 🇩🇰\n')); + characters.main, + prints( + 'Hi 🇩🇰\nThe end of the string: \u{DDF0}\nThe last character: 🇩🇰\n', + ), + ); }); } diff --git a/examples/misc/test/language_tour/classes_test.dart b/examples/misc/test/language_tour/classes_test.dart index 1d0a058e21..19347142a1 100644 --- a/examples/misc/test/language_tour/classes_test.dart +++ b/examples/misc/test/language_tour/classes_test.dart @@ -91,8 +91,10 @@ void main() { }); test('employee', () { - expect(employee.main, - m.prints(['in Person', 'in Employee', "Instance of 'Employee'"])); + expect( + employee.main, + m.prints(['in Person', 'in Employee', "Instance of 'Employee'"]), + ); }); test('point_with_distance', () { @@ -106,15 +108,16 @@ void main() { test('logger', () { expect( - logger_with_main.main, - m.prints([ - 'Button clicked', - 'log1: This is l1.', - 'log1: This is l1_2.', - 'log2: This is l2.', - 'UI: This is logger.', - 'UI: This is loggerJson.' - ])); + logger_with_main.main, + m.prints([ + 'Button clicked', + 'log1: This is l1.', + 'log1: This is l1_2.', + 'log2: This is l2.', + 'UI: This is logger.', + 'UI: This is loggerJson.', + ]), + ); }); test('rectangle_with_main', () { @@ -127,26 +130,30 @@ void main() { test('imposter', () { expect( - impostor.main, - m.prints([ - 'Hello, Bob. I am Kathy.', - 'Hi Bob. Do you know who I am?', - ])); + impostor.main, + m.prints(['Hello, Bob. I am Kathy.', 'Hi Bob. Do you know who I am?']), + ); }); test('no_such_method', () { - expect(no_such_method.main, - m.prints('You tried to use a non-existent member: Symbol("foo")')); + expect( + no_such_method.main, + m.prints('You tried to use a non-existent member: Symbol("foo")'), + ); }); test('enum_with_main', () { - expect(enum_with_main.main, - m.prints(['Your favorite color is blue!', 'Color.blue', 'blue', 80])); + expect( + enum_with_main.main, + m.prints(['Your favorite color is blue!', 'Color.blue', 'blue', 80]), + ); }); test('orchestra', () { expect( - orchestra.main, m.prints(['Waving hands', 'Playing piano', 'Dancing'])); + orchestra.main, + m.prints(['Waving hands', 'Playing piano', 'Dancing']), + ); }); test('static-field', () { @@ -195,8 +202,10 @@ void main() { expect(simpleVector3d.y, equals(6.4)); expect(simpleVector3d.z, equals(3)); - final yzPlaneVector3d = - super_initializer_parameters.Vector3d.yzPlane(y: 2.17, z: 3); + final yzPlaneVector3d = super_initializer_parameters.Vector3d.yzPlane( + y: 2.17, + z: 3, + ); expect(yzPlaneVector3d.x, equals(0)); expect(yzPlaneVector3d.y, equals(2.17)); expect(yzPlaneVector3d.z, equals(3)); diff --git a/examples/misc/test/language_tour/control_flow_test.dart b/examples/misc/test/language_tour/control_flow_test.dart index 106449aedc..f77ca04ae8 100644 --- a/examples/misc/test/language_tour/control_flow_test.dart +++ b/examples/misc/test/language_tour/control_flow_test.dart @@ -18,8 +18,10 @@ void main() { // #enddocregion assert // #docregion assert-with-message - assert(urlString.startsWith('https'), - 'URL ($urlString) should start with "https".'); + assert( + urlString.startsWith('https'), + 'URL ($urlString) should start with "https".', + ); // #enddocregion assert-with-message }); } diff --git a/examples/misc/test/language_tour/exceptions_test.dart b/examples/misc/test/language_tour/exceptions_test.dart index f11ca8b063..a5bf56f027 100644 --- a/examples/misc/test/language_tour/exceptions_test.dart +++ b/examples/misc/test/language_tour/exceptions_test.dart @@ -24,10 +24,13 @@ void main() { // #enddocregion rethrow expect( - main, - prints(allOf([ + main, + prints( + allOf([ contains('misbehave() partially handled'), - contains('main() finished handling') - ]))); + contains('main() finished handling'), + ]), + ), + ); }); } diff --git a/examples/misc/test/language_tour/functions_test.dart b/examples/misc/test/language_tour/functions_test.dart index ed55c32f01..71a2eef97c 100644 --- a/examples/misc/test/language_tour/functions_test.dart +++ b/examples/misc/test/language_tour/functions_test.dart @@ -22,8 +22,10 @@ void main() { assert(say('Bob', 'Howdy') == 'Bob says Howdy'); // #enddocregion call-without-optional-param // #docregion call-with-optional-param - assert(say('Bob', 'Howdy', 'smoke signal') == - 'Bob says Howdy with a smoke signal'); + assert( + say('Bob', 'Howdy', 'smoke signal') == + 'Bob says Howdy with a smoke signal', + ); // #enddocregion call-with-optional-param }); @@ -73,9 +75,10 @@ ORANGES: 7 // #docregion anonymous-function const list = ['apples', 'bananas', 'oranges']; - var uppercaseList = list.map((item) { - return item.toUpperCase(); - }).toList(); + var uppercaseList = + list.map((item) { + return item.toUpperCase(); + }).toList(); // Convert to list after mapping for (var item in uppercaseList) { @@ -123,6 +126,7 @@ ORANGES: 7 } } } + // #enddocregion nested-functions }); diff --git a/examples/misc/test/language_tour/operators_test.dart b/examples/misc/test/language_tour/operators_test.dart index 651b996e77..3b5fec53bf 100644 --- a/examples/misc/test/language_tour/operators_test.dart +++ b/examples/misc/test/language_tour/operators_test.dart @@ -26,10 +26,14 @@ void main() { int d = 1, i = 1, n = 1; // #docregion precedence // Parentheses improve readability. - if ((n % i == 0) && (d % i == 0)) {/*-...-*/} + if ((n % i == 0) && (d % i == 0)) { + // ... + } // Harder to read, but equivalent. - if (n % i == 0 && d % i == 0) {/*-...-*/} + if (n % i == 0 && d % i == 0) { + // ... + } // #enddocregion precedence }); @@ -81,8 +85,10 @@ void main() { }); test('is-vs-as', () { - expect(employee.main, - m.prints(['in Person', 'in Employee', "Instance of 'Employee'"])); + expect( + employee.main, + m.prints(['in Person', 'in Employee', "Instance of 'Employee'"]), + ); }); group('`=` vs `??=`:', () { @@ -119,20 +125,16 @@ void main() { test('var initially non-null', () { expect( - testInitiallyNonNull, - m.prints([ - 'Initially: a == 0, b == 0', - 'After: a == 1, b == 0', - ])); + testInitiallyNonNull, + m.prints(['Initially: a == 0, b == 0', 'After: a == 1, b == 0']), + ); }); test('var initially non-null', () { expect( - testNull, - m.prints([ - 'Initially: a == null, b == null', - 'After: a == 1, b == 1', - ])); + testNull, + m.prints(['Initially: a == null, b == null', 'After: a == 1, b == 1']), + ); }); /* diff --git a/examples/misc/test/library_tour/convert_test.dart b/examples/misc/test/library_tour/convert_test.dart index bf4039541e..b27df05678 100644 --- a/examples/misc/test/library_tour/convert_test.dart +++ b/examples/misc/test/library_tour/convert_test.dart @@ -31,14 +31,16 @@ void main() { var scores = [ {'score': 40}, {'score': 80}, - {'score': 100, 'overtime': true, 'special_guest': null} + {'score': 100, 'overtime': true, 'special_guest': null}, ]; var jsonText = jsonEncode(scores); - assert(jsonText == - '[{"score":40},{"score":80},' - '{"score":100,"overtime":true,' - '"special_guest":null}]'); + assert( + jsonText == + '[{"score":40},{"score":80},' + '{"score":100,"overtime":true,' + '"special_guest":null}]', + ); // #enddocregion json-encode }); @@ -49,7 +51,7 @@ void main() { 0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, //line-br 0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4, //line-br 0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5, //line-br - 0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1 //line-br + 0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1, //line-br ]; var funnyWord = utf8.decode(utf8Bytes); diff --git a/examples/misc/test/library_tour/core_test.dart b/examples/misc/test/library_tour/core_test.dart index 88064af29c..fba6811932 100644 --- a/examples/misc/test/library_tour/core_test.dart +++ b/examples/misc/test/library_tour/core_test.dart @@ -330,7 +330,7 @@ void main() { var hawaiianBeaches = { 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'], 'Big Island': ['Wailea Bay', 'Pololu Beach'], - 'Kauai': ['Hanalei', 'Poipu'] + 'Kauai': ['Hanalei', 'Poipu'], }; // Maps can be built from a constructor. @@ -366,7 +366,7 @@ void main() { var hawaiianBeaches = { 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'], 'Big Island': ['Wailea Bay', 'Pololu Beach'], - 'Kauai': ['Hanalei', 'Poipu'] + 'Kauai': ['Hanalei', 'Poipu'], }; // Get all the keys as an unordered collection @@ -389,7 +389,7 @@ void main() { var hawaiianBeaches = { 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'], 'Big Island': ['Wailea Bay', 'Pololu Beach'], - 'Kauai': ['Hanalei', 'Poipu'] + 'Kauai': ['Hanalei', 'Poipu'], }; assert(hawaiianBeaches.containsKey('Oahu')); @@ -449,8 +449,10 @@ void main() { // #enddocregion map-for-each } - expect(testForEach, - m.prints('I want to visit Honolulu and swim at Hanauma Bay')); + expect( + testForEach, + m.prints('I want to visit Honolulu and swim at Hanauma Bay'), + ); }); test('List.map()', () { @@ -519,7 +521,8 @@ void main() { var encoded = Uri.encodeComponent(uri); assert( - encoded == 'https%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message'); + encoded == 'https%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message', + ); var decoded = Uri.decodeComponent(encoded); assert(uri == decoded); @@ -541,11 +544,12 @@ void main() { test('constructor', () { // #docregion uri var uri = Uri( - scheme: 'https', - host: 'example.org', - path: '/foo/bar', - fragment: 'frag', - queryParameters: {'lang': 'dart'}); + scheme: 'https', + host: 'example.org', + path: '/foo/bar', + fragment: 'frag', + queryParameters: {'lang': 'dart'}, + ); assert(uri.toString() == 'https://example.org/foo/bar?lang=dart#frag'); // #enddocregion uri }); diff --git a/examples/misc/test/library_tour/io_test.dart b/examples/misc/test/library_tour/io_test.dart index e3a6073427..eb92dc67c8 100644 --- a/examples/misc/test/library_tour/io_test.dart +++ b/examples/misc/test/library_tour/io_test.dart @@ -27,9 +27,12 @@ void main() { // #enddocregion read-as-string expect( - main, - m.prints( - ['The file is 58 characters long.', 'The file is 4 lines long.'])); + main, + m.prints([ + 'The file is 58 characters long.', + 'The file is 4 lines long.', + ]), + ); }); test('readAsBytes', () { @@ -63,11 +66,14 @@ void main() { test('read-from-stream', () { expect( - main_test_read_from_stream, - prints(allOf([ + main_test_read_from_stream, + prints( + allOf([ contains(RegExp(r'Got \d+ characters from stream')), contains('file is now closed'), - ]))); + ]), + ), + ); }); test('write-file', () async { @@ -123,16 +129,14 @@ void main() { // #enddocregion client http_server.stopAfter = 1; - void clientAndServer() => Future.wait([ - http_server.main(), - main(), - ]); + void clientAndServer() => Future.wait([http_server.main(), main()]); expect( - clientAndServer, - m.prints([ - 'Got request for /dart', - 'Response 200: [Hello from the server]' - ])); + clientAndServer, + m.prints([ + 'Got request for /dart', + 'Response 200: [Hello from the server]', + ]), + ); }); } diff --git a/examples/misc/test/samples_test.dart b/examples/misc/test/samples_test.dart index 4c56bdc942..02a6ea19a0 100644 --- a/examples/misc/test/samples_test.dart +++ b/examples/misc/test/samples_test.dart @@ -44,7 +44,7 @@ void main() { var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune']; var image = { 'tags': ['saturn'], - 'url': '//path/to/saturn.jpg' + 'url': '//path/to/saturn.jpg', }; // #enddocregion var @@ -52,7 +52,9 @@ void main() { expect(flybyObjects, TypeMatcher<List<String>>()); expect(image, TypeMatcher<Map<String, dynamic>>()); expect( - name.length > antennaDiameter, isTrue); // avoid unused_local_variable + name.length > antennaDiameter, + isTrue, + ); // avoid unused_local_variable }); test('Control flow', () { @@ -79,12 +81,15 @@ void main() { } expect( - testControlFlow, - m.prints(flatten([ + testControlFlow, + m.prints( + flatten([ '20th century', flybyObjects, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], - ]))); + ]), + ), + ); }); test('arrow', () { @@ -127,17 +132,15 @@ void main() { } expect( - testUseClass, - prints(allOf( - startsWith('Spacecraft: Voyager I'), - contains('Launched: 1977'), - ))); + testUseClass, + prints( + allOf(startsWith('Spacecraft: Voyager I'), contains('Launched: 1977')), + ), + ); expect( - testNamedConstructor, - m.prints([ - 'Spacecraft: Voyager III', - 'Unlaunched', - ])); + testNamedConstructor, + m.prints(['Spacecraft: Voyager III', 'Unlaunched']), + ); }); test('use enum', () { @@ -221,7 +224,8 @@ void main() { if (await file.exists()) { var modified = await file.lastModified(); print( - 'File for $object already exists. It was modified on $modified.'); + 'File for $object already exists. It was modified on $modified.', + ); continue; } await file.create(); @@ -240,10 +244,9 @@ void main() { } expect( - testAwait, - prints( - contains('File for test_data/config already exists.'), - )); + testAwait, + prints(contains('File for test_data/config already exists.')), + ); }); }); @@ -293,7 +296,9 @@ void main() { } // #enddocregion try - expect(() => describeFlybyObjects(flybyObjects), - prints(startsWith('Could not describe object:'))); + expect( + () => describeFlybyObjects(flybyObjects), + prints(startsWith('Could not describe object:')), + ); }); } diff --git a/examples/misc/test/try_dart_test.dart b/examples/misc/test/try_dart_test.dart index 89f3d9c4db..27db53d806 100644 --- a/examples/misc/test/try_dart_test.dart +++ b/examples/misc/test/try_dart_test.dart @@ -28,9 +28,7 @@ void main() { Instance of 'Chest<Item>' has 2 items. Instance of 'DiamondSword' dealt 50 damage. Instance of 'Sword' dealt 5 damage. - ''' - .trimLeft() - .replaceAll(RegExp(r'\n\s*'), '\n'); + '''.trimLeft().replaceAll(RegExp(r'\n\s*'), '\n'); expect(classes.main, prints(output)); }); } diff --git a/examples/misc/test/tutorial/streams_test.dart b/examples/misc/test/tutorial/streams_test.dart index 4e08444bf0..0d3500ff37 100644 --- a/examples/misc/test/tutorial/streams_test.dart +++ b/examples/misc/test/tutorial/streams_test.dart @@ -6,6 +6,8 @@ import 'package:examples/tutorial/sum_stream_with_catch.dart' void main() { test('sumStream', () => expect(sum_stream.main, prints('55\n'))); - test('sumStream with catch', - () => expect(sum_stream_with_catch.main, prints('-1\n'))); + test( + 'sumStream with catch', + () => expect(sum_stream_with_catch.main, prints('-1\n')), + ); } diff --git a/examples/non_promotion/lib/non_promotion.dart b/examples/non_promotion/lib/non_promotion.dart index b7979d2c99..9a8659a5af 100644 --- a/examples/non_promotion/lib/non_promotion.dart +++ b/examples/non_promotion/lib/non_promotion.dart @@ -48,6 +48,7 @@ void miscDeclAnalyzedButNotTested() { print(i.isEven); } } + // #enddocregion write-combine-ifs } @@ -62,6 +63,7 @@ void miscDeclAnalyzedButNotTested() { print(i.isEven); } } + // #enddocregion write-change-type } @@ -73,6 +75,7 @@ void miscDeclAnalyzedButNotTested() { p = p.next; } } + // #enddocregion loop } @@ -88,6 +91,7 @@ void miscDeclAnalyzedButNotTested() { continue label; } } + // #enddocregion switch-loop } @@ -134,38 +138,42 @@ void miscDeclAnalyzedButNotTested() { { // #docregion subtype-variable void f(Object o) { - if (o is Comparable /* (1) */) { + if (o is Comparable /* (1) */ ) { Object o2 = o; - if (o2 is Pattern /* (2) */) { + if (o2 is Pattern /* (2) */ ) { print( - o2.matchAsPrefix('foo')); // (3) OK; o2 was promoted to `Pattern`. + o2.matchAsPrefix('foo'), + ); // (3) OK; o2 was promoted to `Pattern`. } } } + // #enddocregion subtype-variable } { // #docregion subtype-redundant void f(Object o) { - if (o is Comparable /* (1) */) { - if (o is Pattern /* (2) */) { + if (o is Comparable /* (1) */ ) { + if (o is Pattern /* (2) */ ) { print((o as Pattern).matchAsPrefix('foo')); // (3) OK } } } + // #enddocregion subtype-redundant } { // #docregion subtype-string void f(Object o) { - if (o is Comparable /* (1) */) { - if (o is String /* (2) */) { + if (o is Comparable /* (1) */ ) { + if (o is String /* (2) */ ) { print(o.matchAsPrefix('foo')); // (3) OK } } } + // #enddocregion subtype-string } @@ -180,6 +188,7 @@ void miscDeclAnalyzedButNotTested() { }; // ... Use foo ... } + // #enddocregion local-write-capture-reorder } @@ -195,6 +204,7 @@ void miscDeclAnalyzedButNotTested() { // ... Additional code ... print(i2.isEven); // (2) OK because `i2` isn't write captured. } + // #enddocregion local-write-capture-copy } @@ -209,6 +219,7 @@ void miscDeclAnalyzedButNotTested() { // ... Additional code ... print(i!.isEven); // (2) OK due to `!` check. } + // #enddocregion local-write-capture-bang } @@ -222,6 +233,7 @@ void miscDeclAnalyzedButNotTested() { }; i = j; // (2) } + // #enddocregion closure-new-var } @@ -233,6 +245,7 @@ void miscDeclAnalyzedButNotTested() { print(j.isEven); // OK }; } + // #enddocregion closure-new-var2 } @@ -248,6 +261,7 @@ void miscDeclAnalyzedButNotTested() { i = j; }; } + // #enddocregion closure-write-capture } } @@ -384,4 +398,5 @@ void f4(MockingExample x) { int i = x._i; // OK } } + // #enddocregion mock diff --git a/examples/non_promotion/pubspec.yaml b/examples/non_promotion/pubspec.yaml index 178a896f02..b475c0fb35 100644 --- a/examples/non_promotion/pubspec.yaml +++ b/examples/non_promotion/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.1 resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: mockito: ^5.4.4 diff --git a/examples/pubspec.yaml b/examples/pubspec.yaml index 35ec28865a..fea1f25f03 100644 --- a/examples/pubspec.yaml +++ b/examples/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 workspace: - analysis diff --git a/examples/type_system/lib/animal.dart b/examples/type_system/lib/animal.dart index 44a359fb40..06ae4ce238 100644 --- a/examples/type_system/lib/animal.dart +++ b/examples/type_system/lib/animal.dart @@ -4,7 +4,9 @@ import 'package:examples_util/ellipsis.dart'; // #docregion Animal class Animal { - void chase(Animal a) {/* ... */} + void chase(Animal a) { + /* ... */ + } Animal get parent => ellipsis(); } // #enddocregion Animal @@ -12,7 +14,9 @@ class Animal { // #docregion HoneyBadger class HoneyBadger extends Animal { @override - void chase(Animal a) {/* ... */} + void chase(Animal a) { + /* ... */ + } @override HoneyBadger get parent => ellipsis(); @@ -22,17 +26,27 @@ class HoneyBadger extends Animal { // #docregion chase-Object class HoneyBadger1 extends Animal { @override - void chase(Object a) {/* ... */} + void chase(Object a) { + /* ... */ + } @override Animal get parent => ellipsis(); } // #enddocregion chase-Object -class Alligator extends Animal {/* ... */} +class Alligator extends Animal { + /* ... */ +} -class Cat extends Animal {/* ... */} +class Cat extends Animal { + /* ... */ +} -class Dog extends Animal {/* ... */} +class Dog extends Animal { + /* ... */ +} -class MaineCoon extends Cat {/* ... */} +class MaineCoon extends Cat { + /* ... */ +} diff --git a/examples/type_system/lib/common_fixes_analysis.dart b/examples/type_system/lib/common_fixes_analysis.dart index 8353181af1..13d744c685 100644 --- a/examples/type_system/lib/common_fixes_analysis.dart +++ b/examples/type_system/lib/common_fixes_analysis.dart @@ -71,13 +71,17 @@ void adderRuntimeFail() { // #docregion type-arguments class Superclass<T> { - void method(T param) {/* ... */} + void method(T param) { + /* ... */ + } } class Subclass extends Superclass { @override // ignore: stable, beta, dev, invalid_override - void method(int param) {/* ... */} + void method(int param) { + /* ... */ + } } // #enddocregion type-arguments @@ -93,19 +97,21 @@ class _HoneyBadger extends Animal { final String _name; // #docregion super-goes-last _HoneyBadger(Eats food, String name) - // ignore: stable, beta, dev, super_invocation_not_last - : super(food), - _name = name {/* ... */} -// #enddocregion super-goes-last + // ignore: stable, beta, dev, super_invocation_not_last + : super(food), + _name = name { + /* ... */ + } + // #enddocregion super-goes-last } class HoneyBadger extends Animal { final String _name; // #docregion super-goes-last-ok - HoneyBadger(Eats food, String name) - : _name = name, - super(food) {/* ... */} -// #enddocregion super-goes-last-ok + HoneyBadger(Eats food, String name) : _name = name, super(food) { + /* ... */ + } + // #enddocregion super-goes-last-ok } //----------------------------------------------- @@ -145,8 +151,10 @@ void infNull() { void infFix() { // #docregion type-inf-fix var ints = [1, 2, 3]; - var maximumOrNull = - ints.fold<int?>(null, (a, b) => a == null || a < b ? b : a); + var maximumOrNull = ints.fold<int?>( + null, + (a, b) => a == null || a < b ? b : a, + ); // #enddocregion type-inf-fix } @@ -159,4 +167,5 @@ abstract class C implements List<int> {} // #docregion conflicting-generics // ignore: duplicate_definition, inconsistent_inheritance, conflicting_generic_interfaces abstract class C implements List<int>, Iterable<num> {} + // #enddocregion conflicting-generics diff --git a/examples/type_system/lib/covariant.dart b/examples/type_system/lib/covariant.dart index 280a341ace..615d5f9509 100644 --- a/examples/type_system/lib/covariant.dart +++ b/examples/type_system/lib/covariant.dart @@ -1,10 +1,16 @@ class Animal { - void chase(Animal x) {/* ... */} + void chase(Animal x) { + /* ... */ + } } -class Mouse extends Animal {/* ... */} +class Mouse extends Animal { + /* ... */ +} class Cat extends Animal { @override - void chase(covariant Mouse x) {/* ... */} + void chase(covariant Mouse x) { + /* ... */ + } } diff --git a/examples/type_system/lib/incorrect_animal.dart b/examples/type_system/lib/incorrect_animal.dart index 1d3fd128ba..1a78d906ea 100644 --- a/examples/type_system/lib/incorrect_animal.dart +++ b/examples/type_system/lib/incorrect_animal.dart @@ -2,12 +2,16 @@ import 'animal.dart'; // #docregion chase-mouse -class Mouse extends Animal {/* ... */} +class Mouse extends Animal { + /* ... */ +} class Cat extends Animal { @override // ignore: invalid_override - void chase(Mouse a) {/* ... */} + void chase(Mouse a) { + /* ... */ + } } // #enddocregion chase-mouse @@ -25,5 +29,6 @@ void invalidDynamicList() { List<Cat> foo = <dynamic>[Dog()]; // Error List<dynamic> bar = <dynamic>[Dog(), Cat()]; // OK } + // #enddocregion invalid-dynamic-list } diff --git a/examples/type_system/pubspec.yaml b/examples/type_system/pubspec.yaml index 6a65c8140c..74aa0975a1 100644 --- a/examples/type_system/pubspec.yaml +++ b/examples/type_system/pubspec.yaml @@ -3,7 +3,7 @@ description: dart.dev type system examples. resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: examples_util: {path: ../util} diff --git a/examples/type_system/test/strong_test.dart b/examples/type_system/test/strong_test.dart index 9b83970347..ea5a1650af 100644 --- a/examples/type_system/test/strong_test.dart +++ b/examples/type_system/test/strong_test.dart @@ -5,12 +5,8 @@ import 'package:type_system_examples/animal.dart'; import 'package:type_system_examples/bounded/my_collection.dart'; Matcher _throwsA<T>(String msg) => throwsA( - allOf( - TypeMatcher<T>(), - predicate( - (e) => e.toString().contains(msg), - )), - ); + allOf(TypeMatcher<T>(), predicate((e) => e.toString().contains(msg))), +); void main() { test('opening example', () { @@ -83,8 +79,8 @@ void main() { }); Map<String, dynamic> fetchFromExternalSource() => { - 'names': ['a string'] - }; + 'names': ['a string'], + }; test('downcast check ok: use cast()', () { void downcastCheck() { diff --git a/examples/util/pubspec.yaml b/examples/util/pubspec.yaml index 5db44f9072..b0daf40ebc 100644 --- a/examples/util/pubspec.yaml +++ b/examples/util/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.2 resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: test: ^1.25.8 diff --git a/examples/vector_victor/pubspec.yaml b/examples/vector_victor/pubspec.yaml index 19f93d642a..b7189ec88c 100644 --- a/examples/vector_victor/pubspec.yaml +++ b/examples/vector_victor/pubspec.yaml @@ -5,7 +5,7 @@ version: 1.0.0 resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 # dependencies: # path: ^1.8.0 diff --git a/pubspec.yaml b/pubspec.yaml index 974d32b849..1029ee3a72 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none homepage: https://dart.dev environment: - sdk: ^3.6.1 + sdk: ^3.7.0 workspace: - tool/dart_site diff --git a/src/_data/site.yml b/src/_data/site.yml index 9061150f23..b47ef13ab7 100644 --- a/src/_data/site.yml +++ b/src/_data/site.yml @@ -40,4 +40,4 @@ show_banner: false # in the `firebase.json` redirect rule.) og_image_vers: "?2" -sdkVersion: 3.6.2 +sdkVersion: 3.7.0 diff --git a/src/content/deprecated/sound-problems.md b/src/content/deprecated/sound-problems.md index ce2c63053a..4b97ffd354 100644 --- a/src/content/deprecated/sound-problems.md +++ b/src/content/deprecated/sound-problems.md @@ -278,12 +278,16 @@ which results in an invalid override error on `method(int)`. <?code-excerpt "lib/common_fixes_analysis.dart (type-arguments)" replace="/int/[!$&!]/g"?> ```dart tag=fails-sa class Superclass<T> { - void method(T param) { ... } + void method(T param) { + ... + } } class Subclass extends Superclass { @override - void method([!int!] param) { ... } + void method([!int!] param) { + ... + } } ``` @@ -303,12 +307,16 @@ You can fix the example by specifying the type on the subclass: <?code-excerpt "lib/common_fixes_analysis.dart (type-arguments)" replace="/Superclass /Superclass[!<int\x3E!] /g"?> ```dart tag=passes-sa class Superclass<T> { - void method(T param) { ... } + void method(T param) { + ... + } } class Subclass extends Superclass[!<int>!] { @override - void method(int param) { ... } + void method(int param) { + ... + } } ``` @@ -391,8 +399,10 @@ initialization list. <?code-excerpt "lib/common_fixes_analysis.dart (super-goes-last)" replace="/super/[!$&!]/g; /_HoneyBadger/HoneyBadger/g"?> ```dart tag=fails-sa HoneyBadger(Eats food, String name) - : [!super!](food), - _name = name { ... } + : [!super!](food), + _name = name { + ... +} ``` <?code-excerpt "analyzer-results-stable.txt" retain="/The superconstructor call must be last in an initializer list.*/" replace="/-(.*?):(.*?):(.*?)-/-/g"?> @@ -409,9 +419,9 @@ Fix this error by moving the `super()` call: <?code-excerpt "lib/common_fixes_analysis.dart (super-goes-last-ok)" replace="/super/[!$&!]/g"?> ```dart tag=passes-sa -HoneyBadger(Eats food, String name) - : _name = name, - [!super!](food) { ... } +HoneyBadger(Eats food, String name) : _name = name, [!super!](food) { + ... +} ``` <hr> @@ -488,8 +498,10 @@ var maximumOrNull = ints.fold(null, (a, b) => a == null || a < b ? b : a); <?code-excerpt "lib/common_fixes_analysis.dart (type-inf-fix)"?> ```dart tag=passes-sa var ints = [1, 2, 3]; -var maximumOrNull = - ints.fold<int?>(null, (a, b) => a == null || a < b ? b : a); +var maximumOrNull = ints.fold<int?>( + null, + (a, b) => a == null || a < b ? b : a, +); ``` <hr> diff --git a/src/content/effective-dart/design.md b/src/content/effective-dart/design.md index 8eebcc50b0..bfaac5ac8b 100644 --- a/src/content/effective-dart/design.md +++ b/src/content/effective-dart/design.md @@ -93,7 +93,9 @@ it like a sentence. <?code-excerpt "design_good.dart (code-like-prose)"?> ```dart tag=good // "If errors is empty..." -if (errors.isEmpty) ... +if (errors.isEmpty) { + // ... +} // "Hey, subscription, cancel!" subscription.cancel(); @@ -105,7 +107,9 @@ monsters.where((monster) => monster.hasClaws); <?code-excerpt "design_bad.dart (code-like-prose)" replace="/ as bool//g"?> ```dart tag=bad // Telling errors to empty itself, or asking if it is? -if (errors.empty) ... +if (errors.empty) { + // ... +} // Toggle what? To what? subscription.toggle(); @@ -120,7 +124,9 @@ to force your names to *literally* read like a grammatically correct sentence. <?code-excerpt "design_bad.dart (code-like-prose-overdone)"?> ```dart tag=bad -if (theCollectionOfErrors.isEmpty) ... +if (theCollectionOfErrors.isEmpty) { + // ... +} monsters.producesANewSequenceWhereEach((monster) => monster.hasClaws); ``` @@ -931,10 +937,11 @@ Method cascades are a better solution for chaining method calls. <?code-excerpt "design_good.dart (cascades)"?> ```dart tag=good -var buffer = StringBuffer() - ..write('one') - ..write('two') - ..write('three'); +var buffer = + StringBuffer() + ..write('one') + ..write('two') + ..write('three'); ``` <?code-excerpt "design_bad.dart (cascades)"?> @@ -1517,12 +1524,16 @@ Setters always return `void` in Dart. Writing the word is pointless. <?code-excerpt "design_bad.dart (avoid_return_types_on_setters)"?> ```dart tag=bad -void set foo(Foo value) { ... } +void set foo(Foo value) { + ... +} ``` <?code-excerpt "design_good.dart (avoid_return_types_on_setters)"?> ```dart tag=good -set foo(Foo value) { ... } +set foo(Foo value) { + ... +} ``` @@ -1743,7 +1754,9 @@ means it's OK for a *callback's* type to return `FutureOr<T>`: <?code-excerpt "design_good.dart (future-or-contra)" replace="/FutureOr.S./[!$&!]/g"?> ```dart tag=good Stream<S> asyncMap<T, S>( - Iterable<T> iterable, [!FutureOr<S>!] Function(T) callback) async* { + Iterable<T> iterable, + [!FutureOr<S>!] Function(T) callback, +) async* { for (final element in iterable) { yield await callback(element); } @@ -1803,22 +1816,25 @@ pass later one. You're better off using named arguments for that. ```dart tag=good String.fromCharCodes(Iterable<int> charCodes, [int start = 0, int? end]); -DateTime(int year, - [int month = 1, - int day = 1, - int hour = 0, - int minute = 0, - int second = 0, - int millisecond = 0, - int microsecond = 0]); - -Duration( - {int days = 0, - int hours = 0, - int minutes = 0, - int seconds = 0, - int milliseconds = 0, - int microseconds = 0}); +DateTime( + int year, [ + int month = 1, + int day = 1, + int hour = 0, + int minute = 0, + int second = 0, + int millisecond = 0, + int microsecond = 0, +]); + +Duration({ + int days = 0, + int hours = 0, + int minutes = 0, + int seconds = 0, + int milliseconds = 0, + int microseconds = 0, +}); ``` diff --git a/src/content/effective-dart/documentation.md b/src/content/effective-dart/documentation.md index 1432e85a0b..e1eeacd184 100644 --- a/src/content/effective-dart/documentation.md +++ b/src/content/effective-dart/documentation.md @@ -322,7 +322,9 @@ extra effort here can make all of the other members simpler to document. /// A chunk of non-breaking output text terminated by a hard or soft newline. /// /// ... -class Chunk { ... } +class Chunk { + ... +} ``` ### CONSIDER including code samples in doc comments diff --git a/src/content/effective-dart/style.md b/src/content/effective-dart/style.md index 4d768d9253..ceb949afca 100644 --- a/src/content/effective-dart/style.md +++ b/src/content/effective-dart/style.md @@ -40,9 +40,13 @@ letter of each word (including the first word), and use no separators. <?code-excerpt "style_good.dart (type-names)"?> ```dart tag=good -class SliderMenu { ... } +class SliderMenu { + ... +} -class HttpRequest { ... } +class HttpRequest { + ... +} typedef Predicate<T> = bool Function(T value); ``` @@ -56,10 +60,14 @@ class Foo { } @Foo(anArg) -class A { ... } +class A { + ... +} @Foo() -class B { ... } +class B { + ... +} ``` If the annotation class's constructor takes no parameters, you might want to @@ -70,7 +78,9 @@ create a separate `lowerCamelCase` constant for it. const foo = Foo(); @foo -class C { ... } +class C { + ... +} ``` ### DO name extensions using `UpperCamelCase` @@ -83,9 +93,13 @@ and use no separators. <?code-excerpt "style_good.dart (extension-names)"?> ```dart tag=good -extension MyFancyList<T> on List<T> { ... } +extension MyFancyList<T> on List<T> { + ... +} -extension SmartIterable<T> on Iterable<T> { ... } +extension SmartIterable<T> on Iterable<T> { + ... +} ``` [extensions]: /language/extension-methods diff --git a/src/content/effective-dart/usage.md b/src/content/effective-dart/usage.md index e16ef74c6d..5ab682ba49 100644 --- a/src/content/effective-dart/usage.md +++ b/src/content/effective-dart/usage.md @@ -245,16 +245,24 @@ and use the unary negation operator `!` if necessary: <?code-excerpt "usage_good.dart (non-null-boolean-expression)"?> ```dart tag=good -if (nonNullableBool) { ... } +if (nonNullableBool) { + ... +} -if (!nonNullableBool) { ... } +if (!nonNullableBool) { + ... +} ``` <?code-excerpt "usage_bad.dart (non-null-boolean-expression)"?> ```dart tag=bad -if (nonNullableBool == true) { ... } +if (nonNullableBool == true) { + ... +} -if (nonNullableBool == false) { ... } +if (nonNullableBool == false) { + ... +} ``` To evaluate a boolean expression that *is nullable*, you should use `??` @@ -263,20 +271,28 @@ or an explicit `!= null` check. <?code-excerpt "usage_good.dart (nullable-boolean-expression)"?> ```dart tag=good // If you want null to result in false: -if (nullableBool ?? false) { ... } +if (nullableBool ?? false) { + ... +} // If you want null to result in false // and you want the variable to type promote: -if (nullableBool != null && nullableBool) { ... } +if (nullableBool != null && nullableBool) { + ... +} ``` <?code-excerpt "usage_bad.dart (nullable-boolean-expression)"?> ```dart tag=bad // Static error if null: -if (nullableBool) { ... } +if (nullableBool) { + ... +} // If you want null to be false: -if (nullableBool == true) { ... } +if (nullableBool == true) { + ... +} ``` `nullableBool == true` is a viable expression, @@ -437,14 +453,18 @@ a single long string that doesn't fit on one line. <?code-excerpt "usage_good.dart (adjacent-strings-literals)"?> ```dart tag=good -raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' - 'parts are overrun by martians. Unclear which are which.'); +raiseAlarm( + 'ERROR: Parts of the spaceship are on fire. Other ' + 'parts are overrun by martians. Unclear which are which.', +); ``` <?code-excerpt "usage_bad.dart (adjacent-strings-literals)"?> ```dart tag=bad -raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' + - 'parts are overrun by martians. Unclear which are which.'); +raiseAlarm( + 'ERROR: Parts of the spaceship are on fire. Other ' + + 'parts are overrun by martians. Unclear which are which.', +); ``` ### PREFER using interpolation to compose strings and values @@ -533,7 +553,7 @@ var arguments = [ command, ...?modeFlags, for (var path in filePaths) - if (path.endsWith('.dart')) path.replaceAll('.dart', '.js') + if (path.endsWith('.dart')) path.replaceAll('.dart', '.js'), ]; ``` @@ -543,9 +563,11 @@ var arguments = <String>[]; arguments.addAll(options); arguments.add(command); if (modeFlags != null) arguments.addAll(modeFlags); -arguments.addAll(filePaths - .where((path) => path.endsWith('.dart')) - .map((path) => path.replaceAll('.dart', '.js'))); +arguments.addAll( + filePaths + .where((path) => path.endsWith('.dart')) + .map((path) => path.replaceAll('.dart', '.js')), +); ``` @@ -953,9 +975,9 @@ class Circle { double circumference; Circle(double radius) - : radius = radius, - area = pi * radius * radius, - circumference = pi * 2.0 * radius; + : radius = radius, + area = pi * radius * radius, + circumference = pi * 2.0 * radius; } ``` @@ -1123,9 +1145,10 @@ Treasure? openChest(Chest chest, Point where) { <?code-excerpt "usage_bad.dart (arrow-long)"?> ```dart tag=bad -Treasure? openChest(Chest chest, Point where) => _opened.containsKey(chest) - ? null - : _opened[chest] = (Treasure(where)..addAll(chest.contents)); +Treasure? openChest(Chest chest, Point where) => + _opened.containsKey(chest) + ? null + : _opened[chest] = (Treasure(where)..addAll(chest.contents)); ``` You can also use `=>` on members that don't return a value. This is idiomatic @@ -1217,9 +1240,7 @@ lists: class Box extends BaseBox { Object? value; - Box(Object? value) - : value = value, - super(value); + Box(Object? value) : value = value, super(value); } ``` @@ -1240,9 +1261,7 @@ class ProfileMark { final DateTime start; ProfileMark(this.name) : start = DateTime.now(); - ProfileMark.unnamed() - : name = '', - start = DateTime.now(); + ProfileMark.unnamed() : name = '', start = DateTime.now(); } ``` @@ -1279,9 +1298,7 @@ Many fields are initialized directly from a constructor parameter, like: ```dart tag=bad class Point { double x, y; - Point(double x, double y) - : x = x, - y = y; + Point(double x, double y) : x = x, y = y; } ``` @@ -1318,8 +1335,8 @@ initialize the field in the constructor initializer list: class Point { double x, y; Point.polar(double theta, double radius) - : x = cos(theta) * radius, - y = sin(theta) * radius; + : x = cos(theta) * radius, + y = sin(theta) * radius; } ``` @@ -1379,12 +1396,7 @@ it deprecated and avoid using it in your code. ```dart tag=good Widget build(BuildContext context) { return Row( - children: [ - RaisedButton( - child: Text('Increment'), - ), - Text('Click!'), - ], + children: [RaisedButton(child: Text('Increment')), Text('Click!')], ); } ``` @@ -1394,9 +1406,7 @@ Widget build(BuildContext context) { Widget build(BuildContext context) { return [!new!] Row( children: [ - [!new!] RaisedButton( - child: [!new!] Text('Increment'), - ), + [!new!] RaisedButton(child: [!new!] Text('Increment')), [!new!] Text('Click!'), ], ); @@ -1564,16 +1574,18 @@ Future<int> countActivePlayers(String teamName) [!async!] { <?code-excerpt "usage_bad.dart (async-await)"?> ```dart tag=bad Future<int> countActivePlayers(String teamName) { - return downloadTeam(teamName).then((team) { - if (team == null) return Future.value(0); - - return team.roster.then((players) { - return players.where((player) => player.isActive).length; - }); - }).catchError((e) { - log.error(e); - return 0; - }); + return downloadTeam(teamName) + .then((team) { + if (team == null) return Future.value(0); + + return team.roster.then((players) { + return players.where((player) => player.isActive).length; + }); + }) + .catchError((e) { + log.error(e); + return 0; + }); } ``` diff --git a/src/content/language/branches.md b/src/content/language/branches.md index 722f5b223f..4f1fee84c9 100644 --- a/src/content/language/branches.md +++ b/src/content/language/branches.md @@ -187,7 +187,7 @@ token = switch (charCode) { slash || star || plus || minus => operator(charCode), comma || semicolon => punctuation(charCode), >= digit0 && <= digit9 => number(), - _ => throw FormatException('Invalid') + _ => throw FormatException('Invalid'), }; ``` @@ -246,9 +246,9 @@ class Circle implements Shape { } double calculateArea(Shape shape) => switch (shape) { - Square(length: var l) => l * l, - Circle(radius: var r) => math.pi * r * r - }; + Square(length: var l) => l * l, + Circle(radius: var r) => math.pi * r * r, +}; ``` If anyone were to add a new subclass of `Shape`, diff --git a/src/content/language/built-in-types.md b/src/content/language/built-in-types.md index 42defd9142..7d72bcf31d 100644 --- a/src/content/language/built-in-types.md +++ b/src/content/language/built-in-types.md @@ -221,13 +221,17 @@ object's `toString()` method. ```dart var s = 'string interpolation'; -assert('Dart has $s, which is very handy.' == - 'Dart has string interpolation, ' - 'which is very handy.'); -assert('That deserves all caps. ' - '${s.toUpperCase()} is very handy!' == - 'That deserves all caps. ' - 'STRING INTERPOLATION is very handy!'); +assert( + 'Dart has $s, which is very handy.' == + 'Dart has string interpolation, ' + 'which is very handy.', +); +assert( + 'That deserves all caps. ' + '${s.toUpperCase()} is very handy!' == + 'That deserves all caps. ' + 'STRING INTERPOLATION is very handy!', +); ``` :::note @@ -241,12 +245,15 @@ operator: <?code-excerpt "misc/test/language_tour/built_in_types_test.dart (adjacent-string-literals)"?> ```dart -var s1 = 'String ' +var s1 = + 'String ' 'concatenation' " works even over line breaks."; -assert(s1 == - 'String concatenation works even over ' - 'line breaks.'); +assert( + s1 == + 'String concatenation works even over ' + 'line breaks.', +); var s2 = 'The + operator ' + 'works, as well.'; assert(s2 == 'The + operator works, as well.'); @@ -437,4 +444,4 @@ Symbol literals are compile-time constants. [characters API]: {{site.pub-api}}/characters [characters example]: {{site.pub-pkg}}/characters/example [`Symbol`]: {{site.dart-api}}/dart-core/Symbol-class.html -[language version]: /resources/language/evolution#language-versioning \ No newline at end of file +[language version]: /resources/language/evolution#language-versioning diff --git a/src/content/language/class-modifiers-for-apis.md b/src/content/language/class-modifiers-for-apis.md index c4b0fc0cf0..a4d34cf23f 100644 --- a/src/content/language/class-modifiers-for-apis.md +++ b/src/content/language/class-modifiers-for-apis.md @@ -251,10 +251,10 @@ class Dusty extends Amigo {} class Ned extends Amigo {} String lastName(Amigo amigo) => switch (amigo) { - Lucky _ => 'Day', - Dusty _ => 'Bottoms', - Ned _ => 'Nederlander', - }; + Lucky _ => 'Day', + Dusty _ => 'Bottoms', + Ned _ => 'Nederlander', +}; ``` This switch has a case for each of the subtypes of `Amigo`. diff --git a/src/content/language/classes.md b/src/content/language/classes.md index 15d42fe714..0a06bd777d 100644 --- a/src/content/language/classes.md +++ b/src/content/language/classes.md @@ -287,7 +287,9 @@ interfaces: <?code-excerpt "misc/lib/language_tour/classes/misc.dart (point-interfaces)"?> ```dart -class Point implements Comparable, Location {...} +class Point implements Comparable, Location { + ... +} ``` diff --git a/src/content/language/collections.md b/src/content/language/collections.md index 76f35af32f..569edbc626 100644 --- a/src/content/language/collections.md +++ b/src/content/language/collections.md @@ -42,11 +42,7 @@ but it can help prevent copy-paste errors. <?code-excerpt "misc/lib/language_tour/built_in_types.dart (trailing-commas)"?> ```dart -var list = [ - 'Car', - 'Boat', - 'Plane', -]; +var list = ['Car', 'Boat', 'Plane']; ``` Lists use zero-based indexing, where 0 is the index of the first value @@ -165,14 +161,10 @@ var gifts = { // Key: Value 'first': 'partridge', 'second': 'turtledoves', - 'fifth': 'golden rings' + 'fifth': 'golden rings', }; -var nobleGases = { - 2: 'helium', - 10: 'neon', - 18: 'argon', -}; +var nobleGases = {2: 'helium', 10: 'neon', 18: 'argon'}; ``` :::note @@ -242,11 +234,7 @@ add `const` before the map literal: <?code-excerpt "misc/lib/language_tour/built_in_types.dart (const-map)"?> ```dart -final constantMap = const { - 2: 'helium', - 10: 'neon', - 18: 'argon', -}; +final constantMap = const {2: 'helium', 10: 'neon', 18: 'argon'}; // constantMap[2] = 'Helium'; // This line will cause an error. ``` diff --git a/src/content/language/constructors.md b/src/content/language/constructors.md index 26558a3633..867b2e3008 100644 --- a/src/content/language/constructors.md +++ b/src/content/language/constructors.md @@ -84,9 +84,7 @@ class Point { Point(this.x, this.y); // Named constructor - [!Point.origin()!] - : x = xOrigin, - y = yOrigin; + [!Point.origin()!] : x = xOrigin, y = yOrigin; } ``` @@ -398,9 +396,7 @@ Separate initializers with commas. ```dart // Initializer list sets instance variables before // the constructor body runs. -Point.fromJson(Map<String, double> json) - : x = json['x']!, - y = json['y']! { +Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']! { print('In Point.fromJson(): ($x, $y)'); } ``` @@ -434,9 +430,9 @@ class Point { final double distanceFromOrigin; Point(double x, double y) - : x = x, - y = y, - distanceFromOrigin = sqrt(x * x + y * y); + : x = x, + y = y, + distanceFromOrigin = sqrt(x * x + y * y); } void main() { diff --git a/src/content/language/error-handling.md b/src/content/language/error-handling.md index 8249e43507..86a7d18b1d 100644 --- a/src/content/language/error-handling.md +++ b/src/content/language/error-handling.md @@ -193,8 +193,10 @@ add a string as the second argument to `assert` <?code-excerpt "misc/test/language_tour/control_flow_test.dart (assert-with-message)"?> ```dart -assert(urlString.startsWith('https'), - 'URL ($urlString) should start with "https".'); +assert( + urlString.startsWith('https'), + 'URL ($urlString) should start with "https".', +); ``` The first argument to `assert` can be any expression that diff --git a/src/content/language/extend.md b/src/content/language/extend.md index 782067ebfa..30468974db 100644 --- a/src/content/language/extend.md +++ b/src/content/language/extend.md @@ -47,12 +47,16 @@ intentionally overriding a member: ```dart class Television { // ··· - set contrast(int value) {...} + set contrast(int value) { + ... + } } class SmartTelevision extends Television { [!@override!] - set contrast(num value) {...} + set contrast(num value) { + ... + } // ··· } ``` @@ -101,8 +105,10 @@ class A { // non-existent member results in a NoSuchMethodError. @override void [!noSuchMethod!](Invocation invocation) { - print('You tried to use a non-existent member: ' - '${invocation.memberName}'); + print( + 'You tried to use a non-existent member: ' + '${invocation.memberName}', + ); } } ``` diff --git a/src/content/language/extension-methods.md b/src/content/language/extension-methods.md index 7930b18e92..88f4917501 100644 --- a/src/content/language/extension-methods.md +++ b/src/content/language/extension-methods.md @@ -42,11 +42,13 @@ have that functionality be on `String` instead: To enable that code, you can import a library that contains an extension of the `String` class: -<?code-excerpt "extension_methods/lib/string_extensions/usage_simple_extension.dart (basic)" replace="/ print/print/g"?> +<?code-excerpt "extension_methods/lib/string_extensions/usage_simple_extension.dart (basic)" plaster="none"?> ```dart import 'string_apis.dart'; -// ··· -print('42'.parseInt()); // Use an extension method. + +void main() { + print('42'.parseInt()); // Use an extension method. +} ``` Extensions can define not just methods, @@ -55,13 +57,12 @@ Also, extensions can have names, which can be helpful if an API conflict arises. Here's how you might implement the extension method `parseInt()`, using an extension (named `NumberParsing`) that operates on strings: -<?code-excerpt "extension_methods/lib/string_extensions/string_apis.dart (parseInt)"?> +<?code-excerpt "extension_methods/lib/string_extensions/string_apis.dart (parseInt)" plaster="none"?> ```dart title="lib/string_apis.dart" extension NumberParsing on String { int parseInt() { return int.parse(this); } - // ··· } ``` @@ -75,13 +76,15 @@ Like all Dart code, extension methods are in libraries. You've already seen how to use an extension method—just import the library it's in, and use it like an ordinary method: -<?code-excerpt "extension_methods/lib/string_extensions/usage_simple_extension.dart (import-and-use)" replace="/ print/print/g"?> +<?code-excerpt "extension_methods/lib/string_extensions/usage_simple_extension.dart (import-and-use)" plaster="none"?> ```dart // Import a library that contains an extension on String. import 'string_apis.dart'; -// ··· -print('42'.padLeft(5)); // Use a String method. -print('42'.parseInt()); // Use an extension method. + +void main() { + print('42'.padLeft(5)); // Use a String method. + print('42'.parseInt()); // Use an extension method. +} ``` That's all you usually need to know to use extension methods. @@ -127,7 +130,7 @@ then you have a few options. One option is changing how you import the conflicting extension, using `show` or `hide` to limit the exposed API: -<?code-excerpt "extension_methods/lib/string_extensions/usage_import.dart (hide-conflicts)" replace="/ //g"?> +<?code-excerpt "extension_methods/lib/string_extensions/usage_import.dart (hide-conflicts)" plaster="none"?> ```dart // Defines the String extension method parseInt(). import 'string_apis.dart'; @@ -136,31 +139,33 @@ import 'string_apis.dart'; // hides that extension method. import 'string_apis_2.dart' hide NumberParsing2; -// ··· -// Uses the parseInt() defined in 'string_apis.dart'. -print('42'.parseInt()); +void main() { + // Uses the parseInt() defined in 'string_apis.dart'. + print('42'.parseInt()); +} ``` Another option is applying the extension explicitly, which results in code that looks as if the extension is a wrapper class: -<?code-excerpt "extension_methods/lib/string_extensions/usage_explicit.dart (conflicts-explicit)" replace="/ //g"?> +<?code-excerpt "extension_methods/lib/string_extensions/usage_explicit.dart (conflicts-explicit)" plaster="none"?> ```dart // Both libraries define extensions on String that contain parseInt(), // and the extensions have different names. import 'string_apis.dart'; // Contains NumberParsing extension. import 'string_apis_2.dart'; // Contains NumberParsing2 extension. -// ··· -// print('42'.parseInt()); // Doesn't work. -print(NumberParsing('42').parseInt()); -print(NumberParsing2('42').parseInt()); +void main() { + // print('42'.parseInt()); // Doesn't work. + print(NumberParsing('42').parseInt()); + print(NumberParsing2('42').parseInt()); +} ``` If both extensions have the same name, then you might need to import using a prefix: -<?code-excerpt "extension_methods/lib/string_extensions/usage_prefix.dart (conflicts-prefix)" replace="/ //g"?> +<?code-excerpt "extension_methods/lib/string_extensions/usage_prefix.dart"?> ```dart // Both libraries define extensions named NumberParsing // that contain the extension method parseInt(). One NumberParsing @@ -168,17 +173,18 @@ then you might need to import using a prefix: import 'string_apis.dart'; import 'string_apis_3.dart' as rad; -// ··· -// print('42'.parseInt()); // Doesn't work. +void main() { + // print('42'.parseInt()); // Doesn't work. -// Use the ParseNumbers extension from string_apis.dart. -print(NumberParsing('42').parseInt()); + // Use the ParseNumbers extension from string_apis.dart. + print(NumberParsing('42').parseInt()); -// Use the ParseNumbers extension from string_apis_3.dart. -print(rad.NumberParsing('42').parseInt()); + // Use the ParseNumbers extension from string_apis_3.dart. + print(rad.NumberParsing('42').parseInt()); -// Only string_apis_3.dart has parseNum(). -print('42'.parseNum()); + // Only string_apis_3.dart has parseNum(). + print('42'.parseNum()); +} ``` As the example shows, @@ -209,6 +215,7 @@ extension NumberParsing on String { double parseDouble() { return double.parse(this); } + } ``` diff --git a/src/content/language/functions.md b/src/content/language/functions.md index 03aedd2fa2..376a5ab2cd 100644 --- a/src/content/language/functions.md +++ b/src/content/language/functions.md @@ -92,7 +92,9 @@ as their default value will be `null`: <?code-excerpt "misc/lib/language_tour/functions.dart (specify-named-parameters)"?> ```dart /// Sets the [bold] and [hidden] flags ... -void enableFlags({bool? bold, bool? hidden}) {...} +void enableFlags({bool? bold, bool? hidden}) { + ... +} ``` When calling a function, @@ -114,7 +116,9 @@ For example: <?code-excerpt "misc/lib/language_tour/functions.dart (named-parameter-default-values)"?> ```dart /// Sets the [bold] and [hidden] flags ... -void enableFlags({bool bold = false, bool hidden = false}) {...} +void enableFlags({bool bold = false, bool hidden = false}) { + ... +} // bold will be true; hidden will be false. enableFlags(bold: true); @@ -185,8 +189,10 @@ And here's an example of calling this function with the third parameter: <?code-excerpt "misc/test/language_tour/functions_test.dart (call-with-optional-param)"?> ```dart -assert(say('Bob', 'Howdy', 'smoke signal') == - 'Bob says Howdy with a smoke signal'); +assert( + say('Bob', 'Howdy', 'smoke signal') == + 'Bob says Howdy with a smoke signal', +); ``` To define a default value for an optional positional parameter besides `null`, @@ -326,9 +332,10 @@ prints each converted string with its length. ```dart const list = ['apples', 'bananas', 'oranges']; -var uppercaseList = list.map((item) { - return item.toUpperCase(); -}).toList(); +var uppercaseList = + list.map((item) { + return item.toUpperCase(); + }).toList(); // Convert to list after mapping for (var item in uppercaseList) { @@ -343,9 +350,10 @@ Click **Run** to execute the code. void main() { const list = ['apples', 'bananas', 'oranges']; - var uppercaseList = list.map((item) { - return item.toUpperCase(); - }).toList(); + var uppercaseList = + list.map((item) { + return item.toUpperCase(); + }).toList(); // Convert to list after mapping for (var item in uppercaseList) { diff --git a/src/content/language/generics.md b/src/content/language/generics.md index dd9945ffd2..0e8c460bcb 100644 --- a/src/content/language/generics.md +++ b/src/content/language/generics.md @@ -95,7 +95,7 @@ var uniqueNames = <String>{'Seth', 'Kathy', 'Lars'}; var pages = <String, String>{ 'index.html': 'Homepage', 'robots.txt': 'Hints for web robots', - 'humans.txt': 'We are people, not machines' + 'humans.txt': 'We are people, not machines', }; ``` @@ -168,7 +168,9 @@ class Foo<T [!extends SomeBaseClass!]> { String toString() => "Instance of 'Foo<$T>'"; } -class Extender extends SomeBaseClass {...} +class Extender extends SomeBaseClass { + ... +} ``` It's OK to use `SomeBaseClass` or any of its subtypes as the generic argument: diff --git a/src/content/language/index.md b/src/content/language/index.md index b81cd120f7..7fbff2e1c0 100644 --- a/src/content/language/index.md +++ b/src/content/language/index.md @@ -53,7 +53,7 @@ var antennaDiameter = 3.7; var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune']; var image = { 'tags': ['saturn'], - 'url': '//path/to/saturn.jpg' + 'url': '//path/to/saturn.jpg', }; ``` @@ -253,8 +253,11 @@ enum Planet { neptune(planetType: PlanetType.ice, moons: 14, hasRings: true); /// A constant generating constructor - const Planet( - {required this.planetType, required this.moons, required this.hasRings}); + const Planet({ + required this.planetType, + required this.moons, + required this.hasRings, + }); /// All instance variables are final final PlanetType planetType; @@ -407,7 +410,8 @@ Future<void> createDescriptions(Iterable<String> objects) async { if (await file.exists()) { var modified = await file.lastModified(); print( - 'File for $object already exists. It was modified on $modified.'); + 'File for $object already exists. It was modified on $modified.', + ); continue; } await file.create(); diff --git a/src/content/language/isolates.md b/src/content/language/isolates.md index 722bd685a4..99c08d0596 100644 --- a/src/content/language/isolates.md +++ b/src/content/language/isolates.md @@ -506,6 +506,7 @@ Future<void> parseJson(String message) async { await _isolateReady.future; _sendPort.send(message); } + } ``` @@ -613,7 +614,7 @@ In the `Worker.spawn` method: the `ReceivePort.fromRawReceivePort` constructor, and pass in the `initPort`. -<?code-excerpt "lib/robust_ports_example/spawn_1.dart (worker-spawn)"?> +<?code-excerpt "lib/robust_ports_example/spawn_1.dart (worker-spawn)" plaster="none"?> ```dart class Worker { final SendPort _commands; @@ -630,8 +631,8 @@ class Worker { commandPort, )); }; -// ··· } +} ``` By creating a `RawReceivePort` first, and then a `ReceivePort`, you’ll be able @@ -662,7 +663,7 @@ the `initPort` will be closed, and the `Worker` object won’t be created. - Finally, return an instance of `Worker` by calling its private constructor, and passing in the ports from that completer. -<?code-excerpt "lib/robust_ports_example/spawn_2.dart (worker-spawn)"?> +<?code-excerpt "lib/robust_ports_example/spawn_2.dart (worker-spawn)" plaster="none"?> ```dart class Worker { final SendPort _commands; @@ -692,6 +693,7 @@ class Worker { return Worker._(receivePort, sendPort); } +} ``` Note that in this example (compared to the [previous example][]), `Worker.spawn` @@ -714,15 +716,16 @@ method. In the constructor body, add a listener to the receive port used by the main isolate, and pass an as-yet undefined method to that listener called `_handleResponsesFromIsolate`. -<?code-excerpt "lib/robust_ports_example/step_4.dart (constructor)"?> +<?code-excerpt "lib/robust_ports_example/step_4.dart (constructor)" plaster="none"?> ```dart class Worker { final SendPort _commands; final ReceivePort _responses; -// ··· + Worker._(this._responses, this._commands) { _responses.listen(_handleResponsesFromIsolate); } +} ``` Next, add the code to `_startRemoteIsolate` that is responsible for initializing @@ -758,7 +761,9 @@ and sending the decoded json back as a response. <?code-excerpt "lib/robust_ports_example/step_4.dart (handle-commands)"?> ```dart static void _handleCommandsToIsolate( - ReceivePort receivePort, SendPort sendPort) { + ReceivePort receivePort, + SendPort sendPort, +) { receivePort.listen((message) { try { final jsonData = jsonDecode(message as String); @@ -823,6 +828,8 @@ class Worker { final ReceivePort _responses; final Map<int, Completer<Object?>> _activeRequests = {}; int _idCounter = 0; + // ··· +} ``` The `_activeRequests` map associates a message sent to the worker isolate @@ -867,7 +874,9 @@ the id and the decoded json back to the main isolate, again using a record. <?code-excerpt "lib/robust_ports_example/step_5_add_completers.dart (handle-commands)"?> ```dart static void _handleCommandsToIsolate( - ReceivePort receivePort, SendPort sendPort) { + ReceivePort receivePort, + SendPort sendPort, +) { receivePort.listen((message) { final (int id, String jsonText) = message as (int, String); // New try { @@ -922,7 +931,7 @@ ports on the main isolate and the worker isolate. ```dart class Worker { bool _closed = false; -// ··· + // ··· void close() { if (!_closed) { _closed = true; @@ -931,6 +940,7 @@ class Worker { print('--- port closed --- '); } } +} ``` - Next, you need to handle the “shutdown” message in the worker isolate. Add the @@ -993,7 +1003,8 @@ void main() async { print(await worker.parseJson('"banana"')); print(await worker.parseJson('[true, false, null, 1, "string"]')); print( - await Future.wait([worker.parseJson('"yes"'), worker.parseJson('"no"')])); + await Future.wait([worker.parseJson('"yes"'), worker.parseJson('"no"')]), + ); worker.close(); } diff --git a/src/content/language/metadata.md b/src/content/language/metadata.md index 6d2d9668de..f4b1a0a9cf 100644 --- a/src/content/language/metadata.md +++ b/src/content/language/metadata.md @@ -32,7 +32,9 @@ class Television { } /// Turns the TV's power on. - void turnOn() {...} + void turnOn() { + ... + } // ··· } ``` diff --git a/src/content/language/methods.md b/src/content/language/methods.md index 6510914ca8..4e42e60241 100644 --- a/src/content/language/methods.md +++ b/src/content/language/methods.md @@ -36,6 +36,7 @@ class Point { var dy = y - other.y; return sqrt(dx * dx + dy * dy); } + } ``` diff --git a/src/content/language/operators.md b/src/content/language/operators.md index b9b6bd87cd..91fe4d566e 100644 --- a/src/content/language/operators.md +++ b/src/content/language/operators.md @@ -75,10 +75,14 @@ way: <?code-excerpt "misc/test/language_tour/operators_test.dart (precedence)"?> ```dart // Parentheses improve readability. -if ((n % i == 0) && (d % i == 0)) ... +if ((n % i == 0) && (d % i == 0)) { + // ... +} // Harder to read, but equivalent. -if (n % i == 0 && d % i == 0) ... +if (n % i == 0 && d % i == 0) { + // ... +} ``` :::warning @@ -419,10 +423,11 @@ Consider the following code: <?code-excerpt "misc/lib/language_tour/cascades.dart (cascade)"?> ```dart -var paint = Paint() - ..color = Colors.black - ..strokeCap = StrokeCap.round - ..strokeWidth = 5.0; +var paint = + Paint() + ..color = Colors.black + ..strokeCap = StrokeCap.round + ..strokeWidth = 5.0; ``` The constructor, `Paint()`, @@ -449,7 +454,8 @@ are attempted on that null object. <?code-excerpt "misc/test/language_tour/browser_test.dart (cascade-operator)"?> ```dart document.querySelector('#confirm') // Get an object. - ?..textContent = 'Confirm' // Use its members. + ?..textContent = + 'Confirm' // Use its members. ..classList.add('important') ..onClick.listen((e) => window.alert('Confirmed!')) ..scrollIntoView(); @@ -470,14 +476,16 @@ You can also nest cascades. For example: <?code-excerpt "misc/lib/language_tour/operators.dart (nested-cascades)"?> ```dart -final addressBook = (AddressBookBuilder() - ..name = 'jenny' - ..email = 'jenny@example.com' - ..phone = (PhoneNumberBuilder() - ..number = '415-555-0100' - ..label = 'home') - .build()) - .build(); +final addressBook = + (AddressBookBuilder() + ..name = 'jenny' + ..email = 'jenny@example.com' + ..phone = + (PhoneNumberBuilder() + ..number = '415-555-0100' + ..label = 'home') + .build()) + .build(); ``` Be careful to construct your cascade on a function that returns diff --git a/src/content/language/pattern-types.md b/src/content/language/pattern-types.md index d5739e2fd1..59b1e9c16a 100644 --- a/src/content/language/pattern-types.md +++ b/src/content/language/pattern-types.md @@ -46,7 +46,7 @@ rest are not evaluated. ```dart var isPrimary = switch (color) { Color.red || Color.yellow || Color.blue => true, - _ => false + _ => false, }; ``` @@ -100,7 +100,7 @@ String asciiCharType(int char) { == space => 'space', > space && < zero => 'punctuation', >= zero && <= nine => 'digit', - _ => '' + _ => '', }; } ``` diff --git a/src/content/language/patterns.md b/src/content/language/patterns.md index 3fc8aed8b7..14caecbe93 100644 --- a/src/content/language/patterns.md +++ b/src/content/language/patterns.md @@ -193,7 +193,7 @@ body in switch expressions or statements: ```dart var isPrimary = switch (color) { Color.red || Color.yellow || Color.blue => true, - _ => false + _ => false, }; ``` @@ -237,10 +237,7 @@ the [`MapEntry`][] objects that a `<Map>.entries` call returns: <?code-excerpt "language/lib/patterns/for_in.dart (for-in-pattern)"?> ```dart -Map<String, int> hist = { - 'a': 23, - 'b': 100, -}; +Map<String, int> hist = {'a': 23, 'b': 100}; for (var MapEntry(key: key, value: count) in hist.entries) { print('$key occurred $count times'); @@ -355,9 +352,9 @@ class Circle implements Shape { } double calculateArea(Shape shape) => switch (shape) { - Square(length: var l) => l * l, - Circle(radius: var r) => math.pi * r * r - }; + Square(length: var l) => l * l, + Circle(radius: var r) => math.pi * r * r, +}; ``` ### Validating incoming JSON @@ -368,7 +365,7 @@ JSON data: <?code-excerpt "language/lib/patterns/json.dart (json-1)"?> ```dart var json = { - 'user': ['Lily', 13] + 'user': ['Lily', 13], }; var {'user': [name, age]} = json; ``` diff --git a/src/content/language/records.md b/src/content/language/records.md index 9cc44ac96e..02e481f104 100644 --- a/src/content/language/records.md +++ b/src/content/language/records.md @@ -185,11 +185,7 @@ To retrieve record values from a return, return (json['name'] as String, json['age'] as int); } -final json = <String, dynamic>{ - 'name': 'Dash', - 'age': 10, - 'color': 'blue', -}; +final json = <String, dynamic>{'name': 'Dash', 'age': 10, 'color': 'blue'}; // Destructures using a record pattern with positional fields: var (name, age) = userInfo(json); diff --git a/src/content/language/type-system.md b/src/content/language/type-system.md index 511499cab7..96d976eb64 100644 --- a/src/content/language/type-system.md +++ b/src/content/language/type-system.md @@ -138,7 +138,9 @@ Consider the getter method in the `Animal` class: <?code-excerpt "lib/animal.dart (Animal)" replace="/Animal get.*/[!$&!]/g"?> ```dart class Animal { - void chase(Animal a) { ... } + void chase(Animal a) { + ... + } [!Animal get parent => ...!] } ``` @@ -151,7 +153,9 @@ you can replace the getter's return type with `HoneyBadger` ```dart tag=passes-sa class HoneyBadger extends Animal { @override - void chase(Animal a) { ... } + void chase(Animal a) { + ... + } @override [!HoneyBadger!] get parent => ... @@ -162,7 +166,9 @@ class HoneyBadger extends Animal { ```dart tag=fails-sa class HoneyBadger extends Animal { @override - void chase(Animal a) { ... } + void chase(Animal a) { + ... + } @override [!Root!] get parent => ... @@ -187,7 +193,9 @@ Consider the `chase(Animal)` method for the `Animal` class: <?code-excerpt "lib/animal.dart (Animal)" replace="/void chase.*/[!$&!]/g"?> ```dart class Animal { - [!void chase(Animal a) { ... }!] + [!void chase(Animal a) {!] + ... + } Animal get parent => ... } ``` @@ -199,7 +207,9 @@ It's OK to override the `chase()` method to take anything (`Object`). ```dart tag=passes-sa class HoneyBadger extends Animal { @override - void chase([!Object!] a) { ... } + void chase([!Object!] a) { + ... + } @override Animal get parent => ... @@ -211,11 +221,15 @@ from `Animal` to `Mouse`, a subclass of `Animal`. <?code-excerpt "lib/incorrect_animal.dart (chase-mouse)" replace="/Mouse/[!$&!]/g"?> ```dart tag=fails-sa -class [!Mouse!] extends Animal { ... } +class [!Mouse!] extends Animal { + ... +} class Cat extends Animal { @override - void chase([!Mouse!] a) { ... } + void chase([!Mouse!] a) { + ... + } } ``` @@ -498,14 +512,20 @@ The following shows how you might use `covariant`: <?code-excerpt "lib/covariant.dart" replace="/covariant/[!$&!]/g"?> ```dart tag=passes-sa class Animal { - void chase(Animal x) { ... } + void chase(Animal x) { + ... + } } -class Mouse extends Animal { ... } +class Mouse extends Animal { + ... +} class Cat extends Animal { @override - void chase([!covariant!] Mouse x) { ... } + void chase([!covariant!] Mouse x) { + ... + } } ``` diff --git a/src/content/libraries/async/async-await.md b/src/content/libraries/async/async-await.md index 18a4837982..32c286a94b 100644 --- a/src/content/libraries/async/async-await.md +++ b/src/content/libraries/async/async-await.md @@ -83,11 +83,8 @@ String createOrderMessage() { } Future<String> fetchUserOrder() => - // Imagine that this function is more complex and slow. - Future.delayed( - const Duration(seconds: 2), - () => 'Large Latte', - ); +// Imagine that this function is more complex and slow. +Future.delayed(const Duration(seconds: 2), () => 'Large Latte'); void main() { print(createOrderMessage()); @@ -291,12 +288,9 @@ String createOrderMessage() { } Future<String> fetchUserOrder() => - // Imagine that this function is - // more complex and slow. - Future.delayed( - const Duration(seconds: 2), - () => 'Large Latte', - ); +// Imagine that this function is +// more complex and slow. +Future.delayed(const Duration(seconds: 2), () => 'Large Latte'); void main() { print('Fetching user order...'); @@ -322,12 +316,9 @@ it operates like synchronous code. } Future<String> fetchUserOrder() => - // Imagine that this function is - // more complex and slow. - Future.delayed( - const Duration(seconds: 2), - () => 'Large Latte', - ); +// Imagine that this function is +// more complex and slow. +Future.delayed(const Duration(seconds: 2), () => 'Large Latte'); [!Future<void>!] main() [!async!] { print('Fetching user order...'); @@ -642,8 +633,9 @@ Future<void> printOrderMessage() async { Future<String> fetchUserOrder() { // Imagine that this function is more complex. var str = Future.delayed( - const Duration(seconds: 4), - () => throw 'Cannot locate user order'); + const Duration(seconds: 4), + () => throw 'Cannot locate user order', + ); return str; } diff --git a/src/content/libraries/async/creating-streams.md b/src/content/libraries/async/creating-streams.md index 04941d369b..1052df190d 100644 --- a/src/content/libraries/async/creating-streams.md +++ b/src/content/libraries/async/creating-streams.md @@ -82,8 +82,10 @@ Here's how it might be implemented: <?code-excerpt "misc/lib/articles/creating-streams/stream_controller.dart (basic-usage)"?> ```dart -var counterStream = - Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15); +var counterStream = Stream<int>.periodic( + const Duration(seconds: 1), + (x) => x, +).take(15); ``` To quickly see the events, you can use code like this: @@ -126,10 +128,11 @@ transformers provided by the dart:convert library. <?code-excerpt "misc/lib/articles/creating-streams/stream_controller.dart (use-transform)"?> ```dart Stream<List<int>> content = File('someFile.txt').openRead(); -List<String> lines = await content - .transform(utf8.decoder) - .transform(const LineSplitter()) - .toList(); +List<String> lines = + await content + .transform(utf8.decoder) + .transform(const LineSplitter()) + .toList(); ``` @@ -394,10 +397,11 @@ Stream<int> timedCounter(Duration interval, [int? maxCount]) { } controller = StreamController<int>( - onListen: startTimer, - onPause: stopTimer, - onResume: startTimer, - onCancel: stopTimer); + onListen: startTimer, + onPause: stopTimer, + onResume: startTimer, + onCancel: stopTimer, + ); return controller.stream; } diff --git a/src/content/libraries/async/futures-error-handling.md b/src/content/libraries/async/futures-error-handling.md index 37ab8f5eb2..e71193936b 100644 --- a/src/content/libraries/async/futures-error-handling.md +++ b/src/content/libraries/async/futures-error-handling.md @@ -60,11 +60,13 @@ callback and demonstrates `catchError()`'s versatility as an error handler: <?code-excerpt "futures/lib/simple.dart (comprehensive-errors)" replace="/ellipsis\(\);/.../g;"?> ```dart -myFunc().then((value) { - doSomethingWith(value); - ... - throw Exception('Some arbitrary error'); -}).catchError(handleError); +myFunc() + .then((value) { + doSomethingWith(value); + ... + throw Exception('Some arbitrary error'); + }) + .catchError(handleError); ``` If `myFunc()`'s Future completes with a value, `then()`'s callback fires. If @@ -95,10 +97,15 @@ between an error forwarded _to_ `then()`, and an error generated _within_ <?code-excerpt "futures/lib/simple.dart (throws-then-catch)"?> ```dart -asyncErrorFunction().then(successCallback, onError: (e) { - handleError(e); // Original error. - anotherAsyncErrorFunction(); // Oops, new error. -}).catchError(handleError); // Error from within then() handled. +asyncErrorFunction() + .then( + successCallback, + onError: (e) { + handleError(e); // Original error. + anotherAsyncErrorFunction(); // Oops, new error. + }, + ) + .catchError(handleError); // Error from within then() handled. ``` In the example above, `asyncErrorFunction()`'s Future's error is handled with the @@ -128,11 +135,12 @@ void main() { .then((_) => four()) // Future completes with two()'s error. .then((value) => value.length) // Future completes with two()'s error. .catchError((e) { - print('Got error: $e'); // Finally, callback fires. - return 42; // Future completes with 42. - }).then((value) { - print('The value is $value'); - }); + print('Got error: $e'); // Finally, callback fires. + return 42; // Future completes with 42. + }) + .then((value) { + print('The value is $value'); + }); } // Output of this program: @@ -172,8 +180,10 @@ void main() { handleAuthResponse(const {'username': 'dash', 'age': 3}) .then((_) => ...) .catchError(handleFormatException, test: (e) => e is FormatException) - .catchError(handleAuthorizationException, - test: (e) => e is AuthorizationException); + .catchError( + handleAuthorizationException, + test: (e) => e is AuthorizationException, + ); } ``` @@ -233,10 +243,11 @@ void main() { // Future completes with an error: .then((_) => ...) .catchError((e) { - handleError(e); - printErrorMessage(); - return someObject; // Future completes with someObject - }).whenComplete(() => print('Done!')); // Future completes with someObject + handleError(e); + printErrorMessage(); + return someObject; // Future completes with someObject + }) + .whenComplete(() => print('Done!')); // Future completes with someObject } ``` diff --git a/src/content/libraries/async/using-streams.md b/src/content/libraries/async/using-streams.md index e89d4c4a36..ab17cd0492 100644 --- a/src/content/libraries/async/using-streams.md +++ b/src/content/libraries/async/using-streams.md @@ -295,8 +295,10 @@ The `distinct()` function doesn't exist on `Iterable`, but it could have. <?code-excerpt "misc/lib/tutorial/stream_interface.dart (special-stream-members)"?> ```dart Stream<T> handleError(Function onError, {bool Function(dynamic error)? test}); -Stream<T> timeout(Duration timeLimit, - {void Function(EventSink<T> sink)? onTimeout}); +Stream<T> timeout( + Duration timeLimit, { + void Function(EventSink<T> sink)? onTimeout, +}); Stream<S> transform<S>(StreamTransformer<T, S> streamTransformer); ``` @@ -363,8 +365,12 @@ method—all other stream functions are defined in terms of `listen()`. <?code-excerpt "misc/lib/tutorial/stream_interface.dart (listen)"?> ```dart -StreamSubscription<T> listen(void Function(T event)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}); +StreamSubscription<T> listen( + void Function(T event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, +}); ``` To create a new `Stream` type, you can just extend the `Stream` diff --git a/src/content/libraries/collections/iterables.md b/src/content/libraries/collections/iterables.md index ce18c8fe42..501b92cdae 100644 --- a/src/content/libraries/collections/iterables.md +++ b/src/content/libraries/collections/iterables.md @@ -729,8 +729,9 @@ it reaches the first negative number. <?code-excerpt "iterables/test/iterables_test.dart (takewhile)"?> ```dart -var numbersUntilNegative = - numbers.takeWhile((number) => !number.isNegative); +var numbersUntilNegative = numbers.takeWhile( + (number) => !number.isNegative, +); ``` Notice that the condition `number.isNegative` is negated with `!`. diff --git a/src/content/libraries/dart-async.md b/src/content/libraries/dart-async.md index 6cf7d6778c..9be1af526b 100644 --- a/src/content/libraries/dart-async.md +++ b/src/content/libraries/dart-async.md @@ -61,9 +61,11 @@ waiting for each one to complete before executing the next one. ```dart void runUsingFuture() { // ... - findEntryPoint().then((entryPoint) { - return runExecutable(entryPoint, args); - }).then(flushThenExit); + findEntryPoint() + .then((entryPoint) { + return runExecutable(entryPoint, args); + }) + .then(flushThenExit); } ``` @@ -123,11 +125,14 @@ object might throw. <?code-excerpt "misc/lib/library_tour/async/basic.dart (catch-error)"?> ```dart -httpClient.read(url).then((String result) { - print(result); -}).catchError((e) { - // Handle or ignore the error. -}); +httpClient + .read(url) + .then((String result) { + print(result); + }) + .catchError((e) { + // Handle or ignore the error. + }); ``` The `then().catchError()` pattern is the asynchronous version of @@ -160,8 +165,8 @@ result .then((_) => lengthyComputation()) .then((_) => print('Done!')) .catchError((exception) { - /* Handle exception... */ -}); + /* Handle exception... */ + }); ``` In the preceding example, the methods run in the following order: @@ -384,8 +389,9 @@ different type of data: <?code-excerpt "misc/lib/library_tour/async/stream.dart (transform)"?> ```dart -var lines = - inputStream.transform(utf8.decoder).transform(const LineSplitter()); +var lines = inputStream + .transform(utf8.decoder) + .transform(const LineSplitter()); ``` This example uses two transformers. First it uses utf8.decoder to @@ -415,8 +421,9 @@ Future<void> readFileAwaitFor() async { var config = File('config.txt'); Stream<List<int>> inputStream = config.openRead(); - var lines = - inputStream.transform(utf8.decoder).transform(const LineSplitter()); + var lines = inputStream + .transform(utf8.decoder) + .transform(const LineSplitter()); [!try!] { await for (final line in lines) { print('Got ${line.length} characters from stream'); @@ -438,14 +445,20 @@ an `onDone` listener. var config = File('config.txt'); Stream<List<int>> inputStream = config.openRead(); -inputStream.transform(utf8.decoder).transform(const LineSplitter()).listen( - (String line) { - print('Got ${line.length} characters from stream'); -}, [!onDone!]: () { - print('file is now closed'); -}, [!onError!]: (e) { - print(e); -}); +inputStream + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen( + (String line) { + print('Got ${line.length} characters from stream'); + }, + [!onDone!]: () { + print('file is now closed'); + }, + [!onError!]: (e) { + print(e); + }, + ); ``` diff --git a/src/content/libraries/dart-convert.md b/src/content/libraries/dart-convert.md index 8862497137..bf9a8d0b62 100644 --- a/src/content/libraries/dart-convert.md +++ b/src/content/libraries/dart-convert.md @@ -59,14 +59,16 @@ Encode a supported Dart object into a JSON-formatted string with var scores = [ {'score': 40}, {'score': 80}, - {'score': 100, 'overtime': true, 'special_guest': null} + {'score': 100, 'overtime': true, 'special_guest': null}, ]; var jsonText = jsonEncode(scores); -assert(jsonText == - '[{"score":40},{"score":80},' - '{"score":100,"overtime":true,' - '"special_guest":null}]'); +assert( + jsonText == + '[{"score":40},{"score":80},' + '{"score":100,"overtime":true,' + '"special_guest":null}]', +); ``` Only objects of type int, double, String, bool, null, List, or Map (with @@ -94,7 +96,7 @@ List<int> utf8Bytes = [ 0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, 0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4, 0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5, - 0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1 + 0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1, ]; var funnyWord = utf8.decode(utf8Bytes); diff --git a/src/content/libraries/dart-core.md b/src/content/libraries/dart-core.md index 099fecfd3c..2a78c9896d 100644 --- a/src/content/libraries/dart-core.md +++ b/src/content/libraries/dart-core.md @@ -481,7 +481,7 @@ traditional constructor: var hawaiianBeaches = { 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'], 'Big Island': ['Wailea Bay', 'Pololu Beach'], - 'Kauai': ['Hanalei', 'Poipu'] + 'Kauai': ['Hanalei', 'Poipu'], }; // Maps can be built from a constructor. @@ -517,7 +517,7 @@ You can retrieve all the values or all the keys from a map: var hawaiianBeaches = { 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'], 'Big Island': ['Wailea Bay', 'Pololu Beach'], - 'Kauai': ['Hanalei', 'Poipu'] + 'Kauai': ['Hanalei', 'Poipu'], }; // Get all the keys as an unordered collection @@ -543,7 +543,7 @@ key and checking for null to determine the existence of a key. var hawaiianBeaches = { 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'], 'Big Island': ['Wailea Bay', 'Pololu Beach'], - 'Kauai': ['Hanalei', 'Poipu'] + 'Kauai': ['Hanalei', 'Poipu'], }; assert(hawaiianBeaches.containsKey('Oahu')); @@ -708,7 +708,8 @@ var uri = 'https://example.org/api?foo=some message'; var encoded = Uri.encodeComponent(uri); assert( - encoded == 'https%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message'); + encoded == 'https%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message', +); var decoded = Uri.decodeComponent(encoded); assert(uri == decoded); @@ -744,11 +745,12 @@ constructor: <?code-excerpt "misc/test/library_tour/core_test.dart (uri)"?> ```dart var uri = Uri( - scheme: 'https', - host: 'example.org', - path: '/foo/bar', - fragment: 'frag', - queryParameters: {'lang': 'dart'}); + scheme: 'https', + host: 'example.org', + path: '/foo/bar', + fragment: 'frag', + queryParameters: {'lang': 'dart'}, +); assert(uri.toString() == 'https://example.org/foo/bar?lang=dart#frag'); ``` diff --git a/src/content/libraries/dart-html.md b/src/content/libraries/dart-html.md index 552482c188..5a44024384 100644 --- a/src/content/libraries/dart-html.md +++ b/src/content/libraries/dart-html.md @@ -88,9 +88,7 @@ Element classElement = querySelector('.a-class')!; List<Element> divElements = querySelectorAll('div'); // Find all text inputs. -List<Element> textInputElements = querySelectorAll( - 'input[type="text"]', -); +List<Element> textInputElements = querySelectorAll('input[type="text"]'); // Find all elements with the CSS class 'class' // inside of a <p> that is inside an element with @@ -190,9 +188,7 @@ are also parsed and created. <?code-excerpt "html/lib/html.dart (creating-from-html)"?> ```dart -var elem2 = Element.html( - '<p>Creating <em>is</em> easy!</p>', -); +var elem2 = Element.html('<p>Creating <em>is</em> easy!</p>'); ``` Note that `elem2` is a `ParagraphElement` in the preceding example. @@ -269,9 +265,10 @@ cascades: <?code-excerpt "html/lib/html.dart (elem-set-cascade)"?> ```dart -var message = DivElement() - ..id = 'message2' - ..text = 'Please subscribe to the Dart mailing list.'; +var message = + DivElement() + ..id = 'message2' + ..text = 'Please subscribe to the Dart mailing list.'; ``` While using IDs and classes to associate an element with a set of styles @@ -409,8 +406,10 @@ void initWebSocket([int retrySeconds = 1]) { void scheduleReconnect() { if (!reconnectScheduled) { - Timer(Duration(seconds: retrySeconds), - () => initWebSocket(retrySeconds * 2)); + Timer( + Duration(seconds: retrySeconds), + () => initWebSocket(retrySeconds * 2), + ); } reconnectScheduled = true; } diff --git a/src/content/libraries/dart-io.md b/src/content/libraries/dart-io.md index c1251e50f8..8954446ba2 100644 --- a/src/content/libraries/dart-io.md +++ b/src/content/libraries/dart-io.md @@ -231,10 +231,7 @@ void processRequest(HttpRequest request) { final response = request.response; if (request.uri.path == '/dart') { response - ..headers.contentType = ContentType( - 'text', - 'plain', - ) + ..headers.contentType = ContentType('text', 'plain') ..write('Hello from the server'); } else { response.statusCode = HttpStatus.notFound; diff --git a/src/content/resources/dart-cheatsheet.md b/src/content/resources/dart-cheatsheet.md index 5ab989b54d..bb8b722978 100644 --- a/src/content/resources/dart-cheatsheet.md +++ b/src/content/resources/dart-cheatsheet.md @@ -335,11 +335,7 @@ You can create them using literals: ```dart final aListOfStrings = ['one', 'two', 'three']; final aSetOfStrings = {'one', 'two', 'three'}; -final aMapOfStringsToInts = { - 'one': 1, - 'two': 2, - 'three': 3, -}; +final aMapOfStringsToInts = {'one': 1, 'two': 2, 'three': 3}; ``` Dart's type inference can assign types to these variables for you. @@ -1521,9 +1517,7 @@ which goes between the constructor's signature and its body: <?code-excerpt "misc/lib/language_tour/classes/point_alt.dart (initializer-list-no-comment)"?> ```dart -Point.fromJson(Map<String, double> json) - : x = json['x']!, - y = json['y']! { +Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']! { print('In Point.fromJson(): ($x, $y)'); } ``` @@ -1533,9 +1527,7 @@ which run only during development: <?code-excerpt "misc/lib/cheatsheet/initializer_lists.dart (assert)"?> ```dart -NonNegativePoint(this.x, this.y) - : assert(x >= 0), - assert(y >= 0) { +NonNegativePoint(this.x, this.y) : assert(x >= 0), assert(y >= 0) { print('I just made a NonNegativePoint: ($x, $y)'); } ``` @@ -1645,9 +1637,7 @@ class Point { Point(this.x, this.y); - Point.origin() - : x = 0, - y = 0; + Point.origin() : x = 0, y = 0; } ``` diff --git a/src/content/tools/non-promotion-reasons.md b/src/content/tools/non-promotion-reasons.md index 235c357dd7..8464104cda 100644 --- a/src/content/tools/non-promotion-reasons.md +++ b/src/content/tools/non-promotion-reasons.md @@ -933,8 +933,8 @@ the variable's current promoted type ```dart tag=bad void f(Object o) { - if (o is Comparable /* (1) */) { - if (o is Pattern /* (2) */) { + if (o is Comparable /* (1) */ ) { + if (o is Pattern /* (2) */ ) { print(o.matchAsPrefix('foo')); // (3) ERROR } } @@ -960,11 +960,12 @@ the new variable is promoted to `Pattern`: <?code-excerpt "non_promotion/lib/non_promotion.dart (subtype-variable)" replace="/Object o2.*/[!$&!]/g;/(o2)(\.| is)/[!$1!]$2/g"?> ```dart void f(Object o) { - if (o is Comparable /* (1) */) { + if (o is Comparable /* (1) */ ) { [!Object o2 = o;!] - if ([!o2!] is Pattern /* (2) */) { + if ([!o2!] is Pattern /* (2) */ ) { print( - [!o2!].matchAsPrefix('foo')); // (3) OK; o2 was promoted to `Pattern`. + [!o2!].matchAsPrefix('foo'), + ); // (3) OK; o2 was promoted to `Pattern`. } } } @@ -980,8 +981,8 @@ A redundant type check might be a better solution: <?code-excerpt "non_promotion/lib/non_promotion.dart (subtype-redundant)" replace="/\(o as Pattern\)/[!$&!]/g"?> ```dart tag=good void f(Object o) { - if (o is Comparable /* (1) */) { - if (o is Pattern /* (2) */) { + if (o is Comparable /* (1) */ ) { + if (o is Pattern /* (2) */ ) { print([!(o as Pattern)!].matchAsPrefix('foo')); // (3) OK } } @@ -996,8 +997,8 @@ Because `String` is a subtype of `Comparable`, the promotion works: <?code-excerpt "non_promotion/lib/non_promotion.dart (subtype-string)" replace="/is String/is [!String!]/g"?> ```dart tag=good void f(Object o) { - if (o is Comparable /* (1) */) { - if (o is [!String!] /* (2) */) { + if (o is Comparable /* (1) */ ) { + if (o is [!String!] /* (2) */ ) { print(o.matchAsPrefix('foo')); // (3) OK } } diff --git a/src/content/tutorials/server/cmdline.md b/src/content/tutorials/server/cmdline.md index ee6406a01e..b0e32fa977 100644 --- a/src/content/tutorials/server/cmdline.md +++ b/src/content/tutorials/server/cmdline.md @@ -190,7 +190,7 @@ $ dart run bin/dcat.dart -n pubspec.yaml 4 # repository: https://github.com/my_org/my_repo 5 6 environment: -7 sdk: ^3.6.1 +7 sdk: ^3.7.0 8 9 # Add regular dependencies here. 10 dependencies: diff --git a/src/content/tutorials/server/fetch-data.md b/src/content/tutorials/server/fetch-data.md index a2f5ac2ac0..a2c6d31e7c 100644 --- a/src/content/tutorials/server/fetch-data.md +++ b/src/content/tutorials/server/fetch-data.md @@ -293,8 +293,10 @@ of the key-value pairs as the `headers` optional named parameter: <?code-excerpt "lib/fetch_data.dart (http-headers)"?> ```dart -await http.get(Uri.https('dart.dev', '/f/packages/http.json'), - headers: {'User-Agent': '<product name>/<product-version>'}); +await http.get( + Uri.https('dart.dev', '/f/packages/http.json'), + headers: {'User-Agent': '<product name>/<product-version>'}, +); ``` [http-read]: {{site.pub-api}}/http/latest/http/read.html @@ -623,6 +625,7 @@ class PackageRetrievalException implements Exception { buf.write('!'); return buf.toString(); } + } ``` diff --git a/tool/dart_site/bin/dart_site.dart b/tool/dart_site/bin/dart_site.dart index d066590a74..4b96a3f49f 100644 --- a/tool/dart_site/bin/dart_site.dart +++ b/tool/dart_site/bin/dart_site.dart @@ -12,15 +12,14 @@ import 'package:path/path.dart' as path; void main(List<String> args) async { // Verify that we are running from the root of the website repository. if (!Directory(path.join('tool', 'dart_site')).existsSync()) { - throw Exception( - 'Error: Wrong directory, run from root of the repository.', - ); + throw Exception('Error: Wrong directory, run from root of the repository.'); } final runner = DartSiteCommandRunner(); try { - final result = - await runner.run(args).whenComplete(io.sharedStdIn.terminate); + final result = await runner + .run(args) + .whenComplete(io.sharedStdIn.terminate); exit(result is int ? result : 0); } on UsageException catch (e) { diff --git a/tool/dart_site/lib/dart_site.dart b/tool/dart_site/lib/dart_site.dart index e6d8c1545d..822c997b6b 100644 --- a/tool/dart_site/lib/dart_site.dart +++ b/tool/dart_site/lib/dart_site.dart @@ -24,10 +24,10 @@ import 'src/commands/verify_firebase_json.dart'; /// run `dart run dart_site --help`. final class DartSiteCommandRunner extends CommandRunner<int> { DartSiteCommandRunner() - : super( - 'dart_site', - 'Infrastructure tooling for the Dart documentation website.', - ) { + : super( + 'dart_site', + 'Infrastructure tooling for the Dart documentation website.', + ) { addCommand(CheckLinksCommand()); addCommand(CheckLinkReferencesCommand()); addCommand(CheckSiteVariableCommand()); diff --git a/tool/dart_site/lib/src/commands/analyze_dart.dart b/tool/dart_site/lib/src/commands/analyze_dart.dart index ccaf178944..581b5dc3c1 100644 --- a/tool/dart_site/lib/src/commands/analyze_dart.dart +++ b/tool/dart_site/lib/src/commands/analyze_dart.dart @@ -26,22 +26,18 @@ final class AnalyzeDartCommand extends Command<int> { String get name => 'analyze-dart'; @override - Future<int> run() async => analyzeDart( - verboseLogging: argResults.get<bool>(_verboseFlag, false), - ); + Future<int> run() async => + analyzeDart(verboseLogging: argResults.get<bool>(_verboseFlag, false)); } -int analyzeDart({ - bool verboseLogging = false, -}) { +int analyzeDart({bool verboseLogging = false}) { if (!verboseLogging) { print('Analyzing code...'); } - final dartAnalyzeOutput = Process.runSync( - Platform.executable, - const ['analyze'], - ); + final dartAnalyzeOutput = Process.runSync(Platform.executable, const [ + 'analyze', + ]); if (dartAnalyzeOutput.exitCode != 0) { final normalOutput = dartAnalyzeOutput.stdout.toString(); diff --git a/tool/dart_site/lib/src/commands/build.dart b/tool/dart_site/lib/src/commands/build.dart index ff58e56bc2..546b0681cc 100644 --- a/tool/dart_site/lib/src/commands/build.dart +++ b/tool/dart_site/lib/src/commands/build.dart @@ -32,9 +32,7 @@ final class BuildSiteCommand extends Command<int> { 'node_modules/@11ty/eleventy/cmd.cjs', '--config=eleventy.config.ts', ], - environment: { - 'PRODUCTION': '$productionRelease', - }, + environment: {'PRODUCTION': '$productionRelease'}, ); await stdout.addStream(process.stdout); diff --git a/tool/dart_site/lib/src/commands/check_all.dart b/tool/dart_site/lib/src/commands/check_all.dart index cd2b5ef41c..e74d6b2e1a 100644 --- a/tool/dart_site/lib/src/commands/check_all.dart +++ b/tool/dart_site/lib/src/commands/check_all.dart @@ -30,10 +30,11 @@ final class CheckAllCommand extends Command<int> { for (final task in verificationTasks) { groupStart(task.first); - final process = await Process.start( - Platform.executable, - ['run', 'dart_site', ...task], - ); + final process = await Process.start(Platform.executable, [ + 'run', + 'dart_site', + ...task, + ]); await stdout.addStream(process.stdout); await stderr.addStream(process.stderr); final processExitCode = await process.exitCode; diff --git a/tool/dart_site/lib/src/commands/check_link_references.dart b/tool/dart_site/lib/src/commands/check_link_references.dart index 3d603fd140..257871f223 100644 --- a/tool/dart_site/lib/src/commands/check_link_references.dart +++ b/tool/dart_site/lib/src/commands/check_link_references.dart @@ -9,7 +9,8 @@ import 'package:path/path.dart' as path; final class CheckLinkReferencesCommand extends Command<int> { @override - String get description => 'Verify there are no unlinked/broken ' + String get description => + 'Verify there are no unlinked/broken ' 'Markdown link references in the generated site output.'; @override diff --git a/tool/dart_site/lib/src/commands/check_links.dart b/tool/dart_site/lib/src/commands/check_links.dart index d53c43cba5..a1acf23143 100644 --- a/tool/dart_site/lib/src/commands/check_links.dart +++ b/tool/dart_site/lib/src/commands/check_links.dart @@ -30,9 +30,8 @@ final class CheckLinksCommand extends Command<int> { String get name => 'check-links'; @override - Future<int> run() async => _checkLinks( - checkExternal: argResults.get<bool>(_externalFlag, false), - ); + Future<int> run() async => + _checkLinks(checkExternal: argResults.get<bool>(_externalFlag, false)); } /// The port that the firebase emulator runs on by default. @@ -81,15 +80,12 @@ Future<int> _checkLinks({bool checkExternal = false}) async { } try { - final result = await linkcheck.run( - [ - ':$_emulatorPort', - '--skip-file', - _skipFilePath, - if (checkExternal) 'external' - ], - stdout, - ); + final result = await linkcheck.run([ + ':$_emulatorPort', + '--skip-file', + _skipFilePath, + if (checkExternal) 'external', + ], stdout); return result; } catch (e, stackTrace) { stderr.writeln('Error: linkcheck failed to execute properly!'); diff --git a/tool/dart_site/lib/src/commands/format_dart.dart b/tool/dart_site/lib/src/commands/format_dart.dart index f3563462a4..9aa99c237a 100644 --- a/tool/dart_site/lib/src/commands/format_dart.dart +++ b/tool/dart_site/lib/src/commands/format_dart.dart @@ -21,16 +21,16 @@ final class FormatDartCommand extends Command<int> { } @override - String get description => 'Format or check formatting of the site ' + String get description => + 'Format or check formatting of the site ' 'examples and tools.'; @override String get name => 'format-dart'; @override - Future<int> run() async => formatDart( - justCheck: argResults.get<bool>(_checkFlag, false), - ); + Future<int> run() async => + formatDart(justCheck: argResults.get<bool>(_checkFlag, false)); } int formatDart({bool justCheck = false}) { diff --git a/tool/dart_site/lib/src/commands/freshness.dart b/tool/dart_site/lib/src/commands/freshness.dart index 45506f3a43..81e44935c1 100644 --- a/tool/dart_site/lib/src/commands/freshness.dart +++ b/tool/dart_site/lib/src/commands/freshness.dart @@ -23,7 +23,8 @@ final class FreshnessCommand extends Command<int> { ); argParser.addOption( _cutoffDaysOption, - help: 'The cut off amount of days since lastVerified date ' + help: + 'The cut off amount of days since lastVerified date ' 'to consider inclusion in output.', ); } @@ -36,22 +37,16 @@ final class FreshnessCommand extends Command<int> { @override Future<int> run() async => determineFreshness( - includeMissing: argResults.get<bool>(_includeMissingFlag, true), - cutOffDays: int.tryParse(argResults.get<String>(_cutoffDaysOption, '')), - ); + includeMissing: argResults.get<bool>(_includeMissingFlag, true), + cutOffDays: int.tryParse(argResults.get<String>(_cutoffDaysOption, '')), + ); } int determineFreshness({bool includeMissing = true, int? cutOffDays}) { // Directories to check for content. - final directoryPathsToCheck = [ - path.join('src', 'content'), - ]; + final directoryPathsToCheck = [path.join('src', 'content')]; - const extensionsToConsider = { - '.md', - '.html', - '.liquid', - }; + const extensionsToConsider = {'.md', '.html', '.liquid'}; final currentDate = DateTime.now(); final results = FreshnessResults._(); @@ -62,9 +57,11 @@ int determineFreshness({bool includeMissing = true, int? cutOffDays}) { .listSync(recursive: true) .whereType<File>() .where( - (file) => extensionsToConsider.contains(path.extension(file.path))) + (file) => extensionsToConsider.contains(path.extension(file.path)), + ) .where( - (file) => !path.basenameWithoutExtension(file.path).startsWith('_')) + (file) => !path.basenameWithoutExtension(file.path).startsWith('_'), + ) .where((file) => path.basenameWithoutExtension(file.path).isNotEmpty) .toList(growable: false); @@ -88,12 +85,16 @@ int determineFreshness({bool includeMissing = true, int? cutOffDays}) { results._addStale(filePath, lastVerified: lastVerified); } } else { - results._addMisformatted(filePath, - misformattedDate: lastVerifiedString); + results._addMisformatted( + filePath, + misformattedDate: lastVerifiedString, + ); } } else { - results._addMisformatted(filePath, - misformattedDate: '$lastVerifiedRaw'); + results._addMisformatted( + filePath, + misformattedDate: '$lastVerifiedRaw', + ); } } else { results._addMissingVerified(filePath); @@ -116,7 +117,7 @@ int determineFreshness({bool includeMissing = true, int? cutOffDays}) { final List<({int days, String icon})> _cutoffDays = [ (days: 270, icon: '🟨'), (days: 540, icon: '🟧'), - (days: 810, icon: '🟥') + (days: 810, icon: '🟥'), ]; final DateFormat _dateFormat = DateFormat('y-MM-dd'); @@ -139,8 +140,9 @@ final class FreshnessResults { } void _addMisformatted(String path, {required String misformattedDate}) { - _misformattedDateFiles - .add(MisformattedDateFile(path, misformattedDate: misformattedDate)); + _misformattedDateFiles.add( + MisformattedDateFile(path, misformattedDate: misformattedDate), + ); } void _addError(String path, {required String error}) { @@ -207,7 +209,8 @@ final class FreshnessResults { if (_misformattedDateFiles.isNotEmpty) { _misformattedDateFiles.sortByPath(); buffer.writeln( - '\n====== Files with misformatted lastVerified dates ======\n'); + '\n====== Files with misformatted lastVerified dates ======\n', + ); for (final misformattedFile in _misformattedDateFiles) { buffer.write('❗ '); buffer.write(misformattedFile.misformattedDate); diff --git a/tool/dart_site/lib/src/commands/generate_effective_dart_toc.dart b/tool/dart_site/lib/src/commands/generate_effective_dart_toc.dart index 2505aaf884..dadc8d3d9f 100644 --- a/tool/dart_site/lib/src/commands/generate_effective_dart_toc.dart +++ b/tool/dart_site/lib/src/commands/generate_effective_dart_toc.dart @@ -26,24 +26,25 @@ final class GenerateEffectiveDartToc extends Command<int> { } @override - String get description => 'Generate or check up-to-date status of the ' + String get description => + 'Generate or check up-to-date status of the ' 'Effective Dart table of contents.'; @override String get name => 'effective-dart'; @override - Future<int> run() async => await _generateToc( - justCheck: argResults.get<bool>(_checkFlag, false), - ); + Future<int> run() async => + await _generateToc(justCheck: argResults.get<bool>(_checkFlag, false)); } Future<int> _generateToc({bool justCheck = false}) async { const dirPath = 'src/content/effective-dart'; const filenames = ['style.md', 'documentation.md', 'usage.md', 'design.md']; - final sections = - filenames.map((name) => _Section(dirPath, name)).toList(growable: false); + final sections = filenames + .map((name) => _Section(dirPath, name)) + .toList(growable: false); for (final section in sections) { // Read the lines, but skip the YAML front matter, @@ -178,10 +179,11 @@ class _Section { final List<_Subsection> subsections = []; _Section(String dirPath, String filename) - : file = File(path.join(dirPath, filename)), - uri = Uri.parse('/effective-dart/').resolve(filename.split('.').first), - name = '${filename[0].toUpperCase()}' - "${filename.substring(1).split('.').first}"; + : file = File(path.join(dirPath, filename)), + uri = Uri.parse('/effective-dart/').resolve(filename.split('.').first), + name = + '${filename[0].toUpperCase()}' + "${filename.substring(1).split('.').first}"; } class _Subsection { @@ -190,8 +192,8 @@ class _Subsection { final List<_Rule> rules = []; _Subsection(md.Element element) - : name = _concatenatedText(element), - fragment = _generateAnchorHash(_concatenatedText(element)); + : name = _concatenatedText(element), + fragment = _generateAnchorHash(_concatenatedText(element)); } /// Generates a valid HTML anchor from [text]. @@ -212,10 +214,13 @@ String _concatenatedText(md.Element element) { } return children - .map((child) => (child is md.Text) - ? _unescape.convert(child.text) - : (child is md.Element) - ? _concatenatedText(child) - : _unescape.convert(child.textContent)) + .map( + (child) => + (child is md.Text) + ? _unescape.convert(child.text) + : (child is md.Element) + ? _concatenatedText(child) + : _unescape.convert(child.textContent), + ) .join(''); } diff --git a/tool/dart_site/lib/src/commands/refresh_excerpts.dart b/tool/dart_site/lib/src/commands/refresh_excerpts.dart index 7666864254..758f8d24e8 100644 --- a/tool/dart_site/lib/src/commands/refresh_excerpts.dart +++ b/tool/dart_site/lib/src/commands/refresh_excerpts.dart @@ -41,10 +41,10 @@ final class RefreshExcerptsCommand extends Command<int> { @override Future<int> run() async => _refreshExcerpts( - verboseLogging: argResults.get<bool>(_verboseFlag, false), - dryRun: argResults.get<bool>(_dryRunFlag, false), - failOnUpdate: argResults.get<bool>(_failOnUpdateFlag, false), - ); + verboseLogging: argResults.get<bool>(_verboseFlag, false), + dryRun: argResults.get<bool>(_dryRunFlag, false), + failOnUpdate: argResults.get<bool>(_failOnUpdateFlag, false), + ); } Future<int> _refreshExcerpts({ @@ -60,18 +60,11 @@ Future<int> _refreshExcerpts({ validTargetExtensions: const {'.md'}, defaultTransforms: [ SimpleReplaceTransform('//!<br>', ''), - SimpleReplaceTransform( - RegExp(r'ellipsis(<\w+>)?(\(\))?;?'), - '...', - ), - BackReferenceReplaceTransform( - RegExp(r'/\*(\s*\.\.\.\s*)\*/'), - '\$1', - ), - BackReferenceReplaceTransform( - RegExp(r'\{/\*-(\s*\.\.\.\s*)-\*/\}'), - '\$1', - ), + SimpleReplaceTransform(RegExp(r'ellipsis(<\w+>)?(\(\))?;?'), '...'), + BackReferenceReplaceTransform(RegExp(r'/\*(\s*\.\.\.\s*)\*/'), '\$1'), + // Workaround for https://github.com/dart-lang/dart_style/issues/1644 + // to remove extra new lines after block close. + SimpleReplaceTransform(RegExp(r'[\r\n]+$'), ''), ], ); diff --git a/tool/dart_site/lib/src/commands/serve.dart b/tool/dart_site/lib/src/commands/serve.dart index 3713dbe951..25814ca6d3 100644 --- a/tool/dart_site/lib/src/commands/serve.dart +++ b/tool/dart_site/lib/src/commands/serve.dart @@ -19,11 +19,9 @@ final class ServeSiteCommand extends Command<int> { '--config=eleventy.config.ts', '--serve', '--incremental', - '--port=${Platform.environment['PORT'] ?? 4000}' + '--port=${Platform.environment['PORT'] ?? 4000}', ], - environment: const { - 'PRODUCTION': 'false', - }, + environment: const {'PRODUCTION': 'false'}, runInShell: true, mode: ProcessStartMode.inheritStdio, ); diff --git a/tool/dart_site/lib/src/commands/test_dart.dart b/tool/dart_site/lib/src/commands/test_dart.dart index 9da973424f..afdc360433 100644 --- a/tool/dart_site/lib/src/commands/test_dart.dart +++ b/tool/dart_site/lib/src/commands/test_dart.dart @@ -27,14 +27,11 @@ final class TestDartCommand extends Command<int> { String get name => 'test-dart'; @override - Future<int> run() async => _testDart( - verboseLogging: argResults.get<bool>(_verboseFlag, false), - ); + Future<int> run() async => + _testDart(verboseLogging: argResults.get<bool>(_verboseFlag, false)); } -int _testDart({ - bool verboseLogging = false, -}) { +int _testDart({bool verboseLogging = false}) { final directoriesToTest = [ path.join('tool', 'dart_site'), ...dartProjectExampleDirectories, @@ -52,15 +49,11 @@ int _testDart({ return pubGetResult; } - final dartTestOutput = Process.runSync( - Platform.executable, - const [ - 'test', - '--reporter', - 'expanded', // Non-animated expanded output looks better in CI and logs. - ], - workingDirectory: directory, - ); + final dartTestOutput = Process.runSync(Platform.executable, const [ + 'test', + '--reporter', + 'expanded', // Non-animated expanded output looks better in CI and logs. + ], workingDirectory: directory); if (dartTestOutput.exitCode != 0) { final normalOutput = dartTestOutput.stdout.toString(); diff --git a/tool/dart_site/lib/src/commands/verify_firebase_json.dart b/tool/dart_site/lib/src/commands/verify_firebase_json.dart index c799496534..fe499db38a 100644 --- a/tool/dart_site/lib/src/commands/verify_firebase_json.dart +++ b/tool/dart_site/lib/src/commands/verify_firebase_json.dart @@ -9,7 +9,8 @@ import 'package:args/command_runner.dart'; final class VerifyFirebaseJsonCommand extends Command<int> { @override - String get description => 'Verify the firebase.json file is valid and ' + String get description => + 'Verify the firebase.json file is valid and ' 'meets the site standards.'; @override @@ -102,9 +103,7 @@ int _verifyFirebaseJson() { } if (sources.contains(source)) { - stderr.writeln( - "Error: Multiple redirects share the '$source' source.", - ); + stderr.writeln("Error: Multiple redirects share the '$source' source."); duplicatesFound += 1; } diff --git a/tool/dart_site/lib/src/diagnostics/diagnostics.dart b/tool/dart_site/lib/src/diagnostics/diagnostics.dart index 849459b63b..c5b3878fa8 100644 --- a/tool/dart_site/lib/src/diagnostics/diagnostics.dart +++ b/tool/dart_site/lib/src/diagnostics/diagnostics.dart @@ -23,7 +23,12 @@ Future<void> generate() async { /// Compute the path to the file into which documentation is being generated. String get _outputPath => path.join( - repositoryRoot, 'src', 'content', 'tools', 'diagnostic-messages.md'); + repositoryRoot, + 'src', + 'content', + 'tools', + 'diagnostic-messages.md', +); /// An information holder containing information about a diagnostic that was /// extracted from the instance creation expression. @@ -67,8 +72,10 @@ class DiagnosticInformation { for (final previousName in previousNames) { sink.writeln(); final previousInLowerCase = previousName.toLowerCase(); - sink.writeln('<a id="$previousInLowerCase" aria-hidden="true"></a>' - '_(Previously known as `$previousInLowerCase`)_'); + sink.writeln( + '<a id="$previousInLowerCase" aria-hidden="true"></a>' + '_(Previously known as `$previousInLowerCase`)_', + ); } for (final message in messages) { sink.writeln(); @@ -118,8 +125,10 @@ class DocumentationGenerator { _extractAllDocs(classEntry.key, classEntry.value); } - _extractAllDocs('ParserErrorCode', - messages.cfeToAnalyzerErrorCodeTables.analyzerCodeToInfo); + _extractAllDocs( + 'ParserErrorCode', + messages.cfeToAnalyzerErrorCodeTables.analyzerCodeToInfo, + ); } /// Writes the documentation to [sink]. @@ -141,8 +150,9 @@ class DocumentationGenerator { final name = errorCodeInfo.sharedName ?? errorName; var info = infoByName[name]; final message = convertTemplate( - errorCodeInfo.computePlaceholderToIndexMap(), - errorCodeInfo.problemMessage); + errorCodeInfo.computePlaceholderToIndexMap(), + errorCodeInfo.problemMessage, + ); if (info == null) { info = DiagnosticInformation(name, message); infoByName[name] = info; @@ -157,7 +167,8 @@ class DocumentationGenerator { if (docs.isNotEmpty) { if (info.documentation != null) { throw StateError( - 'Documentation defined multiple times for ${info.name}'); + 'Documentation defined multiple times for ${info.name}', + ); } info.documentation = docs; } @@ -166,14 +177,16 @@ class DocumentationGenerator { /// Extract documentation from the given [errorCodeInfo]. String _extractDoc(String errorCode, ErrorCodeInfo errorCodeInfo) { - final parsedComment = - parseErrorCodeDocumentation(errorCode, errorCodeInfo.documentation); + final parsedComment = parseErrorCodeDocumentation( + errorCode, + errorCodeInfo.documentation, + ); if (parsedComment == null) { return ''; } return [ for (final documentationPart in parsedComment) - documentationPart.formatForDocumentation() + documentationPart.formatForDocumentation(), ].join('\n'); } diff --git a/tool/dart_site/lib/src/diagnostics/error_code_documentation_info.dart b/tool/dart_site/lib/src/diagnostics/error_code_documentation_info.dart index dfe1937ae4..057b1bec8e 100644 --- a/tool/dart_site/lib/src/diagnostics/error_code_documentation_info.dart +++ b/tool/dart_site/lib/src/diagnostics/error_code_documentation_info.dart @@ -9,7 +9,9 @@ import 'dart:convert'; /// user-publishable documentation about the given [errorCode], along with code /// blocks illustrating when the error occurs and how to fix it. List<ErrorCodeDocumentationPart>? parseErrorCodeDocumentation( - String errorCode, String? documentation) { + String errorCode, + String? documentation, +) { if (documentation == null) { return null; } @@ -53,11 +55,13 @@ class ErrorCodeDocumentationBlock extends ErrorCodeDocumentationPart { /// the file. final String? uri; - ErrorCodeDocumentationBlock(this.text, - {required this.containingSection, - required this.fileType, - this.languageVersion, - this.uri}); + ErrorCodeDocumentationBlock( + this.text, { + required this.containingSection, + required this.fileType, + this.languageVersion, + this.uri, + }); @override String formatForDocumentation() { @@ -91,7 +95,8 @@ String _migrateHighlightingSpans(String input) { if (trimmedLine.isNotEmpty) { final leadingSpaceCount = line.length - trimmedLine.length; resultLines.add( - '${' ' * leadingSpaceCount}$openingMark$trimmedLine$closingMark'); + '${' ' * leadingSpaceCount}$openingMark$trimmedLine$closingMark', + ); } else { resultLines.add(line); } @@ -109,10 +114,12 @@ String _migrateHighlightingSpans(String input) { final leadingSpaceCount = trimmedLine.isNotEmpty ? line.length - trimmedLine.length : 0; - resultLines.add('${' ' * leadingSpaceCount}$openingMark' - '${line.substring(leadingSpaceCount, closeIndex)}' - '$closingMark' - '${line.substring(closeIndex + closingMark.length)}'); + resultLines.add( + '${' ' * leadingSpaceCount}$openingMark' + '${line.substring(leadingSpaceCount, closeIndex)}' + '$closingMark' + '${line.substring(closeIndex + closingMark.length)}', + ); isOpen = false; continue; } @@ -121,8 +128,10 @@ String _migrateHighlightingSpans(String input) { if (isOpen) { throw StateError('Overlapping span at line $lineNumber: $line'); } - resultLines.add('${line.substring(0, openIndex)}$openingMark' - '${line.substring(openIndex + openingMark.length)}$closingMark'); + resultLines.add( + '${line.substring(0, openIndex)}$openingMark' + '${line.substring(openIndex + openingMark.length)}$closingMark', + ); isOpen = true; continue; } @@ -131,8 +140,10 @@ String _migrateHighlightingSpans(String input) { if (openIndex < closeIndex) { throw StateError('Overlapping span at line $lineNumber: $line'); } - resultLines.add('$openingMark${line.substring(0, closeIndex)}$closingMark' - '${line.substring(closeIndex + closingMark.length)}'); + resultLines.add( + '$openingMark${line.substring(0, closeIndex)}$closingMark' + '${line.substring(closeIndex + closingMark.length)}', + ); isOpen = false; } else { if (closeIndex < openIndex) { @@ -238,8 +249,10 @@ class _ErrorCodeDocumentationParser { } Never problem(String explanation) { - throw FormatException('In documentation for $errorCode, ' - 'at line ${currentLineNumber + 1}, $explanation'); + throw FormatException( + 'In documentation for $errorCode, ' + 'at line ${currentLineNumber + 1}, $explanation', + ); } void processCodeBlock() { @@ -263,11 +276,15 @@ class _ErrorCodeDocumentationParser { ++currentLineNumber; if (containingSection != null) { // Ignore code blocks where they're allowed but aren't checked. - result.add(ErrorCodeDocumentationBlock(codeLines.join('\n'), + result.add( + ErrorCodeDocumentationBlock( + codeLines.join('\n'), containingSection: containingSection, fileType: fileType, languageVersion: languageVersion, - uri: uri)); + uri: uri, + ), + ); } return; } else if (line.startsWith('%')) { diff --git a/tool/dart_site/lib/src/diagnostics/error_code_info.dart b/tool/dart_site/lib/src/diagnostics/error_code_info.dart index cc564d79fe..c4e1228710 100644 --- a/tool/dart_site/lib/src/diagnostics/error_code_info.dart +++ b/tool/dart_site/lib/src/diagnostics/error_code_info.dart @@ -39,27 +39,32 @@ final class Messages { analyzerMessages: analyzerMessages, linterMessages: linterMessages, frontEndMessages: frontEndMessages, - cfeToAnalyzerErrorCodeTables: - CfeToAnalyzerErrorCodeTables._(frontEndMessages), + cfeToAnalyzerErrorCodeTables: CfeToAnalyzerErrorCodeTables._( + frontEndMessages, + ), ); } } /// Pattern used by the front end to identify placeholders in error message /// strings. -final RegExp _placeholderPattern = - RegExp('#([-a-zA-Z0-9_]+)(?:%([0-9]*).([0-9]+))?'); +final RegExp _placeholderPattern = RegExp( + '#([-a-zA-Z0-9_]+)(?:%([0-9]*).([0-9]+))?', +); /// Convert a CFE template string (which uses placeholders like `#string`) to /// an analyzer template string (which uses placeholders like `{0}`). String convertTemplate(Map<String, int> placeholderToIndexMap, String entry) { - return entry.replaceAllMapped(_placeholderPattern, - (match) => '{${placeholderToIndexMap[match.group(0)!]}}'); + return entry.replaceAllMapped( + _placeholderPattern, + (match) => '{${placeholderToIndexMap[match.group(0)!]}}', + ); } Future<String> _fetchSdkFile(String pathInSdk) async { final uri = Uri.parse( - 'https://raw.githubusercontent.com/dart-lang/sdk/refs/heads/main/$pathInSdk'); + 'https://raw.githubusercontent.com/dart-lang/sdk/refs/heads/main/$pathInSdk', + ); final rawFile = await http.read(uri); return rawFile; } @@ -73,7 +78,8 @@ Future<Object?> _loadSdkYaml(String pathInSdk) async { /// two-level map of [ErrorCodeInfo], indexed first by class name and then by /// error name. Map<String, Map<String, AnalyzerErrorCodeInfo>> _decodeAnalyzerMessagesYaml( - Object? yaml) { + Object? yaml, +) { Never problem(String message) { throw Exception('Problem in analyzer/messages.yaml: $message'); } @@ -94,22 +100,29 @@ Map<String, Map<String, AnalyzerErrorCodeInfo>> _decodeAnalyzerMessagesYaml( for (final errorEntry in classValue.entries) { final errorName = errorEntry.key; if (errorName is! String) { - problem('in class $className, non-string error key ' - '${json.encode(errorName)}'); + problem( + 'in class $className, non-string error key ' + '${json.encode(errorName)}', + ); } final errorValue = errorEntry.value; if (errorValue is! Map<Object?, Object?>) { - problem('value associated with error $className.$errorName is not a ' - 'map'); + problem( + 'value associated with error $className.$errorName is not a ' + 'map', + ); } AnalyzerErrorCodeInfo errorCodeInfo; try { - errorCodeInfo = (result[className] ??= {})[errorName] = - AnalyzerErrorCodeInfo.fromYaml(errorValue); + errorCodeInfo = + (result[className] ??= + {})[errorName] = AnalyzerErrorCodeInfo.fromYaml(errorValue); } catch (e, st) { Error.throwWithStackTrace( - 'while processing $className.$errorName, $e', st); + 'while processing $className.$errorName, $e', + st, + ); } if (errorCodeInfo case AliasErrorCodeInfo(:final aliasFor)) { @@ -121,8 +134,10 @@ Map<String, Map<String, AnalyzerErrorCodeInfo>> _decodeAnalyzerMessagesYaml( for (final key in aliasForPath) { final value = node[key]; if (value is! Map<Object?, Object?>) { - problem('No Map value at "$aliasFor", aliased from ' - '$className.$errorName'); + problem( + 'No Map value at "$aliasFor", aliased from ' + '$className.$errorName', + ); } node = value; } @@ -163,7 +178,7 @@ class AliasErrorCodeInfo extends AnalyzerErrorCodeInfo { final String aliasFor; AliasErrorCodeInfo._fromYaml(super.yaml, {required this.aliasFor}) - : super._fromYaml(); + : super._fromYaml(); String get aliasForClass => aliasFor.split('.').first; } @@ -223,30 +238,37 @@ pkg/front_end/tool/fasta generate-messages } final previousEntryForIndex = indexToInfo[index]; if (previousEntryForIndex != null) { - throw Exception('Index $index used by both ' - '$previousEntryForIndex and $frontEndCode'); + throw Exception( + 'Index $index used by both ' + '$previousEntryForIndex and $frontEndCode', + ); } indexToInfo[index] = errorCodeInfo; final analyzerCodeLong = errorCodeInfo.analyzerCode.single; final expectedPrefix = 'ParserErrorCode.'; if (!analyzerCodeLong.startsWith(expectedPrefix)) { - throw Exception('Expected all analyzer error codes to be prefixed with ' - '${json.encode(expectedPrefix)}. Found ' - '${json.encode(analyzerCodeLong)}.'); + throw Exception( + 'Expected all analyzer error codes to be prefixed with ' + '${json.encode(expectedPrefix)}. Found ' + '${json.encode(analyzerCodeLong)}.', + ); } final analyzerCode = analyzerCodeLong.substring(expectedPrefix.length); final previousEntryForAnalyzerCode = analyzerCodeToInfo[analyzerCode]; if (previousEntryForAnalyzerCode != null) { - throw Exception('Analyzer code $analyzerCode used by both ' - '$previousEntryForAnalyzerCode and ' - '$frontEndCode'); + throw Exception( + 'Analyzer code $analyzerCode used by both ' + '$previousEntryForAnalyzerCode and ' + '$frontEndCode', + ); } analyzerCodeToInfo[analyzerCode] = errorCodeInfo; } for (var i = 1; i < indexToInfo.length; i++) { if (indexToInfo[i] == null) { throw Exception( - 'Indices are not consecutive; no error code has index $i.'); + 'Indices are not consecutive; no error code has index $i.', + ); } } } @@ -289,13 +311,14 @@ abstract class ErrorCodeInfo { /// Decodes an [ErrorCodeInfo] object from its YAML representation. ErrorCodeInfo.fromYaml(Map<Object?, Object?> yaml) - : this( - correctionMessage: yaml['correctionMessage'] as String?, - deprecatedMessage: yaml['deprecatedMessage'] as String?, - documentation: yaml['documentation'] as String?, - problemMessage: yaml['problemMessage'] as String? ?? '', - sharedName: yaml['sharedName'] as String?, - previousName: yaml['previousName'] as String?); + : this( + correctionMessage: yaml['correctionMessage'] as String?, + deprecatedMessage: yaml['deprecatedMessage'] as String?, + documentation: yaml['documentation'] as String?, + problemMessage: yaml['problemMessage'] as String? ?? '', + sharedName: yaml['sharedName'] as String?, + previousName: yaml['previousName'] as String?, + ); /// Given a messages.yaml entry, come up with a mapping from placeholder /// patterns in its message strings to their corresponding indices. @@ -308,8 +331,9 @@ abstract class ErrorCodeInfo { // make sure none of those are used. if (match.group(0) != '#${match.group(1)}') { throw Exception( - 'Template string ${json.encode(value)} contains unsupported ' - 'placeholder pattern ${json.encode(match.group(0))}'); + 'Template string ${json.encode(value)} contains unsupported ' + 'placeholder pattern ${json.encode(match.group(0))}', + ); } mapping[match.group(0)!] ??= mapping.length; @@ -330,9 +354,9 @@ class FrontEndErrorCodeInfo extends ErrorCodeInfo { final int? index; FrontEndErrorCodeInfo.fromYaml(super.yaml) - : analyzerCode = _decodeAnalyzerCode(yaml['analyzerCode']), - index = yaml['index'] as int?, - super.fromYaml(); + : analyzerCode = _decodeAnalyzerCode(yaml['analyzerCode']), + index = yaml['index'] as int?, + super.fromYaml(); static List<String> _decodeAnalyzerCode(Object? value) { return switch (value) { diff --git a/tool/dart_site/lib/src/diagnostics/linter.dart b/tool/dart_site/lib/src/diagnostics/linter.dart index bdc658beb7..4cece7af2b 100644 --- a/tool/dart_site/lib/src/diagnostics/linter.dart +++ b/tool/dart_site/lib/src/diagnostics/linter.dart @@ -16,17 +16,21 @@ String get _outputPath => Future<void> fetchAndUpdate() async { final rawRulesInfoUri = Uri.parse( - 'https://raw.githubusercontent.com/dart-lang/sdk/refs/heads/main/pkg/linter/tool/machine/rules.json'); + 'https://raw.githubusercontent.com/dart-lang/sdk/refs/heads/main/pkg/linter/tool/machine/rules.json', + ); final rawRulesInfo = await http.read(rawRulesInfoUri); final rulesInfo = (jsonDecode(rawRulesInfo) as List<Object?>).cast<Map<String, Object?>>(); final coreRules = await _rulesConfigured( - 'https://raw.githubusercontent.com/dart-lang/core/refs/heads/main/pkgs/lints/lib/core.yaml'); + 'https://raw.githubusercontent.com/dart-lang/core/refs/heads/main/pkgs/lints/lib/core.yaml', + ); final recommendedRules = await _rulesConfigured( - 'https://raw.githubusercontent.com/dart-lang/core/refs/heads/main/pkgs/lints/lib/recommended.yaml'); + 'https://raw.githubusercontent.com/dart-lang/core/refs/heads/main/pkgs/lints/lib/recommended.yaml', + ); final flutterRules = await _rulesConfigured( - 'https://raw.githubusercontent.com/flutter/packages/refs/heads/main/packages/flutter_lints/lib/flutter.yaml'); + 'https://raw.githubusercontent.com/flutter/packages/refs/heads/main/packages/flutter_lints/lib/flutter.yaml', + ); for (final rule in rulesInfo) { final ruleName = rule['name'] as String; @@ -37,8 +41,9 @@ Future<void> fetchAndUpdate() async { }.toList(growable: false); } - final formattedRuleInfo = - const JsonEncoder.withIndent(' ').convert(rulesInfo); + final formattedRuleInfo = const JsonEncoder.withIndent( + ' ', + ).convert(rulesInfo); File(_outputPath).writeAsStringSync(formattedRuleInfo); } @@ -51,7 +56,5 @@ Future<Set<String>> _rulesConfigured(String path) async { // Assume the structure of the analysis options file. final linterOptions = options['linter'] as Map; final enabledRules = linterOptions['rules'] as List<Object?>; - return { - for (final ruleName in enabledRules) ruleName as String, - }; + return {for (final ruleName in enabledRules) ruleName as String}; } diff --git a/tool/dart_site/lib/src/utils.dart b/tool/dart_site/lib/src/utils.dart index d605ea95c4..1fd4890b4c 100644 --- a/tool/dart_site/lib/src/utils.dart +++ b/tool/dart_site/lib/src/utils.dart @@ -36,11 +36,10 @@ void groupEnd() { } int runPubGetIfNecessary(String directory) { - final pubGetOutput = Process.runSync( - Platform.executable, - const ['pub', 'get'], - workingDirectory: directory, - ); + final pubGetOutput = Process.runSync(Platform.executable, const [ + 'pub', + 'get', + ], workingDirectory: directory); if (pubGetOutput.exitCode != 0) { final normalOutput = pubGetOutput.stdout.toString(); @@ -66,10 +65,10 @@ extension ArgResultExtensions on ArgResults? { /// excluding ones in hidden directories or codelabs. final List<String> dartProjectExampleDirectories = findNestedDirectoriesWithPubspec( - Directory('examples'), - skipPaths: {}, - skipHidden: true, -)..sort(); + Directory('examples'), + skipPaths: {}, + skipHidden: true, + )..sort(); List<String> findNestedDirectoriesWithPubspec( Directory rootDirectory, { @@ -91,11 +90,13 @@ List<String> findNestedDirectoriesWithPubspec( if (entity is Directory) { // If this entity is a direct, recurse in to it // to find any pubspec files. - directoriesWithPubspec.addAll(findNestedDirectoriesWithPubspec( - entity, - skipPaths: skipPaths, - skipHidden: skipHidden, - )); + directoriesWithPubspec.addAll( + findNestedDirectoriesWithPubspec( + entity, + skipPaths: skipPaths, + skipHidden: skipHidden, + ), + ); } else if (entity is File && path.basename(entity.path) == 'pubspec.yaml') { // If the directory has a pubspec.yaml file, this directory counts. directoriesWithPubspec.add(normalizedPath); diff --git a/tool/dart_site/pubspec.yaml b/tool/dart_site/pubspec.yaml index 48d73febd1..2261936a43 100644 --- a/tool/dart_site/pubspec.yaml +++ b/tool/dart_site/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: args: ^2.5.0 diff --git a/tool/get-dart/archive/pubspec.yaml b/tool/get-dart/archive/pubspec.yaml index 279f0d56b7..335e93ffc6 100644 --- a/tool/get-dart/archive/pubspec.yaml +++ b/tool/get-dart/archive/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: dart_sdk_archive: diff --git a/tool/get-dart/dart_sdk_archive/lib/src/generator.dart b/tool/get-dart/dart_sdk_archive/lib/src/generator.dart index 214a547b10..8b346e3453 100644 --- a/tool/get-dart/dart_sdk_archive/lib/src/generator.dart +++ b/tool/get-dart/dart_sdk_archive/lib/src/generator.dart @@ -16,17 +16,20 @@ class SvnVersionGenerator { final result = <String, String>{ for (final MapEntry(key: revision, value: version) in versionInfos.entries) - revision: version.toString() + revision: version.toString(), }; return result; } Future<void> _loadVersionInfo( - Map<String, VersionInfo> versionInfos, String channel) async { - final versionBaseNames = await _downloader - .fetchVersionPaths(channel) - .map(path.basename) - .toList(); + Map<String, VersionInfo> versionInfos, + String channel, + ) async { + final versionBaseNames = + await _downloader + .fetchVersionPaths(channel) + .map(path.basename) + .toList(); await Future.forEach<String>(versionBaseNames, (name) async { if (!isSvnRevision(name)) { diff --git a/tool/get-dart/dart_sdk_archive/lib/src/operating_system.dart b/tool/get-dart/dart_sdk_archive/lib/src/operating_system.dart index 96df371102..dfb072135f 100644 --- a/tool/get-dart/dart_sdk_archive/lib/src/operating_system.dart +++ b/tool/get-dart/dart_sdk_archive/lib/src/operating_system.dart @@ -1,8 +1,13 @@ import 'package:web/web.dart'; final class OperatingSystem { - static final OperatingSystem current = - [_chrome, _mac, _windows, _linux, _unix].firstWhere( + static final OperatingSystem current = [ + _chrome, + _mac, + _windows, + _linux, + _unix, + ].firstWhere( (system) => window.navigator.appVersion.contains(system._navigatorName), orElse: () => const OperatingSystem('Unknown', 'Unknown'), ); @@ -18,27 +23,12 @@ final class OperatingSystem { bool get isWindows => this == _windows; } -const _linux = OperatingSystem( - 'Linux', - 'Linux', -); - -const _mac = OperatingSystem( - 'Mac', - 'Mac', -); - -const _unix = OperatingSystem( - 'Unix', - 'X11', -); - -const _windows = OperatingSystem( - 'Windows', - 'Win', -); - -const _chrome = OperatingSystem( - 'ChromeOS', - 'CrOS', -); +const _linux = OperatingSystem('Linux', 'Linux'); + +const _mac = OperatingSystem('Mac', 'Mac'); + +const _unix = OperatingSystem('Unix', 'X11'); + +const _windows = OperatingSystem('Windows', 'Win'); + +const _chrome = OperatingSystem('ChromeOS', 'CrOS'); diff --git a/tool/get-dart/dart_sdk_archive/lib/src/svn_versions.dart b/tool/get-dart/dart_sdk_archive/lib/src/svn_versions.dart index 8245b6b458..7b772bfa78 100644 --- a/tool/get-dart/dart_sdk_archive/lib/src/svn_versions.dart +++ b/tool/get-dart/dart_sdk_archive/lib/src/svn_versions.dart @@ -148,5 +148,5 @@ const Map<String, String> svnVersions = { '45268': '1.10.0-dev.1.7', '45369': '1.10.0-dev.1.10', '45311': '1.10.0-dev.1.9', - '45519': '1.11.0-dev.0.0' + '45519': '1.11.0-dev.0.0', }; diff --git a/tool/get-dart/dart_sdk_archive/lib/src/version_selector.dart b/tool/get-dart/dart_sdk_archive/lib/src/version_selector.dart index 9900d4b1f0..1533546735 100644 --- a/tool/get-dart/dart_sdk_archive/lib/src/version_selector.dart +++ b/tool/get-dart/dart_sdk_archive/lib/src/version_selector.dart @@ -30,18 +30,20 @@ class VersionSelector { Future<void> init() async { _versionSelector.addEventListener( - 'change', - (Event event) { - populateTable(); - }.toJS); + 'change', + (Event event) { + populateTable(); + }.toJS, + ); _osSelector.addEventListener( - 'change', - (Event event) { - filterTable(); - }.toJS); - final versions = (await fetchSdkVersions(channel) - ..sort()) - .reversed; + 'change', + (Event event) { + filterTable(); + }.toJS, + ); + final versions = + (await fetchSdkVersions(channel) + ..sort()).reversed; for (final version in versions) { addVersion(version); } @@ -63,12 +65,15 @@ class VersionSelector { } Future<void> populateTable() async { - final selectedVersion = - _versionSelector.selectedOptions.item(0)?.getAttribute('value'); + final selectedVersion = _versionSelector.selectedOptions + .item(0) + ?.getAttribute('value'); if (selectedVersion == null) return; final svnRevision = svnRevisionForVersion(selectedVersion); - final versionInfo = - await _client.fetchVersion(channel, svnRevision ?? selectedVersion); + final versionInfo = await _client.fetchVersion( + channel, + svnRevision ?? selectedVersion, + ); await findSystemLocale(); await initializeDateFormatting(Intl.systemLocale); clearTable(); @@ -90,10 +95,12 @@ class VersionSelector { } void filterTable() { - final selectedVersion = - _versionSelector.selectedOptions.item(0)!.getAttribute('value'); - final selectedOs = - _osSelector.selectedOptions.item(0)!.getAttribute('value'); + final selectedVersion = _versionSelector.selectedOptions + .item(0)! + .getAttribute('value'); + final selectedOs = _osSelector.selectedOptions + .item(0)! + .getAttribute('value'); final tableVersionRows = _table.querySelectorAll('tr[data-version]'); if (selectedVersion == 'all' && selectedOs == 'all') { @@ -109,8 +116,9 @@ class VersionSelector { selector += '[data-version="$selectedVersion"]'; } - final tableOsSelectors = - _table.querySelectorAll('$selector[data-os="api"]'); + final tableOsSelectors = _table.querySelectorAll( + '$selector[data-os="api"]', + ); tableOsSelectors.forEachElement((element) { element.classList.remove('hidden'); }); @@ -151,9 +159,10 @@ class VersionSelector { } void addVersion(Version version) { - final option = (document.createElement('option') as HTMLOptionElement) - ..text = version.toString() - ..setAttribute('value', version.toString()); + final option = + (document.createElement('option') as HTMLOptionElement) + ..text = version.toString() + ..setAttribute('value', version.toString()); _versionSelector.appendChild(option); } @@ -169,8 +178,11 @@ class VersionSelector { continue; } } else if (platformVariant.architecture == 'ARMv7' && - versionInfo.date.isBefore(DateTime.parse( - (channel == 'dev') ? '2015-10-21' : '2015-08-31'))) { + versionInfo.date.isBefore( + DateTime.parse( + (channel == 'dev') ? '2015-10-21' : '2015-08-31', + ), + )) { continue; } else if (platformVariant.architecture == 'ARMv8 (ARM64)' && versionInfo.date.isBefore(DateTime.parse('2017-03-09'))) { @@ -234,12 +246,13 @@ class VersionSelector { (_table.tBodies.item(0) as HTMLTableSectionElement).insertRow() ..setAttribute('data-version', versionInfo.version.toString()) ..setAttribute('data-os', archiveMap[name] ?? ''); - final versionCell = row.insertCell() - ..textContent = versionInfo.version.toString(); - versionCell - .appendChild((document.createElement('span') as HTMLSpanElement) - ..textContent = ' (${_prettyRevRef(versionInfo)})' - ..classList.add('muted')); + final versionCell = + row.insertCell()..textContent = versionInfo.version.toString(); + versionCell.appendChild( + (document.createElement('span') as HTMLSpanElement) + ..textContent = ' (${_prettyRevRef(versionInfo)})' + ..classList.add('muted'), + ); row.insertCell().textContent = name; row.insertCell() ..classList.add('nowrap') @@ -256,7 +269,8 @@ class VersionSelector { continue; } - var baseFileName = '${archiveMap[pa]}-${archiveMap[name]}-' + var baseFileName = + '${archiveMap[pa]}-${archiveMap[name]}-' '${archiveMap[platformVariant.architecture]}'; if (pa == 'Debian package') { @@ -272,18 +286,22 @@ class VersionSelector { '$_storageBase/channels/$channel/release/${_versionString(versionInfo)}' '/${directoryMap[pa]}/$baseFileName${suffixMap[pa]}'; - c.appendChild((document.createElement('a') as HTMLAnchorElement) - ..text = pa - ..setAttribute('href', uri)); + c.appendChild( + (document.createElement('a') as HTMLAnchorElement) + ..text = pa + ..setAttribute('href', uri), + ); final svnRevisionInfo = _svnRevision(versionInfo); if (pa != 'Dart Editor' && pa != 'Debian package' && (svnRevisionInfo == null || svnRevisionInfo > 38976)) { c.append(' '.toJS); - c.appendChild((document.createElement('a') as HTMLAnchorElement) - ..textContent = '(SHA-256)' - ..setAttribute('href', '$uri.sha256sum') - ..classList.add('sha')); + c.appendChild( + (document.createElement('a') as HTMLAnchorElement) + ..textContent = '(SHA-256)' + ..setAttribute('href', '$uri.sha256sum') + ..classList.add('sha'), + ); } c.appendChild(document.createElement('br')); } @@ -292,12 +310,14 @@ class VersionSelector { } // Add DartDoc archive. - final row = (_table.tBodies.item(0) as HTMLTableSectionElement).insertRow() - ..setAttribute('data-version', versionInfo.version.toString()) - ..setAttribute('data-os', 'api'); - final rev = (document.createElement('span') as HTMLSpanElement) - ..textContent = ' (${_prettyRevRef(versionInfo)})' - ..classList.add('muted'); + final row = + (_table.tBodies.item(0) as HTMLTableSectionElement).insertRow() + ..setAttribute('data-version', versionInfo.version.toString()) + ..setAttribute('data-os', 'api'); + final rev = + (document.createElement('span') as HTMLSpanElement) + ..textContent = ' (${_prettyRevRef(versionInfo)})' + ..classList.add('muted'); row.insertCell() ..textContent = versionInfo.version.toString() ..appendChild(rev); @@ -307,11 +327,14 @@ class VersionSelector { _addReleaseDateCell(versionInfo, row); final c = row.insertCell()..classList.add('archives'); - final uri = '$_storageBase/channels/$channel/release/' + final uri = + '$_storageBase/channels/$channel/release/' '${versionInfo.version}/api-docs/dartdocs-gen-api.zip'; - c.appendChild((document.createElement('a') as HTMLAnchorElement) - ..textContent = 'API docs' - ..setAttribute('href', uri)); + c.appendChild( + (document.createElement('a') as HTMLAnchorElement) + ..textContent = 'API docs' + ..setAttribute('href', uri), + ); final templateRows = _table.querySelectorAll('.template'); templateRows.forEachElement((element) { @@ -325,8 +348,9 @@ class VersionSelector { if (creationDate == null) { dateRow.textContent = '---'; } else { - dateRow.textContent = - DateFormat.yMMMd(Intl.systemLocale).format(creationDate); + dateRow.textContent = DateFormat.yMMMd( + Intl.systemLocale, + ).format(creationDate); } } } diff --git a/tool/get-dart/dart_sdk_archive/pubspec.yaml b/tool/get-dart/dart_sdk_archive/pubspec.yaml index 6d5e35b87c..6c5ab43bad 100644 --- a/tool/get-dart/dart_sdk_archive/pubspec.yaml +++ b/tool/get-dart/dart_sdk_archive/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: http: ^1.2.2 diff --git a/tool/get-dart/pubspec.yaml b/tool/get-dart/pubspec.yaml index 2c2c7a8e50..93f0e923bc 100644 --- a/tool/get-dart/pubspec.yaml +++ b/tool/get-dart/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 workspace: - archive diff --git a/tool/get-dart/sdk_builds/lib/src/dart_downloads.dart b/tool/get-dart/sdk_builds/lib/src/dart_downloads.dart index 68d07d8495..958597376e 100644 --- a/tool/get-dart/sdk_builds/lib/src/dart_downloads.dart +++ b/tool/get-dart/sdk_builds/lib/src/dart_downloads.dart @@ -19,8 +19,7 @@ String _revisionPath( String channel, String revision, [ List<String> extra = const [], -]) => - p.joinAll(['channels', channel, _flavor, revision, ...extra]); +]) => p.joinAll(['channels', channel, _flavor, revision, ...extra]); class DartDownloads { final storage.StorageApi _api; @@ -31,11 +30,14 @@ class DartDownloads { DartDownloads._(client ?? http.Client()); DartDownloads._(http.Client client) - : _client = client, - _api = storage.StorageApi(client, rootUrl: storageBaseUrl); + : _client = client, + _api = storage.StorageApi(client, rootUrl: storageBaseUrl); Future<Uri> createDownloadLink( - String channel, String revision, String path) async { + String channel, + String revision, + String path, + ) async { final prefix = _revisionPath(channel, revision, [path]); final results = await _api.objects.list(_dartChannel, prefix: prefix); final items = results.items; @@ -56,9 +58,10 @@ class DartDownloads { } Future<List<VersionInfo>> fetchVersions(String channel) async { - final versions = await fetchVersionPaths(channel) - .where((event) => !event.contains('latest')) - .toList(); + final versions = + await fetchVersionPaths( + channel, + ).where((event) => !event.contains('latest')).toList(); final versionMaps = <VersionInfo>[]; @@ -85,8 +88,12 @@ class DartDownloads { String? nextToken; do { - final objects = await _api.objects.list(_dartChannel, - prefix: prefix, pageToken: nextToken, delimiter: '/'); + final objects = await _api.objects.list( + _dartChannel, + prefix: prefix, + pageToken: nextToken, + delimiter: '/', + ); nextToken = objects.nextPageToken; final prefixes = objects.prefixes; @@ -106,10 +113,11 @@ class DartDownloads { final creationTime = (await _fetchMetadata(channel, revision, 'VERSION')).timeCreated; - final json = await _jsonAsciiDecoder - .bind(media.stream) - .cast<Map<String, Object?>>() - .first; + final json = + await _jsonAsciiDecoder + .bind(media.stream) + .cast<Map<String, Object?>>() + .first; return VersionInfo.parse( channel, @@ -122,20 +130,28 @@ class DartDownloads { void close() => _client.close(); Future<storage.Media> _fetchFile( - String channel, String revision, String path) async => + String channel, + String revision, + String path, + ) async => await _api.objects.get( - _dartChannel, - _revisionPath(channel, revision, [path]), - downloadOptions: storage.DownloadOptions.fullMedia, - ) as storage.Media; + _dartChannel, + _revisionPath(channel, revision, [path]), + downloadOptions: storage.DownloadOptions.fullMedia, + ) + as storage.Media; Future<storage.Object> _fetchMetadata( - String channel, String revision, String path) async => + String channel, + String revision, + String path, + ) async => await _api.objects.get( - _dartChannel, - _revisionPath(channel, revision, [path]), - downloadOptions: storage.DownloadOptions.metadata, - ) as storage.Object; + _dartChannel, + _revisionPath(channel, revision, [path]), + downloadOptions: storage.DownloadOptions.metadata, + ) + as storage.Object; } final _jsonAsciiDecoder = json.fuse(ascii).decoder; diff --git a/tool/get-dart/sdk_builds/pubspec.yaml b/tool/get-dart/sdk_builds/pubspec.yaml index b46c8cabae..5d4c71443b 100644 --- a/tool/get-dart/sdk_builds/pubspec.yaml +++ b/tool/get-dart/sdk_builds/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.1 + sdk: ^3.7.0 dependencies: googleapis: ^13.2.0 diff --git a/tool/get-dart/sdk_builds/test/sdk_builds_test.dart b/tool/get-dart/sdk_builds/test/sdk_builds_test.dart index 377f269206..a0a84c4227 100644 --- a/tool/get-dart/sdk_builds/test/sdk_builds_test.dart +++ b/tool/get-dart/sdk_builds/test/sdk_builds_test.dart @@ -43,8 +43,9 @@ void main() async { const channel = 'dev'; const revision = '1.11.0-dev.5.2'; - final content = await _dartDownloads.fetchVersion(channel, revision) - as GitVersionInfo; + final content = + await _dartDownloads.fetchVersion(channel, revision) + as GitVersionInfo; expect(content.ref, '23736d3630da614c655d0569e1ba5af2021b1c61'); expect(content.version, Version.parse('1.11.0-dev.5.2')); @@ -55,8 +56,9 @@ void main() async { const channel = 'stable'; const revision = '44672'; - final content = await _dartDownloads.fetchVersion(channel, revision) - as SvnVersionInfo; + final content = + await _dartDownloads.fetchVersion(channel, revision) + as SvnVersionInfo; expect(content.revision, 44672); expect(content.version, Version.parse('1.9.1')); @@ -79,7 +81,10 @@ void main() async { const revision = '44672'; final content = await _dartDownloads.createDownloadLink( - channel, revision, 'api-docs/dart-api-docs.zip'); + channel, + revision, + 'api-docs/dart-api-docs.zip', + ); expect(content.pathSegments, [ 'download', 'storage', @@ -87,7 +92,7 @@ void main() async { 'b', 'dart-archive', 'o', - 'channels/$channel/release/$revision/api-docs/dart-api-docs.zip' + 'channels/$channel/release/$revision/api-docs/dart-api-docs.zip', ]); }); }