Headline
CVE-2021-22568: sdk/CHANGELOG.md at main · dart-lang/sdk
When using the dart pub publish command to publish a package to a third-party package server, the request would be authenticated with an oauth2 access_token that is valid for publishing on pub.dev. Using these obtained credentials, an attacker can impersonate the user on pub.dev. We recommend upgrading past https://github.com/dart-lang/sdk/commit/d787e78d21e12ec1ef712d229940b1172aafcdf8 or beyond version 2.15.0
2.16.0****Core libraries****dart:core
Breaking Change #47653: On Windows,
Directory.renamewill no longer delete a directory ifnewPathspecifies one. Instead, aFileSystemExceptionwill be thrown.Add
Error.throwWithStackTracewhich canthrowan error with an existing stack trace, instead of creating a new stack trace.
dart:io
- Breaking Change #47769: The
Platform.packageRootAPI has been removed. It had been marked deprecated in 2018, as it doesn’t work with any Dart 2.x release. - Add optional
sourcePortparameter toSocket.connect,Socket.startConnect,RawSocket.connectandRawSocket.startConnect
dart:isolate
- Breaking Change #47769: The
Isolate.packageRootAPI has been removed. It had been marked deprecated in 2018, as it doesn’t work with any Dart 2.x release.
Tools****Dart command line
Breaking Change #46100: The standalone
dartanalyzertool has been marked deprecated as previously announced. Its replacement is thedart analyzecommand. Should you find any issues, or missing features, in the replacement command, kindly file an issue.Breaking Change #46100: The standalone
dartdoctool has been marked deprecated as previously announced. Its replacement is thedart doccommand. Should you find any issues, or missing features, in the replacement command, kindly file an issue.
Linter
Updated the Linter to 1.15.0, which includes changes that
- adds new lint:
avoid_final_parameters. - adds new lint:
no_leading_underscores_for_library_prefixes. - adds new lint:
no_leading_underscores_for_local_identifiers. - adds new lint:
secure_pubspec_urls. - adds new lint:
sized_box_shrink_expand. - adds new lint:
use_decorated_box. - improves docs for
omit_local_variable_types.
2.15.0****Language
The following features are new in the Dart 2.15 language version. To use them, you must set the lower bound on the SDK constraint for your package to 2.15 or greater (sdk: '>=2.15.0 <3.0.0').
Constructor tear-offs: Previous Dart versions allowed a method on an instance to be passed as a closure, and similarly for static methods. This is commonly referred to as “closurizing” or “tearing off” a method. Constructors were not previously eligible for closurization, forcing users to explicitly write wrapper functions when using constructors as first class functions. See the calls to
map()in this example:class A { int x; A(this.x); A.fromString(String s) : x = int.parse(s); }
void main() { var listOfInts = [1, 2, 3]; var listOfStrings = ["1", "2", “3”]; for(var a in listOfInts.map((x) => A(x))) { print(a.x); } for(var a in listOfStrings.map((x) => A.fromString(x))) { print(a.x); } }
New in Dart 2.15, constructors are now allowed to be torn off. Named constructors are closurized using their declared name (here
A.fromString). To closurize unnamed constructors, use the keywordnew(hereA.new). The above example may now be written as:class A { int x; A(this.x); A.fromString(String s) : x = int.parse(s); }
void main() { var listOfInts = [1, 2, 3]; var listOfStrings = ["1", "2", “3”]; for(A a in listOfInts.map(A.new)) { print(a.x); } for(A a in listOfStrings.map(A.fromString)) { print(a.x); } }
Constructors for generic classes may be torn off as generic functions, or instantiated at the tear-off site. In the following example, the tear-off
G.newis used to initialize the variablefproduces a generic function which may be used to produce an instance ofG<T>for any typeTprovided whenfis called. The tear-offG<String>.newis used to initialize the variablegto produce a non-generic function which may only be used to produce instances of typeG<String>.class G<T> { T x; G(this.x); }
void main() { G<T> Function<T>(T x) f = G.new; var x = f<int>(3); G<String> Function(String y) g = G<String>.new; var y = g(“hello”); }
Generic type literals: Previous Dart versions allowed class names to be used as type literals. So for example,
intmay be used as an expression, producing a value of typeType. Generic classes (e.g.List) could be referred to by name as an expression, but no type arguments could be provided and so only thedynamicinstantiation could be produced directly as an expression without using indirect methods:// Workaround to capture generic type literals. Type typeOf<T>() => T;
void main() { var x = int; // The Type literal corresponding to `int`. var y = List; // The Type literal corresponding to `List<dynamic>`. // Use workaround to capture generic type literal. var z = typeOf<List<int>>(); // The Type literal for `List<int>`. }
New in Dart 2.15, instantiations of generic classes may now be used as Type literals:
void main() { var x = int; // The Type literal corresponding to `int`. var y = List; // The Type literal corresponding to `List<dynamic>`. var z = List<int>; // The Type literal corresponding to `List<int>`. }
Explicit generic method instantiations: Previous Dart versions allowed generic methods to be implicitly specialized (or “instantiated”) to non-generic versions when assigned to a location with a compatible monomorphic type. Example:
// The generic identity function. T id<T>(T x) => x;
void main() { // Initialize `intId` with a version of `id` implicitly specialized to // `int`. int Function(int) intId = id; print(intId(3)); // Initialize `stringId` with a version of `id` implicitly specialized to // `String`. String Function(String) stringId = id; print(stringId(“hello”)); }
New in Dart 2.15, generic methods may be explicitly instantiated using the syntax
f<T>wherefis the generic method to specialize andTis the type argument (in general, type arguments) to be used to specialize the method. Example:// The generic identity function. T id<T>(T x) => x;
void main() { // Initialize `intId` with a version of `id` explicitly specialized to // `int`. var intId = id<int>; print(intId(3)); // Initialize `stringId` with a version of `id` explicitly specialized to // `String`. var stringId = id<String>; print(stringId(“hello”)); }
Generic instantiation of function objects: Generic function instantiation was previously restricted to function declarations. For example, as soon as a function had been torn off, it could not be instantiated:
// Before Dart 2.15: X id<X>(X x) => x;
void main() { var fo = id; // Tear off `id`, creating a function object. var c1 = fo<int>; // Compile-time error: can’t instantiate `fo`. int Function(int) c2 = fo; // Same compile-time error. // Constants are treated the same. }
New in Dart 2.15, this restriction has been lifted. It is now possible to obtain a generic instantiation of an existing function object, both explicitly and implicitly (again, this works the same for non-constants):
X id<X>(X x) => x; X other<X>(X x) => throw x;
void main() { const fo = id; // Tear off `id`, creating a function object.
// Generic function instantiation on `fo` is no longer an error. const c1 = fo<int>; // OK. const int Function(int) c2 = fo; // OK.
// This also generalizes function instantiation because we can, // e.g., use non-trivial expressions and go via a constructor. const c3 = A(true); // OK. }
class A { final int Function(int) x; // `(…)<T>` is now allowed, also in a `const` constructor. const A(bool b): x = (b ? id : other)<int>; }
Annotations on type parameters of classes can no longer refer to class members without a prefix. For example, this used to be permitted:
class C<@Annotation(foo) T> { static void foo() {} }
Now, the reference must be qualified with the class name, i.e.:
class C<@Annotation(C.foo) T> { static void foo() {} }
This brings the implementation behavior in line with the spec.
Initializer expressions on implicitly typed condition variables can now contribute to type promotion. For example, this program no longer produces a compile-time error:
f(int? i) { var iIsNull = i == null; if (!iIsNull) { print(i + 1); // OK, because `i` is known to be non-null. } }
Previously, the above program had a compile-time error due to a bug (#1785) in type promotion which prevented the initializer expression (
i == null) from being accounted for when the variable in question (iIsNull) lacked an explicit type.To avoid causing problems for packages that are intended to work with older versions of Dart, the fix only takes effect when the minimum SDK of the source packages is 2.15 or greater.
Restrictions on members of a class with a constant constructor are relaxed such that they only apply when the class has a generative constant constructor. For example, this used to be an error, but is now permitted:
abstract class A { const factory A() = B; var v1; late final v2 = Random().nextInt(10); late final v3; }
class B implements A { const B([this.v3 = 1]); get v1 => null; set v1(_) => throw 'Cannot mutate B.v1’; final v2 = 0; final v3; set v3(_) => throw 'Cannot initialize B.v3’; }
This implements a relaxation of the specified rule for a
late finalinstance variable, and it brings the implementation behavior in line with the specification in all other cases.Function object canonicalization and equality: Several corner cases in the area of function object canonicalization and function object equality have been updated, such that all tools behave in the same way, and the behavior matches the specification.
In particular, function objects are now equal when they are obtained by generic instantiation from the same function with the same actual type arguments, even when that type argument is not known at compile time. When the expressions are constant then the function objects are identical. Constant expressions are treated as such even when they do not occur in a constant context (e.g.,
var f = top;).
Core libraries****dart:async
- Make the
unawaitedfunction’s argument nullable, to allow calls likeunawaited(foo?.bar()).
dart:cli
- The experimental
waitForfunctionality, and the library containing only that function, are now deprecated.
dart:core
- Add extension
namegetter on enum values. - Add
Enum.compareByIndexhelper function for comparing enum values by index. - Add
Enum.compareByNamehelper function for comparing enum values by name. - Add extension methods on
Iterable<T extends Enum>, intended forSomeEnumType.valueslists, to look up values by name. - Deprecate
IntegerDivisionByZeroException. Makes the class also implementError. Code throwing the exception will be migrated to throwing anErrorinstead until the class is unused and ready to be removed. Code catching the class should move to catchingErrorinstead (or, for integers, check first for whether it’s dividing by zero).
dart:io
- Breaking Change #46875: The
SecurityContextclass indart:iohas been updated to set the minimum TLS protocol version to TLS1_2_VERSION (1.2) instead of TLS1_VERSION. - Add
RawSocket.sendMessage,RawSocket.receiveMessagethat allow passing of file handle references via Unix domain sockets.
dart:js_util
- The
js_utilmethodssetProperty,callMethod, andcallConstructorhave been optimized to remove checks on arguments when the checks can be elided. Also, those methods, along withgetPropertyandnewObject, now support a generic type argument to specify a return type. These two changes make simplejs_utilusage, like reading and writing primitive properties or calling methods with simple arguments, have zero overhead.
dart:web_sql
- Breaking Change #46316: The WebSQL standard was abandoned more than 10 years ago and is not supported by many browsers. This release completely deletes the
dart:web_sqllibrary.
dart:html
- Breaking Change #46316: Related to the removal of
dart:web_sql(see above),window.openDatabasehas been removed.
Tools****Dart command line
Breaking Change #46100: The standalone
dart2nativetool has been removed as previously announced. Its replacements are thedart compile exeanddart compile aot-snapshotcommands, which offer the same functionality.Breaking Change: The standalone
dartfmttool has been removed as previously announced. Its replacement is thedart formatcommand.Note that
dart formathas a different set of options and defaults thandartfmt.When a script is
dart runit will always be precompiled, but with incremental precompilation for following runs.
Dart VM
Breaking Change #45451: Support for
dart-ext:-style native extensions has been removed as previously announced. Usedart:ffito bind to native libraries instead.Breaking Change #46754: Isolates spawned via the
Isolate.spawn()API are now grouped, operate on the same managed heap and can therefore share various VM-internal data structures.This leads to ~100x faster isolate startup latency, ~10-100x lower per-isolate base memory overhead and ~8x faster inter-isolate communication.
Making isolates operate on the same heap will also make them collaborate on garbage collections, which changes performance characteristics for GC-heavy applications that may - in rare cases - negatively affect pause times or throughput.
Allow closures both in inter-isolate messages as well as as entrypoints in
Isolate.spawn(<entrypoint>, ...)calls. Closures and their enclosing context may need to be copied in this process. The enclosing context is - as with normal messages - verified to only contain objects that are sendable.Note of caution: The Dart VM’s current representation of enclosing variables in closures can make closures hang on to more variables than strictly needed. Using such closures in inter-isolate communication can therefore lead to copying of larger transitive object graphs. If the extended transitive closure includes objects that are illegal to send, the sending will fail. See #36983, which tracks this existing memory leak issue.
Linter
Updated the Linter to 1.14.0, which includes changes that
- improves performance for
annotate_overrides,prefer_contains, andprefer_void_to_null. - marks
avoid_dynamic_callsstable. - fixed
avoid_null_checks_in_equality_operatorsfalse positive with non-nullable params. - update
avoid_printto allowkDebugMode-wrapped print calls. - adds support for constructor tear-offs to
avoid_redundant_argument_values,unnecessary_lambdas, andunnecessary_parenthesis. - improves messages for
avoid_renaming_method_parameters. - improves regular expression parsing performance for common checks (
camel_case_types,file_names, etc.). - fixed
file_namesto report at the start of the file (not the entire compilation unit). - allow
while (true) { ... }inliteral_only_boolean_expressions. - fixed
omit_local_variable_typesfalse positives. - fixed
omit_local_variable_typesto not flag a local type that is required for inference. - fixed
overridden_fieldsfalse positive with static fields. - fixed
prefer_collection_literalsnamed typed parameter false positives. - fixed
prefer_const_constructorsfalse positive for deferred imports. - fixed
prefer_final_parametershandling of initializing formals. - fixed
prefer_generic_function_type_aliasesfalse positives with incomplete statements. - fixed
prefer_initializing_formalsfalse positives with factory constructors. - fixed
prefer_void_to_nullfalse positive with overridden properties. - fixed
prefer_void_to_nullfalse positives on overriding returns. - fixed
prefer_void_to_nullfalse positives. - adds a new lint:
unnecessary_constructor_nameto flag unnecessary uses of.new. - updates
unnecessary_getters_settersto only flag the getter. - fixed
unnecessary_parenthesisfalse positive with function expressions. - fixed
use_build_context_synchronouslyfalse positive in awaits inside anonymous functions. - improve control flow analysis for
use_build_context_synchronously. - fixed
use_rethrow_when_possiblefalse positives. - fixed
void_checksfalse positives with incomplete source.
Pub
- If you have analytics enabled
dart pub getwill send usage metrics for packages from pub.dev, intended for popularity analysis. - Adds support for token-based authorization to third-party package-repositories with the new command
dart pub token. - Credentials are no longer stored in the pub-cache, but in a platform dependent config directory:
- On Linux
$XDG_CONFIG_HOME/dart/pub-credentials.jsonif$XDG_CONFIG_HOMEis defined, otherwise$HOME/.config/dart/pub-credentials.json - On Mac OS:
$HOME/Library/Application Support/dart/pub-credentials.json - On Windows:
%APPDATA%/dart/pub-credentials.json
- On Linux
- The syntax for dependencies hosted at a third-party package repository has been simplified. Before you would need to write:
dependencies: colorizer: hosted: name: colorizer url: ‘https://custom-pub-server.com’ version: ^1.2.3 environment: sdk: ‘>=2.14.0 < 3.0.0’
Now you can write:
dependencies: colorizer: hosted: ‘https://custom-pub-server.com’ version: ^1.2.3 environment: sdk: ‘>=2.15.0 < 3.0.0’
This feature requires language-version 2.15 or later, e.g. the pubspec.yaml should have an SDK constraint of >=2.15 <3.0.0.
Detect potential leaks in
dart pub publish. When publishing, pub will examine your files for potential secret keys, and warn you.To ignore a file that has a false positive, add it to a
false_secretssection of yourpubspec.yaml.Fixes unicode terminal detection windows.
New flag
--exampleto the commandsdart pub get/upgrade/downgrade/add/removethat will result in theexample/folder dependencies to be updated after operating in the current directory.
Other libraries****package:js
- Extensions on JS interop or native
dart:htmlclasses can now declare members asexternal. These members are equivalent to regular extension members that usejs_utilto expose the underlying JavaScript.
2.14.4 - 2021-10-14
This is a patch release that fixes:
- a memory leak of analyzer plugins (issue flutter/flutter#90868).
- the Dart VM sometimes loading expired certificates on Windows (issues #46370 and #47420).
2.14.3 - 2021-09-30
This is a patch release that fixes:
- a code completion performance regression (issue flutter/flutter-intellij#5761).
- debug information emitted by the Dart VM (issue #47289).
2.14.2 - 2021-09-16
This is a patch release that fixes:
- two dartdoc crashes (issues dart-lang/dartdoc#2740 and dart-lang/dartdoc#2755).
- error messages when using the
>>>operator on older language versions (issue #46886). - invalid
pubspec.lockpaths on Windows (issue dart-lang/pub#3012).
2.14.1 - 2021-09-09
- Fixed an issue specific to the macOS ARM64 (Apple Silicon) SDK, where the Dart commandline tools did not have the expected startup performance.
2.14.0 - 2021-09-09****Language
Add an unsigned shift right operator
>>>. Pad with zeroes, ignoring the sign bit. On the web platformint.>>>shifts the low 32 bits interpreted as an unsigned integer, soa >>> bgives the same result asa.toUnsigned(32) >>> bon the VM.Prior to Dart 2.14, metadata (annotations) were not permitted to be specified with generic type arguments. This restriction is lifted in Dart Dart 2.14.
class C<T> { const C(); } @C(); // Previously permitted. @C<int>(); // Previously an error, now permitted.
Prior to Dart 2.14, generic function types were not permitted as arguments to generic classes or functions, nor to be used as generic bounds. This restriction is lifted in Dart 2.14.
T wrapWithLogging<T>(T f) { if (f is void Function<T>(T x)) { return <S>(S x) { print("Call: f<$S>($x)"); var r = f<S>(x); print(“Return: $x”); return r; } as T; } // More cases here return f; } void foo<T>(T x) { print(“Foo!”); } void main() { // Previously an error, now permitted. var f = wrapWithLogging<void Function<T>(T)>(foo); f<int>(3); }
Core libraries****dart:async
The uncaught error handlers of
Zones are now run in the parent zone of the zone where they were declared. This prevents a throwing handler from causing an infinite loop by repeatedly triggering itself.Added
ignore()as extension member on futures.Added
void unawaited(Future)top-level function to deal with theunawaited_futureslint.
dart:core
Introduce
Enuminterface implemented by allenumdeclarations.The native
DateTimeclass now better handles local time around daylight saving changes that are not precisely one hour. (No change on the Web which uses the JavaScriptDateobject.)Adds static methods
hash,hashAllandhashAllUnorderedto theObjectclass. These can be used to combine the hash codes of multiple objects in a consistent way.The
Symbolconstructor now accepts any string as argument. Symbols are equal if they were created from the same string.
dart:ffi
- Adds the
DynamicLibrary.providesSymbolfunction to check whether a symbol is available in a dynamic library.
dart:html
convertNativeToDart_Dictionary()now converts objects recursively, this fixes APIs like MediaStreamTrack.getCapabilities that convert between Maps and browser Dictionaries. #44319- Added some access-control HTTP header names to
HttpHeaders.
dart:io
- BREAKING CHANGE (for pre-migrated null safe code):
HttpClient's.authenticateand.authenticateProxysetter callbacks must now accept a nullablerealmargument. - Added some access-control HTTP header names to
HttpHeaders.
dart:typed_data
- BREAKING CHANGE (https://github.com/dart-lang/sdk/issues/45115) Most types exposed by this library can no longer be extended, implemented or mixed-in. The affected types are
ByteBuffer,TypedDataand all its subclasses,Int32x4,Float32x4,Float64x2andEndian.
dart:web_sql
dart:web_sqlis marked deprecated and will be removed in an upcoming release. Also the APIwindow.openDatabaseindart:htmlis deprecated as well.This API and library was exposing the WebSQL proposed standard. The standard was abandoned more than 5 years ago and is not supported by most browsers. The
dart:web_sqllibrary has been documented as unsupported and deprecated for many years as well and but wasn’t annotated properly until now.
Dart VM
- Breaking Change #45071:
Dart_NewWeakPersistentHandle's andDart_NewFinalizableHandle'sobjectparameter no longer acceptsPointers and subtypes ofStruct. Expandos no longer acceptPointers and subtypes ofStructs.
Tools****Dart command line
Breaking Change #46100: The standalone
dart2nativetool has been marked deprecated, and now prints a warning message. Its replacements are thedart compile exeanddart compile aot-snapshotcommands, which offer the same functionality. Thedart2nativetool will be removed from the Dart SDK in Dart 2.15.Breaking Change: The standalone
dartfmttool has been marked deprecated, and now prints a warning message. Instead, usedart format. Thedartfmttool will be removed from the Dart SDK in Dart 2.15.Note that
dart formathas a different set of options and defaults thandartfmt.The
dart createcommand has been updated to create projects that use the new ‘recommended’ set of lints frompackage:lints. See https://dart.dev/go/core-lints for more information about these lints.
The
dart analyzecommand has been extended to support specifying multiple files or directories to analyze; see also https://github.com/dart-lang/sdk/issues/45352.The
dartanalyzercommand’s JSON output mode has been changed to emit the JSON output on stdout instead of stderr.
dart format
- Simplify and optimize cascade formatting. See: https://github.com/dart-lang/dart_style/pull/1033
- Don’t unnecessarily split argument lists with
/* */comments. - Return correct exit code from
FormatCommandwhen formatting stdin. - Split empty catch blocks with finally clauses or catches after them.
Linter
Updated the Linter to 1.8.0, which includes changes that
- improve performance for
prefer_is_not_empty. - fix false positives in
no_logic_in_create_state. - improve
package_namesto allow dart identifiers as package names. - fix a false-positive in
package_names(causing keywords to wrongly get flagged). - fix
avoid_classes_with_only_static_memberto check for inherited members and also flag classes with only methods. - fix
curly_braces_in_flow_control_structuresto properly flag terminatingelse-ifblocks. - improve
always_specify_typesto support type aliases. - fix a false positive in
unnecessary_string_interpolationsw/ nullable interpolated strings - fix a false positive in
avoid_function_literals_in_foreach_callsfor nullable iterables. - fix false positives in
avoid_returning_nullw/ NNBD - fix false positives in
use_late_for_private_fields_and_variablesin the presence of const constructors. - adds a new lint:
eol_at_end_of_file. - fix case-sensitive false positive in
use_full_hex_values_for_flutter_colors. - improve try-block and switch statement flow analysis for
use_build_context_synchronously. - update
use_setters_to_change_propertiesto only highlight a method name, not the entire body and doc comment. - update
unnecessary_getters_settersto allow otherwise “unnecessary” getters and setters with annotations. - update
missing_whitespace_between_adjacent_stringsto allow String interpolations at the beginning and end of String literals. - update
unnecessary_getters_settersto allow for setters with non-basic assignments (for example,??=or+=). - relax
non_constant_identifier_namesto allow for a trailing underscore. - fix false negative in
prefer_final_parameterswhere first parameter is final. - improve
directives_orderingsorting of directives with dot paths and dot-separated package names. - (internal) migrate to
SecurityLintCodeinstead of deprecatedSecurityLintCodeWithUniqueName. - (internal) fix
avoid_types_as_parameter_namesto skip field formal parameters. - fix false positives in
prefer_interpolation_to_compose_stringswhere the left operand is not a String. - fix false positives in
only_throw_errorsfor misidentified type variables. - add new lint:
depend_on_referenced_packages. - update
avoid_returning_null_for_futureto skip checks for null-safe libraries. - add new lint:
use_test_throws_matchers. - relax
sort_child_properties_lastto accept closures after child. - improve performance for
prefer_containsandprefer_is_empty. - add new lint:
noop_primitive_operations. - mark
avoid_web_libraries_in_flutteras stable. - add new lint:
prefer_final_parameters. - update
prefer_initializing_formalsto allow assignments where identifier names don’t match. - update
directives_orderingto checks ordering ofpackage:imports in code outside pub packages. - add simple reachability analysis to
use_build_context_synchronouslyto short-circuit await-discovery in terminating blocks. - update
use_build_context_synchronouslyto recognize nullable types when accessed from legacy libraries.
Pub
dart pub publishnow respects.pubignorefiles with gitignore-style rules..gitignorefiles in the repo are still respected if they are not overridden by a.pubignorein the same directory.pub no longer queries git for listing the files. This implies:
- Checked in files will now be ignored if they are included by a
.gitignorerule. - Global ignores are no longer taken into account.
- Even packages that are not in git source control will have their
.gitignorefiles respected. .gitignoreand.pubignoreis always case-insensitive on MacOs and Windows (as is default forgitrepositories).
- Checked in files will now be ignored if they are included by a
New flag
dart pub deps --jsongives a machine parsable overview of the current dependencies.New command:
dart pub cache clean. Will delete everything in your current pub cache.Commands related to a single package now takes a
--directoryoption to operate on a package in the given directory instead of the working directory.git dependencies with a relative repo url would previously be interpreted relative to the current package, even for transitive dependencies. This now fails instead.
Pub now uses a Dart library to read and write tar files. This should fix several issues we had with incompatibilities between different system
tars.PUB_HOSTED_URLcan now include a trailing slash.Incremental compilation is now used for compilation of executables from dependencies when using
dart run <package>:<command>.
Dart2JS
- Breaking Change #46545: Dart2JS emits ES6+ JavaScript by default, thereby no longer supporting legacy browsers. Passing the
--legacy-javascriptflag will let you opt out of this update, but this flag will be removed in a future release. Modern browsers will not be affected, as Dart2JS continues to support last two major releases of Edge, Safari, Firefox, and Chrome.
Dart Dev Compiler (DDC)
- Breaking Change #44154: Subtyping relations of
package:jsclasses have been changed to be more correct and consistent with Dart2JS. Likeanonymousclasses, non-anonymousclasses will no longer check the underlying type in DDC. The internal type representation of these objects have changed as well, which will affect thetoStringvalue of these types.
2.13.4 - 2021-06-28
This is a patch release that fixes:
- a Dart VM compiler crash (issue flutter/flutter#84212).
- a DDC compiler crash (issue flutter/flutter#82838).
2.13.3 - 2021-06-10
This is a patch release that fixes:
- a Dart compiler crash (issue flutter/flutter#83094).
- an analysis server deadlock causing it to stop responding to IDE requests (issue #45996).
- an analyzer crash when analyzing against
package:metav1.4.0(issue #46183).
2.13.1 - 2021-05-25
This is a patch release that fixes:
- incorrect behavior in CastMap (issue #45473).
- missing nullability from recursive type hierarchies in DDC (issue #45767).
2.13.0 - 2021-05-18****Language
Type aliases Non-function type aliases: Type aliases (names for types introduced via the
typedefkeyword) were previously restricted to only introduce names for function types. In this release, we remove this restriction and allow type aliases to name any kind of type.import 'dart:convert’;
typedef JsonMap = Map<String, dynamic>;
JsonMap parseJsonMap(String input) => json.decode(input) as JsonMap;
In addition to being usable as type annotations, type aliases that name class types can now also be used anywhere that the underlying class could be used, allowing type aliases to be used to safely rename existing classes.
class NewClassName<T> { NewClassName.create(T x); static NewClassName<T> mkOne<T>(T x) => NewClassName<T>.create(x); } @Deprecated(“Use NewClassName instead”) typedef OldClassName<T> = NewClassName<T>;
class LegacyClass extends OldClassName<int> { LegacyClass() : super.create(3); } OldClassName<int> legacyCode() { var one = OldClassName.create(1); var two = OldClassName.mkOne(2); return LegacyClass(); }
The new type alias feature is only available as part of the 2.13 language version. To use this feature, you must set the lower bound on the sdk constraint for your package to 2.13 or greater.
Core libraries****dart:collection
The
SplayTreeMapwas changed to allownullas key if thecomparefunction allows it. It now checks that a new key can be used as an argument to thecomparefunction when the member is added, even if the map is empty (in which case it just compares the key to itself).The
SplayTreeSetwas changed to checks that a new element can be used as an argument to thecomparefunction when the member is added, even if the set is empty (in which case it just compares the element to itself).
dart:developer
- Added
serverWebSocketUriproperty toServiceProtocolInfo.
Dart VM****Tools****Analyzer
Static analyses with “error” severity can once again be ignored with comments like
// ignore: codeand// ignore_for_file: code. To declare that certain analysis codes, or codes with certain severities ("error", "warning", and “info”) cannot be ignored with such comments, list them inanalysis_options.yaml, under theanalyzerheading, with a new YAML key,cannot-ignore. For example, to declare that “error” codes andunused_importcannot be ignored, write the following intoanalysis_options.yaml:analyzer: cannot-ignore: - error - unused_import
dart format
- Correct constructor initializer indentation after
requirednamed parameters.
Linter
Updated the Linter to 1.2.1, which includes:
- Improved
iterable_contains_unrelated_typeto better supportListcontent checks. - Fixed
camel_case_typesandprefer_mixinto support non-function type aliases. - Fixed
prefer_mixinto properly make exceptions fordart.collectionlegacy mixins. - Added new lints
avoid_multiple_declarations_per_line,use_if_null_to_convert_nulls_to_bools,deprecated_consistency,use_named_constants,use_build_context_synchronously(experimental). - Deprecated
avoid_as. - Migrated library to null-safety.
Other libraries****package:js
- Breaking change: It is no longer valid to use
Strings that match an@Nativeannotation in an@JS()annotation for a non-anonymous JS interop class. This led to erroneous behavior due to the way interceptors work. If you need to work with a native class, preferdart:html, an@anonymousclass, orjs_util. See issue #44211 for more details.
2.12.4 - 2021-04-15
This is a patch release that fixes a Dart VM compiler crashes when compiling initializers containing async closures (issue #45306).
2.12.3 - 2021-04-14
This is a patch release that fixes a vulnerability in dart:html related to DOM clobbering. See the vulnerability advisory for more details. Thanks again to Vincenzo di Cicco for finding and reporting this vulnerability.
2.12.2 - 2021-03-17
This is a patch release that fixes crashes reported by Flutter 2 users (issue flutter/flutter#78167).
2.12.1 - 2021-03-10
This is a patch release that fixes:
- an unhandled exception in HTTPS connections (issue #45047).
- a typing issue in the typed_data
+operator (issue #45140).
2.12.0 - 2021-03-03****Language
Breaking Change Null safety is now enabled by default in all code that has not opted out. With null safety, types in your code are non-nullable by default. Null can only flow into parts of your program where you want it. With null safety, your runtime null-dereference bugs turn into edit-time analysis errors.
You can opt out of null safety and preserve your code’s previous behavior by setting the lower bound of the SDK constraint in your pubspec to 2.11.0 or earlier to request an earlier language version. You can opt out individual Dart files by adding
// @dart=2.11to the beginning of the file.Files that are opted in to null safety may report new compile-time errors. Opting in to null safety also gives you access to other new language features:
- Smarter flow analysis and type promotion
requirednamed parameterslatevariables- The postfix
!null assertion operator - The
?..and?[]null-aware operators
Breaking Change #44660: Fixed an implementation bug where
thiswould sometimes undergo type promotion in extensions.
Core libraries****dart:async
- Add extension method
onError()onFutureto allow better typing of error callbacks.
dart:collection
Add
UnmodifiableSetViewclass, which allows users to guarantee that methods that could change underlyingSetinstance can not be invoked.Make it explicit that
LinkedListcompares elements by identity, and updatecontains()to take advantage of this.
dart:core
- Add
Set.unmodifiable()constructor, which allows users to create unmodifiableSetinstances.
dart:io
HttpRequestnow correctly follows HTTP 308 redirects (HttpStatus.permanentRedirect).
dart:isolate
- Add
debugNamepositional parameter toReceivePortandRawReceivePortconstructors, a name which can be associated with the port and displayed in tooling. - Introduce
Isolate.exit([port, message])which terminates current isolate and, ifportis specified, as a last action sends out themessageout to thatport.
dart:html
EventStreamSubscription.cancelhas been updated to retain its synchronous timing when running in both sound and unsound null safety modes. See issue #44157 for more details.
Dart VM
Breaking Change #42312:
Dart_WeakPersistentHandles no longer auto-delete themselves when the referenced object is garbage collected to avoid race conditions, but they are still automatically deleted when the isolate group shuts down.Breaking Change #42312:
Dart_WeakPersistentHandleFinalizeris renamed toDart_HandleFinalizerand had itshandleargument removed. All API functions using that type have been updated.
Foreign Function Interface (dart:ffi)
Breaking Change #44621: Invocations with a generic
TofsizeOf<T>,Pointer<T>.elementAt(),Pointer<T extends Struct>.ref, andPointer<T extends Struct>[]are being deprecated in the current stable release (2.12), and are planned to be fully removed in the following stable release (2.13). Consequently,allocateinpackage:ffiwill no longer be able to invokesizeOf<T>generically, and will be deprecated as well. Instead, theAllocatorit is introduced todart:ffi, and also requires a constantTon invocations. For migration notes see the breaking change request.Breaking Change #44622: Subtypes of
Structwithout any native member are being deprecated in the current stable release (2.12), and are planned to be fully removed in the following stable release (2.13). Migrate opaque types to extendOpaquerather thanStruct.
Dart2JS
- Remove
--no-defer-class-typesand--no-new-deferred-split.
Tools****Analyzer
Remove the
--use-fasta-parser,--preview-dart-2, and--enable-assert-initializerscommand line options. These options haven’t been supported in a while and were no-ops.Report diagnostics regarding the
@internalannotation.Improve diagnostic-reporting regarding the
@doNotStoreannotation.Introduce a diagnostic which is reported when a library member named
mainis not a function.Introduce a diagnostic which is reported when a
mainfunction’s first parameter is not a supertype ofList<String>.Introduce diagnostics for when an
// ignorecomment contains an error code which is not being reported, cannot be ignored, or is already being ignored.Report diagnostics when using [
@visibleForTesting](https://pub.dev/documentation/meta/latest/meta/ visibleForTesting-constant.html) on top-level variables.Fix false positive reports of “unused element” for top-level setters and getters.
Fix false positive reports regarding
@deprecatedfield formal parameters at their declaration.For null safety, introduce a diagnostic which reports when a null-check will always fail.
Fix false positive reports regarding optional parameters on private constructors being unused.
Introduce a diagnostic which is reported when a constructor includes duplicate field formal parameters.
Improve the “unused import” diagnostic when multiple import directives share a common prefix.
Fix false positive “unused import” diagnostic regarding an import which provides an extension method which is used.
For null safety, improve the messaging of “use of nullable value” diagnostics for eight different contexts.
Fix false positive reports regarding
@visibleForTestingmembers in a “hide” combinator of an import or export directive.Improve the messaging of “invalid override” diagnostics.
Introduce a diagnostic which is reported when
Future<T>.catchErroris called with anonErrorcallback which does not returnFutureOr<T>.
dartfmt
Don’t duplicate comments on chained if elements.
Preserve
?in initializing formal function-typed parameters.Fix performance issue with constructors that have no initializer list.
Linter
Updated the Linter to 0.1.129, which includes:
New lints:
avoid_dynamic_calls,cast_nullable_to_non_nullable,null_check_on_nullable_type_parameter,tighten_type_of_initializing_formals,unnecessary_null_checks, andavoid_type_to_string.Fix crash in
prefer_collection_literalswhen there is no static parameter element.Fix false negatives for
prefer_collection_literalswhen a LinkedHashSet or LinkedHashMap instantiation is passed as the argument to a function in any position other than the first.Fix false negatives for
prefer_collection_literalswhen a LinkedHashSet or LinkedHashMap instantiation is used in a place with a static type other than Set or Map.Update to
package_namesto allow leading underscores.Fix crashes in
unnecessary_null_checksandmissing_whitespace_between_adjacent_strings.Update to
void_checksfor null safety.Fix range error in
unnecessary_string_escapes.Fix false positives in
unnecessary_null_types.Fix to
prefer_constructors_over_static_methodsto respect type parameters.Update to
always_require_non_null_named_parametersto be null safety-aware.Update to
unnecessary_nullable_for_final_variable_declarationsto allow dynamic.Update
overridden_fieldsto not report on abstract parent fields.Fix to
unrelated_type_equality_checksfor null safety.Improvements to
type_init_formalsto allow types not equal to the field type.Updates to
public_member_apisto check generic type aliases.Fix
close_sinksto handlethis-prefixed property accesses.Fix
unawaited_futuresto handleFuturesubtypes.Performance improvements to
always_use_package_imports,avoid_renaming_method_parameters,prefer_relative_importsandpublic_member_api_docs.
Pub
Breaking: The Dart SDK constraint is now required in
pubspec.yaml. You must include a section like:environment: sdk: “>=2.10.0 <3.0.0”
See #44072.
For legacy dependencies without an SDK constraint, pub will now assume a default language version of 2.7.
The top level
pubexecutable has been deprecated. Usedart pubinstead. See dart tool.New command
dart pub addthat adds new dependencies to yourpubspec.yaml, and a correspondingdart pub removethat removes dependencies.New option
dart pub upgrade --major-versionswill update constraints in yourpubspec.yamlto match the resolvable column reported indart pub outdated. This allows users to easily upgrade to latest version for all dependencies where this is possible, even if such upgrade requires an update to the version constraint inpubspec.yaml.It is also possible to only upgrade the major version for a subset of your dependencies using
dart pub upgrade --major-versions <dependencies...>.New option
dart pub upgrade --null-safetywill attempt to update constraints in yourpubspec.yaml, such that only null-safety migrated versions of dependencies are allowed.New option
dart pub outdated --mode=null-safetythat will analyze your dependencies for null-safety.dart pub getanddart pub upgradewill highlight dependencies that have been discontinued on pub.dev.dart pub publishwill now check your pubspec keys for likely typos.dart pub upgrade package_foofetchs dependencies but ignores thepubspec.lockforpackage_foo, allowing users to only upgrade a subset of dependencies.New command
dart pub loginthat logs in to pub.dev.The
--serveroption todart pub publishanddart pub uploaderare deprecated. Usepublish_toin yourpubspec.yamlor set the$PUB_HOSTED_URLenvironment variable.pub global activateno longer re-precompiles if the current global installation was same version.The Flutter SDK constraint upper bound is now ignored in pubspecs and deprecated when publishing. See: flutter-upper-bound-deprecation.
2.10.5 - 2021-01-21
This is a patch release that fixes a crash in the Dart VM. (issue #44563).
2.10.4 - 2020-11-12
This is a patch release that fixes a crash in the Dart VM (issues #43941, flutter/flutter#43620, and Dart-Code/Dart-Code#2814).
2.10.3 - 2020-10-29
This is a patch release that fixes the following issues:
- breaking changes in Chrome 86 that affect DDC (issues #43750 and #43193).
- compiler error causing incorrect use of positional parameters when named parameters should be used instead (issues flutter/flutter#65324 and flutter/flutter#68092).
- crashes and/or undefined behavor in AOT compiled code (issues #43770 and #43786).
- AOT compilation of classes with more than 64 unboxed fields (issue flutter/flutter#67803).
2.10.2 - 2020-10-15
This is a patch release that fixes a DDC compiler crash (issue #43589).
2.10.1 - 2020-10-06
This is a patch release that fixes the following issues:
- crashes when developing Flutter applications (issue #43464).
- non-deterministic incorrect program behaviour and/or crashes (issue flutter/flutter#66672).
- uncaught TypeErrors in DDC (issue #43661).
2.10.0 - 2020-09-28****Core libraries****dart:io
- Adds
Abortmethod to classHttpClientRequest, which allows users to cancel outgoing HTTP requests and stop following IO operations. - A validation check is added to
pathof classCookie. Having characters ranging from 0x00 to 0x1f and 0x3b (“;”) will lead to aFormatException. - The
HttpClientandHttpServerclasses now have a 1 MiB limit for the total size of the HTTP headers when parsing a request or response, instead of the former 8 KiB limit for each header name and value. This limit cannot be configured at this time.
dart:typed_data
- Class
BytesBuilderis moved fromdart:iotodart:typed_data. It’s temporarily being exported fromdart:ioas well.
dart:uri
- [#42564]: Solved inconsistency in
Uri.httpsandUri.httpconstructors’queryParamstype.
Dart VM
- Breaking Change #42982:
dart_api_dl.ccis renamed todart_api_dl.cand changed to a pure C file. - Introduces
Dart_FinalizableHandles. They do auto-delete, and the weakly referred object cannot be accessed through them.
Dart2JS
- Adds support for deferred loading of types seperately from classes. This enables dart2js to make better optimization choices when deferred loading. This work is necessary to address unsoundness in the deferred loading algorithm. Currently, fixing this unsoundness would result in code bloat, but loading types seperately from classes will allow us to fix the unsoundness with only a minimal regression. To explicitly disable deferred loading of types, pass
--no-defer-class-types. See the original post on the unsoundness in the deferred loading algorithm. - Enables a new sound deferred splitting algorithm. To explicitly disable the new deferred splitting algorithm, pass
--no-new-deferred-split. See the original post on the unsoundness in the deferred loading algorithm.
Tools****dartfmt
- Don’t crash when non-ASCII whitespace is trimmed.
- Split all conditional expressions (
?:) when they are nested. - Handle
externalandabstractfields and variables.
Linter
Updated the Linter to 0.1.118, which includes:
- New lint:
unnecessary_nullable_for_final_variable_declarations. - Fixed NPE in
prefer_asserts_in_initializer_lists. - Fixed range error in
unnecessary_string_escapes. unsafe_htmlupdated to support unique error codes.- Updates to
diagnostic_describe_all_propertiesto check forDiagnosticables (notDiagnosticableMixins). - New lint:
use_late. - Fixed
unnecessary_lambdasto respect deferred imports. - Updated
public_member_api_docsto check mixins. - Updated
unnecessary_statementsto skipasexpressions. - Fixed
prefer_relative_importsto work with path dependencies.
Pub
pub runandpub global runaccepts a--(no-)-sound-null-safetyflag, that is passed to the VM.- Fix: Avoid multiple recompilation of binaries in global packages.
- Fix: Avoid exponential behaviour of error reporting from the solver.
- Fix: Refresh binstubs after recompile in global run.
2.9.3 - 2020-09-08
This is a patch release that fixes DDC to handle a breaking change in Chrome (issue #43193).
2.9.2 - 2020-08-26
This is a patch release that fixes transient StackOverflow exceptions when building Flutter applications (issue flutter/flutter#63560).
2.9.1 - 2020-08-12
This is a patch release that fixes unhandled exceptions in some Flutter applications (issue flutter/flutter#63038).
2.9.0 - 2020-08-05****Language****Core libraries****dart:async
- Adds
Stream.multiconstructor creating streams which can be listened to more than once, and where each individual listener can be controlled independently.
dart:convert
- Breaking Change #41100: When encoding a string containing unpaired surrogates as UTF-8, the unpaired surrogates will be encoded as replacement characters (
U+FFFD). When decoding UTF-8, encoded surrogates will be treated as malformed input. When decoding UTF-8 withallowMalformed: true, the number of replacement characters emitted for malformed input sequences has been changed to match the WHATWG encoding standard.
dart:io
- #42006: The signature of
exithas been changed to return theNevertype instead ofvoid. since no code will run after it, - Class
OSErrornow implementsException. This change meansOSErrorwill now be caught in catch clauses catchingExceptions. - Added
InternetAddress.tryParse. - Abstract Unix Domain Socket is supported on Linux/Android now. Using an
InternetAddresswithaddressstarting with ‘@’ and type beingInternetAddressType.Unixwill create an abstract Unix Domain Socket. - On Windows, file APIs can now handle files and directories identified by long paths (greater than 260 characters). It complies with all restrictions from Long Path on Windows. Note that
Directory.currentdoes not work with long path.
dart:html
Breaking Change:
CssClassSet.add()previously returnednullif theCssClassSetcorresponded to multiple elements. In order to align with the null-safe changes in theSetinterface, it will now returnfalseinstead. The same applies forCssClassSet.toggle.EventStreamSubscription.cancelmethod used to returnnull, but sinceStreamSubscription.cancelhas changed to be non-nullable, this method returns an emptyFutureinstead. Due to an optimization onnullFutures, this method used to complete synchronously, but now that theFutureis empty instead, it completes asynchronously, therefore potentially invalidating code that relied on the synchronous side-effect. This change will only affect code using sound null-safety. See issue #41653 for more details.Methods in
Consolehave been updated to better reflect the modern Console specification. Particularly of interest aredirandtablewhich take in extra optional arguments.
dart:mirrors
Breaking Change #42714: web compilers (dart2js and DDC) now produce a compile-time error if
dart:mirrorsis imported.Most projects should not be affected. Since 2.0.0 this library was unsupported and produced runtime errors on all its APIs. Since then several tools already reject code that use
dart:mirrorsincluding webdev and flutter tools, we expect few projects to run into this problem.
Tools****dartfmt
- Add
--fix-single-cascade-statements. - Correctly handle
varin--fix-function-typedefs. - Preserve leading indentation in fixed doc comments.
- Split outer nested control flow elements.
- Always place a blank line after script tags.
- Don’t add unneeded splits on if elements near comments.
- Indent blocks in initializers of multiple-variable declarations.
- Update the null-aware subscript syntax from
?.[]to?[].
Analyzer
- Static analyses with a severity of “error” can no longer be ignored with comments (
// ignore: codeand// ignore_for_file: code).
Linter
Updated the Linter to 0.1.117, which includes:
- New lint:
do_not_use_environment. - New lint:
exhaustive_cases. - New lint:
no_default_cases(experimental). - New lint:
sized_box_for_whitespace. - New lint:
use_is_even_rather_than_modulo. - Updated
directives_orderingto remove third party package special-casing. - Updated
prefer_is_emptyto special-case assert initializers and const contexts. - Updated
prefer_mixinto allow “legacy” SDK abstract class mixins. - Updated
sized_box_for_whitespaceto address false-positives. - Updated
type_annotate_public_apisto allow inferred types in final field assignments. - Updated
unnecessary_lambdasto check for tear-off assignability. - Updated
unsafe_htmlto use aSecurityLintCode(making it un-ignorable) and to includeWindow.open,Element.htmlandDocumentFragment.htmlin unsafe API checks. Also added checks for attributes and methods on extensions.
Dart VM
- Breaking Change #41100: When printing a string using the
printfunction, the default implementation (used when not overridden by the embedder or the current zone) will print any unpaired surrogates in the string as replacement characters (U+FFFD). Similarly, theDart_StringToUTF8function in the Dart API will convert unpaired surrogates into replacement characters.
Pub
pub runandpub global runaccepts a--enable-experimentflag enabling experiments in the Dart VM (and language).- Warn when publishing the first null-safe version of a package.
pub outdated:- If the current version of a dependency is a prerelease version, use prereleases for latest if there is no newer stable.
- Don’t require a
pubspec.lockfile. When the lockfile is missing, the Current column is empty.
pub upgrade: Show summary count of outdated packages after running. It will also only show newer packages if they are not prereleases or the package is already a prerelease.- Publishing Flutter plugins using the old plugin format is no longer allowed. Plugins using the old plugin format can still be consumed.
pub run: Fix precompilation with relativePUB_CACHEpaths (#2486).- Preserve Windows line endings in
pubspec.lockif they are already there (#2489). - Better terminal color-detection. Use colors in terminals on Windows.
- Fix git folder names in cache, allowing for ssh-style git dependencies.
- Fix: Avoid precompilation of dependencies of global packages.
2.8.4 - 2020-06-04
This is a patch release that fixes potential memory leaks in the Dart front-end (issues #42111 and #42112).
2.8.3 - 2020-05-28
This is a patch release that fixes the following issues:
- crashes in Flutter apps (issue flutter/flutter#57318).
- a regression in stack traces (issue #41907).
- re-canonicalization of constants with unboxed fields (issue flutter/flutter#57190).
2.8.2 - 2020-05-13
This is a patch release that fixes an AOT compilation bug in global transformations which manifests as a NoSuchMethod exception (issue flutter/flutter#56479).
2.8.1 - 2020-05-06
Much of the changes in this release are in preparation for non-nullable types, which will arrive in a future version. In anticipation of that, we have made a number of small but technically breaking changes to several core library APIs in order to make them easier to use in a world with non-nullable types. Almost all existing Dart code will be unaffected by these changes, but if you see unexpected failures, note the breaking changes listed below.
Language
There are no new language features in this release. There are only two minor breaking changes:
Breaking change #40675: Fixed an implementation bug where local variable inference would incorrectly use the promoted type of a type variable.
Breaking change #41362: Dart 2.0.0 made the clauses
implements Function,extends Function, orwith Functionhave no effect (spec section 19.6). We fixed an implementation bug that may be visible on some rare scenarios.
Core libraries****dart:async
Breaking change #40676: Changed the return type of
StreamSubscription.cancel()toFuture<void>. Previously, it was declared to returnFutureand was allowed to returnnullat runtime.Breaking change #40681: The
runZoned()function is split into two functions:runZoned()andrunZonedGuarded(), where the latter has a requiredonErrorparameter, and the former has none. This prepares the functions for null safety where the two functions will differ in the nullability of their return types.Breaking change #40683: Errors passed to
Completer.completeError(),Stream.addError(),Future.error(), etc. can no longer benull. These operations now synchronously throw an exception if passed anullerror.Make stack traces non-null #40130. Where methods like
completer.completeError()allow omitting a stack trace, the platform will now insert a default stack trace rather than propagate anullvalue.Error handling functions need no longer be prepared for
nullstack traces.
dart:core
Breaking change #40674: Three members on
RuneIteratorno longer returnnullwhen accessed before the first call tomoveNext(). Instead,currentandrawIndexreturn-1andcurrentAsStringreturns an empty string.Breaking change #40678: The
String.fromEnvironment()default value fordefaultValueis now an empty string instead ofnull. Likewise, the default value forint.fromEnvironment()'sdefaultValueparameter is zero. Under null safety, a constructor cannot returnnull, so this prepares these APIs for that.The class
CastErroris deprecated, and all implementation specific classes implementingTypeErrororCastErrornow implement both. In a future release,CastErrorwill be removed. See issue 40763 for details.Adds
StackTrace.emptyconstant which is the stack trace used as default stack trace when no better alternative is available.The class
TypeErrorno longer extendsAssertionError. This also means that it no longer inherits the spuriousmessagegetter which was added toAssertionErrorwhen the second operand toassertwas allowed. The value of that getter on aTypeErrorwas the same string as returned bytoString(), so it is still available.ArgumentError.checkNotNull()and theRangeErrorstatic methodscheckValueInInterval(),checkValidIndex()andcheckNotNegative()all return their first argument on success. This makes these functions more convenient to use in-line in, for example,=>function bodies or constructor initialization lists.
dart:developer
- The constructors for
TimelineTasknow accept an optionalfilterKeyparameter. If provided, the arguments for all events associated with the task will contain an entry namedfilterKey, set to the value of thefilterKeyparameter provided in the constructor. This will be used by tooling to allow for better filtering of timeline events.
dart:html
Breaking Change #39627: Changed the return type of several HTML native methods involving futures. In return types that matched
Future<List<T>>,T waschanged todynamic. These methods would have resulted in a runtime error if they were used.Breaking Change:
Node.insertAllBefore()erroneously had a return type ofNode, even though it was not returning anything. This has been corrected tovoid.
dart:io
Class
HttpParserwill no longer throw an exception when a HTTP response status code is within [0, 999]. Customized status codes in this range are now valid.Breaking change #33501: The signature of
HttpHeadersmethodsadd()andsethave been changed to:void add(String name, Object value, {bool preserveHeaderCase: false}) void set(String name, Object value, {bool preserveHeaderCase: false})
Setting
preserveHeaderCasetotruepreserves the case of thenameparameter instead of converting it to lowercase. TheHttpHeader.forEach()method provides the current case of each header.This is breaking only for classes extending or implementing
HttpHeadersand having their ownaddorsetmethods without thebool preserveHeaderCasenamed parameter.Breaking change #40702: The
Socketclass now throws aSocketExceptionif the socket has been explicitly destroyed or upgraded to a secure socket upon setting or getting socket options. Previously, setting a socket option would be ignored and getting a socket option would returnnull.Breaking change #40483: The
Processclass now throws aStateErrorif the process is detached (ProcessStartMode.detachedandProcessStartMode.detachedWithStdio) upon accessing theexitCodegetter. It now also throws when not connected to the child process’s stdio (ProcessStartMode.detachedandProcessStartMode.inheritStdio) upon accessing thestdin,stdout, andstderrgetters. Previously, these getters would all returnnull.Breaking change #40706: The dummy object returned if
FileStat.stat()orFileStat.statSync()fail now contains Unix epoch timestamps instead ofnullfor theaccessed,changed, andmodifiedgetters.Breaking change #40709: The
HeaderValueclass now parses more strictly in two invalid edge cases. This is the class used to parse the semicolon delimited parameters used in theAccept,Authorization,Content-Type, and other such HTTP headers.The empty parameter value without double quotes (which is not allowed by the standards) is now parsed as the empty string rather than
null. E.g.HeaderValue.parse("v;a=").parametersnow gives{"a": ""}rather than{"a": null}.Invalid inputs with unbalanced double quotes are now rejected. E.g.
HeaderValue.parse('v;a="b').parameterswill now throw aHttpExceptioninstead of giving{"a": "b"}.The
HeaderValue.toString()method now supports parameters withnullvalues by omitting the value.HeaderValue("v", {"a": null, "b": "c"}).toString()now givesv; a; b=c. This behavior can be used to implement some features in theAcceptandSec-WebSocket-Extensionsheaders.Likewise the empty value and values using characters outside of RFC 7230 tokens are now correctly implemented by double quoting such values with escape sequences. For example:
HeaderValue("v", {"a": "A", "b": "(B)", "c": "", "d": "ø", "e": "\\\""}).toString()
Gives:
v;a=A;b="(B)";c="";d="ø";e="\\\"".Unix domain sockets are now supported on Linux, Android and MacOS, which can be used by passing a
InternetAddressofInternetAddressType.Unixinto theconnect(),startConnect()andbind()methods. Theportargument in those methods will be ignored. Theportgetter always returns 0 for Unix domain sockets.Class
InternetAddressTypegains one more optionUnix, which represents a Unix domain address.Class
InternetAddress:InternetAddressconstructor gains an optionaltypeparameter. To create a Unix domain address,typeis set toInternetAddressType.Unixandaddressis a file path.InternetAddressgains a new constructorfromRawAddress()that takes an address in byte format for Internet addresses or raw file path for Unix domain addresses.
Breaking change #40681: The static methods
runZoned()andrunWithHttpOverrides()onHttpOverridesno longer acceptzoneSpecificationandonErrorparameters. Use therunZoned()orrunZonedGuarded()functions fromdart:asyncdirectly if needing to specify those.Class
HttpClientandHttpServer, when receivingHttpRequestorHttpClientResponse, will now put a 8K size limit on its header fields and values.
dart:mirrors
- Added
MirrorSystem.neverType.
Dart VM
Added
Dart_TypeDynamic,Dart_TypeVoidandDart_TypeNever. Typedynamiccan no longer by reached usingDart_GetType(dart:core, dynamic).Added the following methods to the VM embedding API:
Dart_GetNonNullableType()Dart_GetNullableType()Dart_TypeToNonNullable()Dart_TypeToNullable()Dart_IsLegacyType()Dart_IsNonNullableType()Dart_IsNullableType()
Foreign Function Interface (dart:ffi)
- Breaking Change: Changed
Pointer.asFunction()andDynamicLibrary.lookupFunction()to extension methods. Invoking them dynamically previously already threw an exception, so the runtime behavior stays the same. However, the extension methods are only visible ifdart:ffiis imported directly. This breaks code wheredart:ffiis not directly imported. To fix, add:
Tools****Dart Dev Compiler (DDC)
We fixed several inconsistencies between DDC and Dart2JS so that users less frequently encounter code that is accepted by one compiler but then fails in the other.
Breaking Change: Deleted the legacy (analyzer based) version of DDC. For additional details see the announcement.
The
--kerneloption is now ignored and defaults to true. There is no longer any way to invoke the legacy (analyzer based) version of DDC.Command line arguments that were only used for the legacy DDC have been removed.
The pre-compiled
dart_sdk.jsartifacts generated by legacy DDC have been deleted fromdart-sdk/lib/dev_compilerin favor of the versions located atdart-sdk/lib/dev_compiler/kernel.
Breaking Change: Functions passed to JavaScript using the recommended
package:jsinterop specification must now be wrapped with a call toallowInterop. This behavior was always enforced by Dart2JS, but was not enforced consistently by DDC. It is now enforced by both.Breaking Change: Constructors in
@JS()classes must be marked withexternal. Previously theexternalcould be omitted in some cases with DDC but doing so would cause incorrect behavior with Dart2JS.JS interop classes with an index operator are now static errors.
All remaining support from the
dart:mirrorslibrary has been removed. Use of this library on the web has been unsupported and prevented by the Dart build systems since Dart v2.0.0. All known exception cases have been cleaned up. This change makes DDC and Dart2JS now behave consistently.The library can still be imported on web apps, but all APIs throw. In a future breaking change release, imports to this library will likely become a compile-time error.
Dart2JS
A new representation of runtime types is enabled by default.
This change is part of a long term goal of making runtime checks cheaper and more flexible for upcoming changes in the language. The new representation disentangles how types and classes are represented and makes types first-class to the compiler. This makes it possible to do certain kind of optimizations on type checks that were not possible before and will enable us to model non-nullable types in the near future.
This change should not affect the semantics of your application, but it has some relatively small visible effects that we want to highlight:
Types are now canonicalized, this fixes a long standing bug that Types could not be used in switch cases (issue 17207).
Code-size changes may be visible, but the difference is small overall. It is more visible on smaller apps because the new implementation includes more helper methods. On large apps we have even seen an overall code-size reduction.
Certain checks are a lot faster. This is less noticeable if you are compiling apps with
-O3where checks are omitted altogether. Even with-O3, the performance of someischecks used by your app may improve.When using
-O3and-O4incorrect type annotations could surface as errors. The old type representation was accidentally lenient on some invalid type annotations. We have only encountered this issue on programs that were not tested properly at the js-interop program boundary.Type.toString()has a small change that is rarely visible. For a long time, Dart2JS has had support to erase unused type variables. Today, when Dart2JS is given--lax-runtime-type-to-string(currently included in-O2,-O3, and-O4) and it decides to erase the type variable of a classFoo<T>, then it compiles expressions likefoo.runtimeType.toString()to printFoo. With the new representation, this will showFoo<erased>instead. This change may be visible in error messages produced by type checks involving erased types.
Because types and classes are represented separately, we will likely reevaluate restrictions of deferred libraries in the near future. For example, we could support referring to deferred types because types can be downloaded while classes are not.
In the unlikely case you run into any issues, please file a bug so we can investigate. You can temporarily force the old type representation by passing --use-old-rti to Dart2JS if necessary, but our goal is to delete the old type representation soon.
In addition, we fixed some inconsistencies between Dart2JS and DDC:
JS interop classes with an index operator are now static errors instead of causing invalid code in Dart2JS.
Breaking Change: The subtyping rule for generic functions is now more forgiving. Corresponding type parameter bounds now only need to be mutual subtypes rather than structurally equal up to renaming of bound type variables and equating all top types.
Breaking Change: Types are now normalized. See normalization for the full specification. Types will now be printed in their normal form, and mutual subtypes with the same normal form will now be considered equal.
Breaking Change: Constructors in
@JS()classes must be marked withexternal. Previously, the external could be omitted for unused constructors. Omittingexternalfor a constructor which is used would cause incorrect behavior at runtime, now omitting it on any constructor is a static error.
Other dart2js changes:
- Breaking Change: The
--package-rootflag, which was hidden and disabled in Dart 2.0.0, has been completely removed. Passing this flag will now causedart2jsto fail.
Linter
Updated the Linter to 0.1.114, which includes:
- Fixed
avoid_shadowing_type_parametersto support extensions and mixins. - Updated
non_constant_identifier_namesto allow named constructors made up of only underscores (_). - Updated
avoid_unused_constructor_parametersto ignore unused params named in all underscores (_).
Analyzer
- Removed support for the deprecated analysis options file name
.analysis_options.
Pub
Added
pub outdatedcommand which lists outdated package dependencies, and gives advice on how to upgrade.pub getandpub upgradenow fetch version information about hosted dependencies in parallel, improving the time package resolution performance.pub getandpub upgradeno longer precompile executables from dependencies by default. Instead they are precompiled on firstpub run. Usepub get --precompileto get the previous behavior.Fixed missing retries of DNS failures during
pub get.If code contains imports for packages not listed in the package’s
pubspec.yamlthenpub publishwill reject the package.pub publishno longer requires the presence of ahomepagefield, if therepositoryfield is provided.pub publishwarns if non-pre-release packages depends on pre-release packages or pre-release Dart SDKs.Relative paths in
pubspec.locknow use/also on Windows to make the file sharable between machines.Fixed language version in
.dart_tool/package_config.jsonfor packages without an explicit SDK constraint. Pub now writes an empty language version where before the language version of the current SDK would be used.%LOCALAPPDATA%is now preferred over%APPDATA%when creating a pub cache directory on Windows.%LOCALAPPDATA%is not copied when users roam between devices.pub publishwarns if LICENSE and README.md files are not called those exact names.pub repair cachedownloads hosted packages in parallel.
2.7.2 - 2020-03-23
This is a patch release that addresses a vulnerability in dart:html NodeValidator related to DOM clobbering of previousSibling. See the vulnerability advisory for more details. Thanks to Vincenzo di Cicco for finding and reporting this issue.
This release also improves compatibility with ARMv8 processors (issue 40001) and dart:io stability (issue 40589).
2.7.1 - 2020-01-23
This is a patch release that improves dart2js compile-time (issue 40217).
Breaking Change: The Dart SDK for macOS is now only available for x64 (issue 39810).
2.7.0 - 2019-12-11
Extension methods – which we shipped in preview in 2.6.0 – are no longer in preview, and are now officially supported as of 2.7.0. Learn more about them here:
https://medium.com/dartlang/extension-methods-2d466cd8b308
Language
Breaking Change: Static extension members are accessible when imported with a prefix (issue 671). In the extension method preview launch, importing a library with a prefix hid all extension members in addition to hiding the extension name, thereby making them inaccessible in the importing library except via the explicit override syntax. Based on user feedback, we have changed this to make extensions methods accessible even when imported with a prefix.
```dart // "thing.dart" class Thing { } extension Show on Thing { void show() { print("This is a thing"); } } // "client.dart" import "thing.dart" as p; void test() { p.Thing().show(); // Previously an error, now resolves to Show.show } ```
Core libraries****dart:io
- Breaking change: Added
IOOverrides.serverSocketBindto aid in writing tests that wish to mockServerSocket.bind.
dart:typed_data
- Added new constructors,
.sublistView(TypedData, [start, end])to allTypedDataclasses. The constructor makes it easier, and less error-prone, to create a view of (a slice of) anotherTypedDataobject.
Dart VM
- New fields added to existing instances by a reload will now be initialized lazily, as if the field was a late field. This makes the initialization order program-defined, whereas previously it was undefined.
Tools****Linter
The Linter was updated to 0.1.104, which includes:
- updated
unnecessary_overridesto allow overrides when annotations (besides@overrideare specified) - updated
file_namesto allow names w/ leading_'s (and improved performance) - new lint:
unnecessary_final
Pub
pub getgenerates.dart_tool/package_config.jsonin addition to.packagesto support language versioning.pub publishnow warns about the old flutter plugin registration format.pub publishnow warns about theauthorfield in pubspec.yaml being. obsolete.Show a proper error message when
gitis not installed.
2.6.1 - 2019-11-11
This is a patch release that reduces dart2js memory usage (issue 27883), improves stability on arm64 (issue 39090) and updates the Dart FFI documentation.
2.6.0 - 2019-11-05****Language
[IN PREVIEW] Static extension members: A new language feature allowing specially declared static functions to be invoked like instance members on expressions of appropriate static types is available in preview.
Static extension members are declared using a new
extensiondeclaration. Example:extension MyFancyList<T> on List<T> { /// Whether this list has an even length. bool get isLengthEven => this.length.isEven;
/// Whether this list has an odd length. bool get isLengthOdd => !isLengthEven;
/// List of values computed for each pairs of adjacent elements. /// /// The result always has one element less than this list, /// if this list has any elements. List<R> combinePairs<R>(R Function(T, T) combine) => [for (int i = 1; i < this.length; i++) combine(this[i - 1], this[i])]; }
Extension declarations cannot declare instance fields or constructors. Extension members can be invoked explicitly,
MyFancyList(intList).isLengthEven), or implicitly,intList.isLengthEven, where the latter is recognized byintListmatching theList<T>“on” type of the declaration. An extension member cannot be called implicitly on an expression whose static type has a member with the same base-name. In that case, the interface member takes precedence. If multiple extension members apply to the same implicit invocation, the most specific one is used, if there is one such.Extensions can be declared on any type, not just interface types.
extension IntCounter on int { /// The numbers from this number to, but not including, [end]. Iterable<int> to(int end) sync* { int step = end < this ? -1 : 1; for (int i = this; i != end; i += step) yield i; } }
extension CurryFunction<R, S, T> on R Function(S, T) { /// Curry a binary function with its first argument. R Function(T) curry(S first) => (T second) => this(first, second); }
Breaking change #37985: Inference is changed when using
Nullvalues in aFutureOrcontext. Namely, constraints of the forms similar toNull<:FutureOr<T>now yieldNullas the solution forT. For example, the following code will now print "Null", and it was printing “dynamic” before (note that the anonymous closure() {}in the example hasNullas its return type):import 'dart:async’;
void foo<T>(FutureOr<T> Function() f) { print(T); }
main() { foo(() {}); }
Core libraries
- Default values of parameters of abstract methods are no longer available via
dart:mirrors.
dart:developer
- Added optional
parentparameter toTimelineTaskconstructor to allow for linking of asynchronous timeline events in the DevTools timeline view.
dart:io
- Added
enableTimelineLoggingproperty toHttpClientwhich, when enabled, will post HTTP connection and request information to the developer timeline for allHttpClientinstances.
Dart VM
- Added a new tool for AOT compiling Dart programs to native, self-contained executables. See https://dart.dev/tools/dart2native for additional details.
Foreign Function Interface (dart:ffi)
- Breaking change: The API now makes use of static extension members. Static extension members enable the
dart:ffiAPI to be more precise with types, and provide convenient access to memory through extension getters and setters. The extension members onPointerprovide.valueand.value =for accessing the value in native memory and[]and[]=for indexed access. The methodasExternalTypedDatahas been replaced withasTypedListextension methods. And finally,Structsdo no longer have a type argument and are accessed using the extension member.refonPointer. These changes makes the code usingdart:ffimuch more concise. - Breaking change: The memory management has been removed (
Pointer.allocateandPointer.free). Instead, memory management is available in package:ffi. - Breaking change:
Pointer.offsetBywas removed, usecastandelementAtinstead. - Faster memory load and stores.
- The dartanalyzer (commandline and IDEs) now reports
dart:ffistatic errors. - Callbacks are now supported in AOT (ahead-of-time) compiled code.
Dart for the Web****Dart Dev Compiler (DDC)
- Kernel DDC will no longer accept non-dill files as summary inputs.
- Removed support for the deprecated web extension.
Tools****Linter
The Linter was updated to 0.1.101, which includes:
- fixed
diagnostic_describe_all_propertiesto flag properties inDiagnosticables with no debug methods defined - fixed
noSuchMethodexception incamel_case_extensionswhen analyzing unnamed extensions - fixed
avoid_printto catch tear-off usage - new lint:
avoid_web_libraries_in_flutter(experimental) - (internal) prepare
unnecessary_lambdasfor comingMethodInvocationvs.FunctionExpressionInvocationchanges
2.5.2 - 2019-10-08
This is a patch release with properly signed binaries required for macOS Catalina (Issue 38765).
2.5.1 - 2019-09-27
This is a patch release that prevents type inference failures in the analyzer (Issue 38365).
2.5.0 - 2019-09-10****Language
The set of operations allowed in constant expressions has been expanded as described in the constant update proposal. The control flow and spread collection features shipped in Dart 2.3 are now also supported in constants as described in the specification here.
Specifically, it is now valid to use the following operations in constant expressions under the appropriate conditions:
- Casts (
e as T) and type tests (e is T). - Comparisons to
null, even for types which override the==operator. - The
&,|, and^binary operators on booleans. - The spread operators (
...and...?). - An
ifelement in a collection literal.
// Example: these are now valid constants. const Object i = 3; const list = [i as int]; const set = {if (list is List<int>) …list}; const map = {if (i is int) i : "int"};
In addition, the semantics of constant evaluation has been changed as follows:
- The
&&operator only evaluates its second operand if the first evaluates to true. - The
||operator only evaluates its second operand if the first evaluates to false. - The
??operator only evaluates its second operand if the first evaluates to null. - The conditional operator (
e ? e1 : e2) only evaluates one of the two branches, depending on the value of the first operand.
// Example: x is now a valid constant definition. const String s = null; const int x = (s == null) ? 0 : s.length;
Core libraries
Breaking change #36900: The following methods and properties across various core libraries, which used to declare a return type of
List<int>, were updated to declare a return type ofUint8List:BytesBuilder.takeBytes()BytesBuilder.toBytes()Datagram.dataFile.readAsBytes()(Future<Uint8List>)File.readAsBytesSync()InternetAddress.rawAddressRandomAccessFile.read()(Future<Uint8List>)RandomAccessFile.readSync()RawSocket.read()Utf8Codec.encode()(andUtf8Encoder.convert())
In addition, the following classes were updated to implement
Stream<Uint8List>rather thanStream<List<int>>:HttpRequestSocket
Possible errors and how to fix them
The argument type ‘Utf8Decoder’ can’t be assigned to the parameter type ‘StreamTransformer<Uint8List, dynamic>’
type ‘Utf8Decoder’ is not a subtype of type ‘StreamTransformer’ of 'streamTransformer’"
You can fix these call sites by updating your code to use
StreamTransformer.bind()instead ofStream.transform(), like so:Before:
stream.transform(utf8.decoder)After:utf8.decoder.bind(stream)The argument type ‘IOSink’ can’t be assigned to the parameter type ‘StreamConsumer’
type ‘_IOSinkImpl’ is not a subtype of type ‘StreamConsumer’ of ‘streamConsumer’
You can fix these call sites by casting your stream instance to a
Stream<List<int>>before calling.pipe()on the stream, like so:Before:
stream.pipe(consumer)After:stream.cast<List<int>>().pipe(consumer)
Finally, the following typed lists were updated to have their `sublist()` methods declare a return type that is the same as the source list:
* `Int8List.sublist()` → `Int8List`
* `Int16List.sublist()` → `Int16List`
* `Int32List.sublist()` → `Int32List`
* `Int64List.sublist()` → `Int64List`
* `Int32x4List.sublist()` → `Int32x4List`
* `Float32List.sublist()` → `Float32List`
* `Float64List.sublist()` → `Float64List`
* `Float32x4List.sublist()` → `Float32x4List`
* `Float64x2List.sublist()` → `Float64x2List`
* `Uint8List.sublist()` → `Uint8List`
* `Uint8ClampedList.sublist()` → `Uint8ClampedList`
* `Uint16List.sublist()` → `Uint16List`
* `Uint32List.sublist()` → `Uint32List`
* `Uint64List.sublist()` → `Uint64List`
dart:async
- Add
valueanderrorconstructors onStreamto allow easily creating single-value or single-error streams.
dart:core
- Update
Uriclass to support RFC6874: “%25” or “%” can be appended to the end of a valid IPv6 representing a Zone Identifier. A valid zone ID consists of unreversed character or Percent encoded octet, which was defined in RFC3986. IPv6addrz = IPv6address “%25” ZoneID
dart:io
Breaking change #37192: The
Cookieclass’s constructor’snameandvalueoptional positional parameters are now mandatory. The signature changes from:Cookie([String name, String value])to
Cookie(String name, String value)However, it has not been possible to set
nameandvalueto null since Dart 1.3.0 (2014) where a bug made it impossible. Any code not using both parameters or setting any to null would necessarily get a noSuchMethod exception at runtime. This change catches such erroneous uses at compile time. Since code could not previously correctly omit the parameters, this is not really a breaking change.Breaking change #37192: The
Cookieclass’snameandvaluesetters now validates that the strings are made from the allowed character set and are not null. The constructor already made these checks and this fixes the loophole where the setters didn’t also validate.
Dart VM****Tools****Pub
- Clean-up invalid git repositories in cache when fetching from git.
- Breaking change #36765: Packages published to pub.dev can no longer contain git dependencies. These packages will be rejected by the server.
Linter
The Linter was updated to 0.1.96, which includes:
- fixed false positives in
unnecessary_parens - various changes to migrate to preferred analyzer APIs
- rule test fixes
Dartdoc
Dartdoc was updated to 0.28.4; this version includes several fixes and is based on a newer version of the analyzer package.
2.4.1 - 2019-08-07
This is a patch release that fixes a performance regression in JIT mode, as well as a potential crash of our AOT compiler.
Dart VM
Fixed a performance regression where usage of
Int32Listcould trigger repeated deoptimizations in JIT mode (Issue 37551).Fixed a bug where usage of a static getter with name
lengthcould cause a crash in our AOT compiler (Issue 35121).
Dart Dev Compiler (DDC)
Callbacks passed to JS and wrapped with allowInterop or allowInteropCaptureThis are now strict about argument counts and argument types. This may mean that tests which were previously passing and relying on loose argument checking (too many or too few arguments, or arguments with too specific types like List<Something> instead of List<dynamic>) may start failing. This changes makes DDC behave more like dart2js with the default flags.
2.4.0 - 2019-06-27****Core libraries****dart:isolate
TransferableTypedDataclass was added to facilitate faster cross-isolate communication ofUint8Listdata.Breaking change:
Isolate.resolvePackageUriwill always throw anUnsupportedErrorwhen compiled with dart2js or DDC. This was the only remaining API indart:isolatethat didn’t automatically throw since we dropped support for this library in Dart 2.0.0. Note that the API already throws in dart2js if the API is used directly without manually setting up adefaultPackagesBasehook.
dart:developer
- Exposed
result,errorCodeanderrorDetailgetters inServiceExtensionResponseto allow for better debugging of VM service extension RPC results.
dart:io
Fixed
Cookieclass interoperability with certain websites by allowing the cookie values to be the empty string (Issue 35804) and not stripping double quotes from the value (Issue 33327) in accordance with RFC 6265.#36971: The
HttpClientResponseinterface has been extended with the addition of a newcompressionStategetter, which specifies whether the body of a response was compressed when it was received and whether it has been automatically uncompressed viaHttpClient.autoUncompress.As part of this change, a corresponding new enum was added to
dart:io:HttpClientResponseCompressionState.This is a breaking change for those implementing the
HttpClientResponseinterface as subclasses will need to implement the new getter.
dart:async
- Breaking change #36382: The
await forallowednullas a stream due to a bug inStreamIteratorclass. This bug has now been fixed.
dart:core
#36171: The
RegExpinterface has been extended with two new constructor named parameters:unicode:(bool, default:false), for Unicode patternsdotAll:(bool, default:false), to change the matching behavior of ‘.’ to also match line terminating characters.
Appropriate properties for these named parameters have also been added so their use can be detected after construction.
In addition,
RegExpmethods that originally returnedMatchobjects now return a more specific subtype,RegExpMatch, which adds two features:Iterable<String> groupNames, a property that contains the names of all named capture groupsString namedGroup(String name), a method that retrieves the match for the given named capture group
This is a breaking change for implementers of the
RegExpinterface. Subclasses will need to add the new properties and may have to update the return types on overridden methods.
Language
- Breaking change #35097: Covariance of type variables used in super-interfaces is now enforced. For example, the following code was previously accepted and will now be rejected:
class A<X> {}; class B<X> extends A<void Function(X)> {};
- The identifier
asynccan now be used in asynchronous and generator functions.
Dart for the Web****Dart Dev Compiler (DDC)
- Improve
NoSuchMethoderrors for failing dynamic calls. Now they include specific information about the nature of the error such as:- Attempting to call a null value.
- Calling an object instance with a null
call()method. - Passing too few or too many arguments.
- Passing incorrect named arguments.
- Passing too few or too many type arguments.
- Passing type arguments to a non-generic method.
Tools****Linter
The Linter was updated to 0.1.91, which includes the following changes:
- Fixed missed cases in
prefer_const_constructors - Fixed
prefer_initializing_formalsto no longer suggest API breaking changes - Updated
omit_local_variable_typesto allow explicitdynamics - Fixed null-reference in
unrelated_type_equality_checks - New lint:
unsafe_html - Broadened
prefer_null_aware_operatorsto work beyond local variables. - Added
prefer_if_null_operators. - Fixed
prefer_containsfalse positives. - Fixed
unnecessary_parenthesisfalse positives. - Fixed
prefer_asserts_in_initializer_listsfalse positives - Fixed
curly_braces_in_flow_control_structuresto handle more cases - New lint:
prefer_double_quotes - New lint:
sort_child_properties_last - Fixed
type_annotate_public_apisfalse positive forstatic constinitializers
Pub
pub publishwill no longer warn about missing dependencies for import statements inexample/.- OAuth2 authentication will explicitly ask for the
openidscope.
2.3.2 - 2019-06-11
This is a patch version release with a security improvement.
Security vulnerability
Security improvement: On Linux and Android, starting a process with
Process.run,Process.runSync, orProcess.startwould first search the current directory before searchingPATH(Issue 37101). This behavior effectively put the current working directory in the front ofPATH, even if it wasn’t in thePATH. This release changes that behavior to only searching the directories in thePATHenvironment variable. Operating systems other than Linux and Android didn’t have this behavior and aren’t affected by this vulnerability.This vulnerability could result in execution of untrusted code if a command without a slash in its name was run inside an untrusted directory containing an executable file with that name:
Process.run("ls", workingDirectory: “/untrusted/directory”)
This would attempt to run
/untrusted/directory/lsif it existed, even though it is not in thePATH. It was always safe to instead use an absolute path or a path containing a slash.This vulnerability was introduced in Dart 2.0.0.
2.3.1 - 2019-05-21
This is a patch version release with bug fixes.
Tools****dart2js
- Fixed a bug that caused the compiler to crash when it compiled UI-as-code features within fields (Issue 36864).
2.3.0 - 2019-05-08
The focus in this release is on the new “UI-as-code” language features which make collections more expressive and declarative.
Language
Flutter is growing rapidly, which means many Dart users are building UI in code out of big deeply-nested expressions. Our goal with 2.3.0 was to make that kind of code easier to write and maintain. Collection literals are a large component, so we focused on three features to make collections more powerful. We’ll use list literals in the examples below, but these features also work in map and set literals.
Spread
Placing ... before an expression inside a collection literal unpacks the result of the expression and inserts its elements directly inside the new collection. Where before you had to write something like this:
CupertinoPageScaffold( child: ListView(children: [ Tab2Header() ]…addAll(buildTab2Conversation()) …add(buildFooter())), );
Now you can write this:
CupertinoPageScaffold( child: ListView(children: [ Tab2Header(), …buildTab2Conversation(), buildFooter() ]), );
If you know the expression might evaluate to null and you want to treat that as equivalent to zero elements, you can use the null-aware spread ...?.
Collection if
Sometimes you might want to include one or more elements in a collection only under certain conditions. If you’re lucky, you can use a ?: operator to selectively swap out a single element, but if you want to exchange more than one or omit elements, you are forced to write imperative code like this:
Widget build(BuildContext context) { var children = [ IconButton(icon: Icon(Icons.menu)), Expanded(child: title) ];
if (isAndroid) { children.add(IconButton(icon: Icon(Icons.search))); }
return Row(children: children); }
We now allow if inside collection literals to conditionally omit or (with else) swap out an element:
Widget build(BuildContext context) { return Row( children: [ IconButton(icon: Icon(Icons.menu)), Expanded(child: title), if (isAndroid) IconButton(icon: Icon(Icons.search)), ], ); }
Unlike the existing ?: operator, a collection if can be composed with spreads to conditionally include or omit multiple items:
Widget build(BuildContext context) { return Row( children: [ IconButton(icon: Icon(Icons.menu)), if (isAndroid) …[ Expanded(child: title), IconButton(icon: Icon(Icons.search)), ] ], ); }
Collection for
In many cases, the higher-order methods on Iterable give you a declarative way to modify a collection in the context of a single expression. But some operations, especially involving both transforming and filtering, can be cumbersome to express in a functional style.
To solve this problem, you can use for inside a collection literal. Each iteration of the loop produces an element which is then inserted in the resulting collection. Consider the following code:
var command = [ engineDartPath, frontendServer, …fileSystemRoots.map((root) => “–filesystem-root=$root”), …entryPoints .where((entryPoint) => fileExists(“lib/$entryPoint.json”)) .map((entryPoint) => “lib/$entryPoint”), mainPath ];
With a collection for, the code becomes simpler:
var command = [ engineDartPath, frontendServer, for (var root in fileSystemRoots) "–filesystem-root=$root", for (var entryPoint in entryPoints) if (fileExists(“lib/$entryPoint.json”)) "lib/$entryPoint", mainPath ];
As you can see, all three of these features can be freely composed. For full details of the changes, see the official proposal.
Note: These features are not currently supported in const collection literals. In a future release, we intend to relax this restriction and allow spread and collection if inside const collections.
Core library changes****dart:isolate
- Added
debugNameproperty toIsolate. - Added
debugNameoptional parameter toIsolate.spawnandIsolate.spawnUri.
dart:core
- RegExp patterns can now use lookbehind assertions.
- RegExp patterns can now use named capture groups and named backreferences. Currently, named group matches can only be retrieved in Dart either by the implicit index of the named group or by downcasting the returned Match object to the type RegExpMatch. The RegExpMatch interface contains methods for retrieving the available group names and retrieving a match by group name.
Dart VM
The VM service now requires an authentication code by default. This behavior can be disabled by providing the
--disable-service-auth-codesflag.Support for deprecated flags '-c’ and ‘–checked’ has been removed.
Dart for the Web****dart2js
A binary format was added to dump-info. The old JSON format is still available and provided by default, but we are starting to deprecate it. The new binary format is more compact and cheaper to generate. On some large apps we tested, it was 4x faster to serialize and used 6x less memory.
To use the binary format today, use --dump-info=binary, instead of --dump-info.
What to expect next?
The visualizer tool will not be updated to support the new binary format, but you can find several command-line tools at
package:dart2js_infothat provide similar features to those in the visualizer.The command-line tools in
package:dart2js_infoalso work with the old JSON format, so you can start using them even before you enable the new format.In a future release
--dump-infowill default to--dump-info=binary. At that point, there will be an option to fallback to the JSON format, but the visualizer tool will be deprecated.A release after that, the JSON format will no longer be available from dart2js, but may be available from a command-line tool in
package:dart2js_info.
Tools****dartfmt
- Tweak set literal formatting to follow other collection literals.
- Add support for “UI as code” features.
- Properly format trailing commas in assertions.
- Improve indentation of adjacent strings in argument lists.
Linter
The Linter was updated to 0.1.86, which includes the following changes:
- Added the following lints:
prefer_inlined_adds,prefer_for_elements_to_map_fromIterable,prefer_if_elements_to_conditional_expressions,diagnostic_describe_all_properties. - Updated
file_namesto skip prefixed-extension Dart files (.css.dart,.g.dart, etc.). - Fixed false positives in
unnecessary_parenthesis.
Pub
- Added a CHANGELOG validator that complains if you
pub publishwithout mentioning the current version. - Removed validation of library names when doing
pub publish. - Added support for
pub global activateing package from a custom pub URL. - Added subcommand:
pub logout. Logs you out of the current session.
Dart native
Initial support for compiling Dart apps to native machine code has been added. Two new tools have been added to the bin folder of the Dart SDK:
dart2aot: AOT (ahead-of-time) compiles a Dart program to native machine code. The tool is supported on Windows, macOS, and Linux.dartaotruntime: A small runtime used for executing an AOT compiled program.
2.2.0 - 2019-02-26****Language
Sets now have a literal syntax like lists and maps do:
Using curly braces makes empty sets ambiguous with maps:
var collection = {}; // Empty set or map?
To avoid breaking existing code, an ambiguous literal is treated as a map. To create an empty set, you can rely on either a surrounding context type or an explicit type argument:
// Variable type forces this to be a set: Set<int> set = {};
// A single type argument means this must be a set: var set2 = <int>{};
Set literals are released on all platforms. The set-literals experiment flag has been disabled.
Tools****Analyzer
The
DEPRECATED_MEMBER_USEhint was split into two hints:DEPRECATED_MEMBER_USEreports on usage of@deprecatedmembers declared in a different package.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGEreports on usage of@deprecatedmembers declared in the same package.
Linter
Upgraded the linter to 0.1.82 which adds the following improvements:
- Added
provide_deprecation_message, anduse_full_hex_values_for_flutter_colors,prefer_null_aware_operators. - Fixed
prefer_const_declarationsset literal false-positives. - Updated
prefer_collection_literalsto support set literals. - Updated
unnecessary_parenthesisplay nicer with cascades. - Removed deprecated lints from the “all options” sample.
- Stopped registering "default lints".
- Fixed
hash_and_equalsto respecthashCodefields.
Other libraries****package:kernel
Breaking change: The
klassgetter on theInstanceConstantclass in the Kernel AST API has been renamed toclassNodefor consistency.Breaking change: Updated
Linkimplementation to utilize true symbolic links instead of junctions on Windows. Existing junctions will continue to work with the newLinkimplementation, but all new links will create symbolic links.To create a symbolic link, Dart must be run with administrative privileges or Developer Mode must be enabled, otherwise a
FileSystemExceptionwill be raised with errno set toERROR_PRIVILEGE_NOT_HELD(Issue 33966).
2.1.1 - 2019-02-18
This is a patch version release. Again, the team’s focus was mostly on improving performance and stability after the large changes in Dart 2.0.0. In particular, dart2js now always uses the “fast startup” emitter and the old emitter has been removed.
There are a couple of very minor breaking changes:
In
dart:io, adding to a closedIOSinknow throws aStateError.On the Dart VM, a soundness hole when using
dart:mirrorsto reflectively invoke a method in an incorrect way that violates its static types has been fixed (Issue 35611).
Language
This release has no language changes.
Core library****dart:core
- Made
DateTime.parse()also recognize,as a valid decimal separator when parsing from a string (Issue 35576).
dart:html
Added methods
Element.removeAttribute,Element.removeAttributeNS,Element.hasAttributeandElement.hasAttributeNS. (Issue 35655).Improved dart2js compilation of
element.attributes.remove(name)to generateelement.removeAttribute(name), so that there is no performance reason to migrate to the above methods.Fixed a number of
dart:htmlbugs:- Fixed HTML API’s with callback typedef to correctly convert Dart functions to JS functions (Issue 35484).
- HttpStatus constants exposed in
dart:html(Issue 34318). - Expose DomName
ondblclickanddblclickEventfor Angular analyzer. - Fixed
removeAllonclasses;elementsparameter should beIterable<Object>to match Set’sremoveAllnotIterable<E>(Issue 30278). - Fixed a number of methods on DataTransferItem, Entry, FileEntry and DirectoryEntry which previously returned NativeJavaScriptObject. This fixes handling drag/drop of files/directories (Issue 35510).
- Added ability to allow local file access from Chrome browser in ddb.
dart:io
- Breaking Change: Adding to a closed
IOSinknow throws aStateError. - Added ability to get and set low level socket options.
Dart VM
In previous releases it was possible to violate static types using dart:mirrors. This code would run without any TypeErrors and print “impossible” output:
import 'dart:mirrors’;
class A { void method(int v) { if (v != null && v is! int) { print(“This should be impossible: expected null or int got ${v}”); } } }
void main() { final obj = A(); reflect(obj).invoke(#method, [‘not-an-number’]); }
This bug is fixed now. Only code that already violates static typing will break. See Issue 35611 for more details.
Dart for the Web****dart2js
The old “full emitter” back-end is removed and dart2js always uses the “fast startup” back-end. The generated fast startup code is optimized to load faster, even though it can be slightly larger. The
--fast-startupand--no-fast-startupare allowed but ignored. They will be removed in a future version.We fixed a bug in how deferred constructor calls were incorrectly not marked as deferred. The old behavior didn’t cause breakages, but was imprecise and pushed more code to the main output unit.
A new deferred split algorithm implementation was added.
This implementation fixes a soundness bug and addresses performance issues of the previous implementation, because of that it can have a visible impact on apps. In particular:
We fixed a performance issue which was introduced when we migrated to the common front-end. On large apps, the fix can cut 2/3 of the time spent on this task.
We fixed a bug in how inferred types were categorized (Issue 35311). The old behavior was unsound and could produce broken programs. The fix may cause more code to be pulled into the main output unit.
This shows up frequently when returning deferred values from closures since the closure’s inferred return type is the deferred type. For example, if you have:
() async { await deferred_prefix.loadLibrary(); return new deferred_prefix.Foo(); }
The closure’s return type is
Future<Foo>. The old implementation defersFoo, and incorrectly makes the return typeFuture<dynamic>. This may break in places where the correct type is expected.The new implementation will not defer
Foo, and will place it in the main output unit. If your intent is to defer it, then you need to ensure the return type is not inferred to beFoo. For example, you can do so by changing the code to a named closure with a declared type, or by ensuring that the return expression has the type you want, like:() async { await deferred_prefix.loadLibrary(); return new deferred_prefix.Foo() as dynamic; }
Because the new implementation might require you to inspect and fix your app, we exposed two temporary flags:
The
--report-invalid-deferred-typescauses dart2js to run both the old and new algorithms and report any cases where an invalid type was detected.The
--new-deferred-splitflag enables this new algorithm.
The
--categories=*flag is being replaced.--categories=allwas only used for testing and it is no longer supported.--categories=Servercontinues to work at this time but it is deprecated, please use--server-modeinstead.The
--library-rootflag was replaced by--libraries-spec. This flag is rarely used by developers invoking dart2js directly. It’s important for integrating dart2js with build systems. See--helpfor more details on the new flag.
Tools****Analyzer
Support for
declarations-castshas been removed and theimplicit-castsoption now has the combined semantics of both options. This means that users that disableimplicit-castsmight now see errors that were not previously being reported.New hints added:
NON_CONST_CALL_TO_LITERAL_CONSTRUCTORandNON_CONST_CALL_TO_LITERAL_CONSTRUCTOR_USING_NEWinform you when a@literalconst constructor is called in a non-const context (or withnew).INVALID_LITERAL_ANNOTATIONreports when something other than a const constructor is annotated with@literal.SUBTYPE_OF_SEALED_CLASSreports when any class or mixin subclasses (extends, implements, mixes in, or constrains to) a@sealedclass, and the two are declared in different packages.MIXIN_ON_SEALED_CLASSreports when a@sealedclass is used as a superclass constraint of a mixin.
dartdoc
Default styles now work much better on mobile. Simple browsing and searching of API docs now work in many cases.
Upgraded the linter to 0.1.78 which adds the following improvements:
- Added
prefer_final_in_for_each,unnecessary_await_in_return,use_function_type_syntax_for_parameters,avoid_returning_null_for_future, andavoid_shadowing_type_parameters. - Updated
invariant_booleansstatus to experimental. - Fixed
type_annotate_public_apisfalse positives on local functions. - Fixed
avoid_shadowing_type_parametersto report shadowed type parameters in generic typedefs. - Fixed
use_setters_to_change_propertiesto not wrongly lint overriding methods. - Fixed
cascade_invocationsto not lint awaited targets. - Fixed
prefer_conditional_assignmentfalse positives. - Fixed
join_return_with_assignmentfalse positives. - Fixed
cascade_invocationsfalse positives. - Deprecated
prefer_bool_in_assertsas it is redundant in Dart 2.
2.1.0 - 2018-11-15
This is a minor version release. The team’s focus was mostly on improving performance and stability after the large changes in Dart 2.0.0. Notable changes:
We’ve introduced a dedicated syntax for declaring a mixin. Instead of the
classkeyword, it usesmixin:mixin SetMixin<E> implements Set<E> { … }
The new syntax also enables
supercalls inside mixins.Integer literals now work in double contexts. When passing a literal number to a function that expects a
double, you no longer need an explicit.0at the end of the number. In releases before 2.1, you need code like this when setting a double likefontSize:TextStyle(fontSize: 18.0)
Now you can remove the
.0:In releases before 2.1,
fontSize : 18causes a static error. This was a common mistake and source of friction.Breaking change: A number of static errors that should have been detected and reported were not supported in 2.0.0. These are reported now, which means existing incorrect code may show new errors.
dart:corenow exportsFutureandStream. You no longer need to importdart:asyncto use those very common types.
Language
Introduced a new syntax for mixin declarations.
mixin SetMixin<E> implements Set<E> { … }
Most classes that are intended to be used as mixins are intended to only be used as mixins. The library author doesn’t want users to be able to construct or subclass the class. The new syntax makes that intent clear and enforces it in the type system. It is an error to extend or construct a type declared using
mixin. (You can implement it since mixins expose an implicit interface.)Over time, we expect most mixin declarations to use the new syntax. However, if you have a “mixin” class where users are extending or constructing it, note that moving it to the new syntax is a breaking API change since it prevents users from doing that. If you have a type like this that is a mixin as well as being a concrete class and/or superclass, then the existing syntax is what you want.
If you need to use a
superinside a mixin, the new syntax is required. This was previously only allowed with the experimental--supermixinsflag because it has some complex interactions with the type system. The new syntax addresses those issues and lets you usesupercalls by declaring the superclass constraint your mixin requires:class Superclass { superclassMethod() { print(“in superclass”); } }
mixin SomeMixin on Superclass { mixinMethod() { // This is OK: super.superclassMethod(); } }
class GoodSub extends Superclass with SomeMixin {}
class BadSub extends Object with SomeMixin {} // Error: Since the super() call in mixinMethod() can’t find a // superclassMethod() to call, this is prohibited.
Even if you don’t need to use
supercalls, the new mixin syntax is good because it clearly expresses that you intend the type to be mixed in.Allow integer literals to be used in double contexts. An integer literal used in a place where a double is required is now interpreted as a double value. The numerical value of the literal needs to be precisely representable as a double value.
Integer literals compiled to JavaScript are now allowed to have any value that can be exactly represented as a JavaScript
Number. They were previously limited to such numbers that were also representable as signed 64-bit integers.
(Breaking) A number of static errors that should have been detected and reported were not supported in 2.0.0. These are reported now, which means existing incorrect code may show new errors:
Setters with the same name as the enclosing class aren’t allowed. (Issue 34225.) It is not allowed to have a class member with the same name as the enclosing class:
class A { set A(int x) {} }
Dart 2.0.0 incorrectly allows this for setters (only). Dart 2.1.0 rejects it.
To fix: This is unlikely to break anything, since it violates all style guides anyway.
Constant constructors cannot redirect to non-constant constructors. (Issue 34161.) It is not allowed to have a constant constructor that redirects to a non-constant constructor:
class A { const A.foo() : this(); // Redirecting to A() A() {} }
Dart 2.0.0 incorrectly allows this. Dart 2.1.0 rejects it.
To fix: Make the target of the redirection a properly const constructor.
Abstract methods may not unsoundly override a concrete method. (Issue 32014.) Concrete methods must be valid implementations of their interfaces:
class A { num get thing => 2.0; }
abstract class B implements A { int get thing; }
class C extends A with B {} // ‘thing’ from ‘A’ is not a valid override of ‘thing’ from 'B’.
main() { print(new C().thing.isEven); // Expects an int but gets a double. }
Dart 2.0.0 allows unsound overrides like the above in some cases. Dart 2.1.0 rejects them.
To fix: Relax the type of the invalid override, or tighten the type of the overridden method.
Classes can’t implement FutureOr. (Issue 33744.) Dart doesn’t allow classes to implement the FutureOr type:
class A implements FutureOr<Object> {}
Dart 2.0.0 allows classes to implement FutureOr. Dart 2.1.0 does not.
To fix: Don’t do this.
Type arguments to generic typedefs must satisfy their bounds. (Issue 33308.) If a parameterized typedef specifies a bound, actual arguments must be checked against it:
class A<X extends int> {}
typedef F<Y extends int> = A<Y> Function();
F<num> f = null;
Dart 2.0.0 allows bounds violations like
F<num>above. Dart 2.1.0 rejects them.To fix: Either remove the bound on the typedef parameter, or pass a valid argument to the typedef.
Constructor invocations must use valid syntax, even with optional
new. (Issue 34403.) Type arguments to generic named constructors go after the class name, not the constructor name, even when used without an explicitnew:class A<T> { A.foo() {} }
main() { A.foo<String>(); // Incorrect syntax, was accepted in 2.0.0. A<String>.foo(); // Correct syntax. }
Dart 2.0.0 accepts the incorrect syntax when the
newkeyword is left out. Dart 2.1.0 correctly rejects this code.To fix: Move the type argument to the correct position after the class name.
Instance members should shadow prefixes. (Issue 34498.) If the same name is used as an import prefix and as a class member name, then the class member name takes precedence in the class scope.
import 'dart:core’; import ‘dart:core’ as core;
class A { core.List get core => null; // “core” refers to field, not prefix. }
Dart 2.0.0 incorrectly resolves the use of
coreincore.Listto the prefix name. Dart 2.1.0 correctly resolves this to the field name.To fix: Change the prefix name to something which does not clash with the instance member.
Implicit type arguments in extends clauses must satisfy the class bounds. (Issue 34532.) Implicit type arguments for generic classes are computed if not passed explicitly, but when used in an
extendsclause they must be checked for validity:class Foo<T> {}
class Bar<T extends Foo<T>> {}
class Baz extends Bar {} // Should error because Bar completes to Bar<Foo>
Dart 2.0.0 accepts the broken code above. Dart 2.1.0 rejects it.
To fix: Provide explicit type arguments to the superclass that satisfy the bound for the superclass.
Mixins must correctly override their superclasses. (Issue 34235.) In some rare cases, combinations of uses of mixins could result in invalid overrides not being caught:
class A { num get thing => 2.0; }
class M1 { int get thing => 2; }
class B = A with M1;
class M2 { num get thing => 2.0; }
class C extends B with M2 {} // ‘thing’ from ‘M2’ not a valid override.
main() { M1 a = new C(); print(a.thing.isEven); // Expects an int but gets a double. }
Dart 2.0.0 accepts the above example. Dart 2.1.0 rejects it.
To fix: Ensure that overriding methods are correct overrides of their superclasses, either by relaxing the superclass type, or tightening the subclass/mixin type.
Core libraries****dart:async
- Fixed a bug where calling
stream.take(0).drain(value)would not correctly forward thevaluethrough the returnedFuture. - Added a
StreamTransformer.fromBindconstructor. - Updated
Stream.fromIterableto send a done event after the error when the iterator’smoveNextthrows, and handle if thecurrentgetter throws (issue 33431).
dart:core
- Added
HashMap.fromEntriesandLinkedHashmap.fromEntriesconstructors. - Added
ArgumentError.checkNotNullutility method. - Made
Uriparsing more permissive about[and]occurring in the path, query or fragment, and#occurring in fragment. - Exported
FutureandStreamfromdart:core. - Added operators
&,|and^tobool. - Added missing methods to
UnmodifiableMapMixin. Some maps intended to be unmodifiable incorrectly allowed new methods added in Dart 2 to succeed. - Deprecated the
provisionalannotation and theProvisionalannotation class. These should have been removed before releasing Dart 2.0, and they have no effect.
dart:html
Fixed Service Workers and any Promise/Future API with a Dictionary parameter.
APIs in dart:html (that take a Dictionary) will receive a Dart Map parameter. The Map parameter must be converted to a Dictionary before passing to the browser’s API. Before this change, any Promise/Future API with a Map/Dictionary parameter never called the Promise and didn’t return a Dart Future - now it does.
This caused a number of breaks especially in Service Workers (register, etc.). Here is a complete list of the fixed APIs:
BackgroundFetchManager
Future<BackgroundFetchRegistration> fetch(String id, Object requests, [Map options])
CacheStorage
Future match(/*RequestInfo*/ request, [Map options])
CanMakePayment
Future<List<Client>> matchAll([Map options])
CookieStore
Future getAll([Map options])Future set(String name, String value, [Map options])
CredentialsContainer
Future get([Map options])Future create([Map options])
ImageCapture
Future setOptions(Map photoSettings)
MediaCapabilities
Future<MediaCapabilitiesInfo> decodingInfo(Map configuration)Future<MediaCapabilitiesInfo> encodingInfo(Map configuration)
MediaStreamTrack
Future applyConstraints([Map constraints])
Navigator
Future requestKeyboardLock([List<String> keyCodes])Future requestMidiAccess([Map options])Future share([Map data])
OffscreenCanvas
Future<Blob> convertToBlob([Map options])
PaymentInstruments
Future set(String instrumentKey, Map details)
Permissions
Future<PermissionStatus> query(Map permission)Future<PermissionStatus> request(Map permissions)Future<PermissionStatus> revoke(Map permission)
PushManager
Future permissionState([Map options])Future<PushSubscription> subscribe([Map options])
RtcPeerConnection
Changed:
Future createAnswer([options_OR_successCallback, RtcPeerConnectionErrorCallback failureCallback, Map mediaConstraints])
to:
Future<RtcSessionDescription> createAnswer([Map options])
Changed:
Future createOffer([options_OR_successCallback, RtcPeerConnectionErrorCallback failureCallback, Map rtcOfferOptions])
to:
Future<RtcSessionDescription> createOffer([Map options])
Changed:
Future setLocalDescription(Map description, VoidCallback successCallback, [RtcPeerConnectionErrorCallback failureCallback])
to:
Future setLocalDescription(Map description)
Changed:
Future setLocalDescription(Map description, VoidCallback successCallback, [RtcPeerConnectionErrorCallback failureCallback])
to:
Future setRemoteDescription(Map description)
ServiceWorkerContainer
Future<ServiceWorkerRegistration> register(String url, [Map options])
ServiceWorkerRegistration
Future<List<Notification>> getNotifications([Map filter])Future showNotification(String title, [Map options])
VRDevice
Future requestSession([Map options])Future supportsSession([Map options])
VRSession
Future requestFrameOfReference(String type, [Map options])
Window
Future fetch(/*RequestInfo*/ input, [Map init])
WorkerGlobalScope
Future fetch(/*RequestInfo*/ input, [Map init])
In addition, exposed Service Worker “self” as a static getter named "instance". The instance is exposed on four different Service Worker classes and can throw a InstanceTypeError if the instance isn’t of the class expected (WorkerGlobalScope.instance will always work and not throw):
SharedWorkerGlobalScope.instanceDedicatedWorkerGlobalScope.instanceServiceWorkerGlobalScope.instanceWorkerGlobalScope.instance
dart:io
- Added new HTTP status codes.
Dart for the Web****dart2js
(Breaking) Duplicate keys in a const map are not allowed and produce a compile-time error. Dart2js used to report this as a warning before. This was already an error in dartanalyzer and DDC and will be an error in other tools in the future as well.
Added
-Oflag to tune optimization levels. For more details rundart2js -h -v.We recommend to enable optimizations using the
-Oflag instead of individual flags for each optimization. This is because the-Oflag is intended to be stable and continue to work in future versions of dart2js, while individual flags may come and go.At this time we recommend to test and debug with
-O1and to deploy with-O3.
Tool Changes****dartfmt
- Addressed several dartfmt issues when used with the new CFE parser.
Linter
Bumped the linter to 0.1.70 which includes the following new lints:
avoid_returning_null_for_voidsort_pub_dependenciesprefer_mixinavoid_implementing_value_typesflutter_style_todosavoid_void_asyncprefer_void_to_null
and improvements:
- Fixed NPE in
prefer_iterable_whereType. - Improved message display for
await_only_futures - Performance improvements for
null_closures - Mixin support
- Updated
sort_constructors_firstto apply to all members. - Updated
unnecessary_thisto work on field initializers. - Updated
unawaited_futuresto ignore assignments within cascades. - Improved handling of constant expressions with generic type params.
- NPE fix for
invariant_booleans. - Improved docs for
unawaited_futures. - Updated
unawaited_futuresto check cascades. - Relaxed
void_checks(allowingT Function()to be assigned tovoid Function()). - Fixed false positives in
lines_longer_than_80_chars.
Pub
- Renamed the
--checkedflag topub runto--enable-asserts. - Pub will no longer delete directories named "packages".
- The
--packages-dirflag is now ignored.
2.0.0 - 2018-08-07
This is the first major version release of Dart since 1.0.0, so it contains many significant changes across all areas of the platform. Large changes include:
(Breaking) The unsound optional static type system has been replaced with a sound static type system using type inference and runtime checks. This was formerly called “strong mode” and only used by the Dart for web products. Now it is the one official static type system for the entire platform and replaces the previous “checked” and “production” modes.
(Breaking) Functions marked
asyncnow run synchronously until the firstawaitstatement. Previously, they would return to the event loop once at the top of the function body before any code runs (issue 30345).(Breaking) Constants in the core libraries have been renamed from
SCREAMING_CAPStolowerCamelCase.(Breaking) Many new methods have been added to core library classes. If you implement the interfaces of these classes, you will need to implement the new methods.
(Breaking) “dart:isolate” and “dart:mirrors” are no longer supported when using Dart for the web. They are still supported in the command-line VM.
(Breaking) Pub’s transformer-based build system has been replaced by a new build system.
The
newkeyword is optional and can be omitted. Likewise,constcan be omitted inside a const context (issue 30921).Dartium is no longer maintained or supported.
Language
“Strong mode” is now the official type system of the language.
The
newkeyword is optional and can be omitted. Likewise,constcan be omitted inside a const context.A string in a
part ofdeclaration may now be used to refer to the library this file is part of. A library part can now declare its library as either:Or:
part of "uriReferenceOfLibrary.dart";
This allows libraries with no library declarations (and therefore no name) to have parts, and it allows tools to easily find the library of a part file. The Dart 1.0 syntax is supported but deprecated.
Functions marked
asyncnow run synchronously until the firstawaitstatement. Previously, they would return to the event loop once at the top of the function body before any code runs (issue 30345).The type
voidis now a Top type likedynamic, andObject. It also now has new errors for being used where not allowed (such as being assigned to any non-void-typed parameter). Some libraries (importantly, mockito) may need to be updated to accept void values to keep their APIs working.Future flattening is now done only as specified in the Dart 2.0 spec, rather than more broadly. This means that the following code has an error on the assignment to
y.test() { Future<int> f; var x = f.then<Future<List<int>>>((x) => []); Future<List<int>> y = x; }
Invocations of
noSuchMethod()receive default values for optional args. The following program used to print "No arguments passed", and now prints "First argument is 3".abstract class B { void m([int x = 3]); }
class A implements B { noSuchMethod(Invocation i) { if (i.positionalArguments.length == 0) { print(“No arguments passed”); } else { print(“First argument is ${i.positionalArguments[0]}”); } } }
void main() { A().m(); }
Bounds on generic functions are invariant. The following program now issues an invalid override error (issue 29014):
class A { void f<T extends int>() {} }
class B extends A { @override void f<T extends num>() {} }
Numerous corner case bugs around return statements in synchronous and asynchronous functions fixed. Specifically:
- Issues 31887, 32881. Future flattening should not be recursive.
- Issues 30638, 32233. Incorrect downcast errors with
FutureOr. - Issue 32233. Errors when returning
FutureOr. - Issue 33218. Returns in functions with void related types.
- Issue 31278. Incorrect hint on empty returns in async. functions.
An empty
return;in an async function with return typeFuture<Object>does not report an error.return exp;whereexphas typevoidin an async function is now an error unless the return type of the function isvoidordynamic.Mixed return statements of the form
return;andreturn exp;are now allowed whenexphas typevoid.A compile time error is emitted for any literal which cannot be exactly represented on the target platform. As a result, dart2js and DDC report errors if an integer literal cannot be represented exactly in JavaScript (issue 33282).
New member conflict rules have been implemented. Most cases of conflicting members with the same name are now static errors (issue 33235).
Core libraries
Replaced
UPPER_CASEconstant names withlowerCamelCase. For example,HTML_ESCAPEis nowhtmlEscape.The Web libraries were re-generated using Chrome 63 WebIDLs (details).
dart:async
Stream:- Added
castandcastFrom. - Changed
firstWhere,lastWhere, andsingleWhereto returnFuture<T>and added an optionalT orElse()callback.
- Added
StreamTransformer: addedcastandcastFrom.StreamTransformerBase: new class.Timer: addedtickproperty.Zone- changed to be strong-mode clean. This required some breaking API changes. See https://goo.gl/y9mW2x for more information.
- Added
bindBinaryCallbackGuarded,bindCallbackGuarded, andbindUnaryCallbackGuarded. - Renamed
Zone.ROOTtoZone.root.
- Removed the deprecated
defaultValueparameter onStream.firstWhereandStream.lastWhere. - Changed an internal lazily-allocated reusable “null future” to always belong to the root zone. This avoids race conditions where the first access to the future determined which zone it would belong to. The zone is only used for scheduling the callback of listeners, the listeners themselves will run in the correct zone in any case. Issue #32556.
dart:cli
- New “provisional” library for CLI-specific features.
waitFor: function that suspends a stack to wait for aFutureto complete.
dart:collection
MapBase: addedmapToString.LinkedHashMapno longer implementsHashMapLinkedHashSetno longer implementsHashSet.- Added
ofconstructor toQueue,ListQueue,DoubleLinkedQueue,HashSet,LinkedHashSet,SplayTreeSet,Map,HashMap,LinkedHashMap,SplayTreeMap. - Removed
Mapsclass. ExtendMapBaseor mix inMapMixininstead to provide map method implementations for a class. - Removed experimental
DocumentmethodgetCSSCanvasContextand propertysupportsCssCanvasContext. - Removed obsolete
Elementpropertyxtagno longer supported in browsers. - Exposed
ServiceWorkerclass. - Added constructor to
MessageChannelandMessagePortaddEventListenerautomatically callsstartmethod to receive queued messages.
dart:convert
Base64Codec.decodereturn type is nowUint8List.JsonUnsupportedObjectError: addedpartialResultpropertyLineSplitternow implementsStreamTransformer<String, String>instead ofConverter. It retainsConvertermethodsconvertandstartChunkedConversion.Utf8Decoderwhen compiled with dart2js uses the browser’sTextDecoderin some common cases for faster decoding.- Renamed
ASCII,BASE64,BASE64URI,JSON,LATIN1andUTF8toascii,base64,base64Uri,json,latin1andutf8. - Renamed the
HtmlEscapeModeconstantsUNKNOWN,ATTRIBUTE,SQ_ATTRIBUTEandELEMENTtounknown,attribute,sqAttributeandelements. - Added
jsonEncode,jsonDecode,base64Encode,base64UrlEncodeandbase64Decodetop-level functions. - Changed return type of
encodeonAsciiCodecandLatin1Codec, andconvertonAsciiEncoder,Latin1Encoder, toUint8List. - Allow
utf8.decoder.fuse(json.decoder)to ignore leading Unicode BOM.
dart:core
BigIntclass added to support integers greater than 64-bits.- Deprecated the
proxyannotation. - Added
Provisionalclass andprovisionalfield. - Added
pragmaannotation. RegExpadded staticescapefunction.- The
Uriclass now correctly handles paths while running on Node.js on Windows. - Core collection changes:
Iterableadded memberscast,castFrom,followedByandwhereType.Iterable.singleWhereaddedorElseparameter.Listadded+operator,firstandlastsetters, andindexWhereandlastIndexWheremethods, and staticcopyRangeandwriteIterablemethods.MapaddedfromEntriesconstructor.MapaddedaddEntries,cast,entries,map,removeWhere,updateandupdateAllmembers.MapEntry: new class used byMap.entries.- Note: if a class extends
IterableBase,ListBase,SetBaseorMapBase(or uses the corresponding mixins) fromdart:collection, the new members are implemented automatically. - Added
ofconstructor toList,Set,Map.
- Renamed
double.INFINITY,double.NEGATIVE_INFINITY,double.NAN,double.MAX_FINITEanddouble.MIN_POSITIVEtodouble.infinity,double.negativeInfinity,double.nan,double.maxFiniteanddouble.minPositive. - Renamed the following constants in
DateTimeto lower case:MONDAYthroughSUNDAY,DAYS_PER_WEEK(asdaysPerWeek),JANUARYthroughDECEMBERandMONTHS_PER_YEAR(asmonthsPerYear). - Renamed the following constants in
Durationto lower case:MICROSECONDS_PER_MILLISECONDtomicrosecondsPerMillisecond,MILLISECONDS_PER_SECONDtomillisecondsPerSecond,SECONDS_PER_MINUTEtosecondsPerMinute,MINUTES_PER_HOURtominutesPerHour,HOURS_PER_DAYtohoursPerDay,MICROSECONDS_PER_SECONDtomicrosecondsPerSecond,MICROSECONDS_PER_MINUTEtomicrosecondsPerMinute,MICROSECONDS_PER_HOURtomicrosecondsPerHour,MICROSECONDS_PER_DAYtomicrosecondsPerDay,MILLISECONDS_PER_MINUTEtomillisecondsPerMinute,MILLISECONDS_PER_HOURtomillisecondsPerHour,MILLISECONDS_PER_DAYtomillisecondsPerDay,SECONDS_PER_HOURtosecondsPerHour,SECONDS_PER_DAYtosecondsPerDay,MINUTES_PER_DAYtominutesPerDay, andZEROtozero. - Added
typeArgumentstoInvocationclass. - Added constructors to invocation class that allows creation of
Invocationobjects directly, without going throughnoSuchMethod. - Added
unaryMinusandemptyconstant symbols on theSymbolclass. - Changed return type of
UriData.dataAsBytestoUint8List. - Added
tryParsestatic method toint,double,num,BigInt,UriandDateTime. - Deprecated
onErrorparameter onint.parse,double.parseandnum.parse. - Deprecated the
NoSuchMethodErrorconstructor. int.parseon the VM no longer accepts unsigned hexadecimal numbers greater than or equal to2**63when not prefixed by0x. (SDK issue 32858)
dart:developer
Flowclass added.Timeline.startSyncandTimeline.timeSyncnow accepts an optional parameterflowof typeFlow. Theflowparameter is used to generate flow timeline events that are enclosed by the slice described byTimeline.{start,finish}SyncandTimeline.timeSync.
dart:html
- Removed deprecated
queryandqueryAll. UsequerySelectorandquerySelectorAll.
dart:io
HttpStatusaddedUPGRADE_REQUIRED.IOOverridesandHttpOverridesadded to aid in writing tests that wish to mock variosdart:ioobjects.Platform.operatingSystemVersionadded that gives a platform-specific String describing the version of the operating system.ProcessStartMode.INHERIT_STDIOadded, which allows a child process to inherit the parent’s stdio handles.RawZLibFilteradded for low-level access to compression and decompression routines.- Unified backends for
SecureSocket,SecurityContext, andX509Certificateto be consistent across all platforms. AllSecureSocket,SecurityContext, andX509Certificateproperties and methods are now supported on iOS and OSX. SecurityContext.alpnSupporteddeprecated as ALPN is now supported on all platforms.SecurityContext: addedwithTrustedRootsnamed optional parameter constructor, which defaults to false.- Added a
timeoutparameter toSocket.connect,RawSocket.connect,SecureSocket.connectandRawSecureSocket.connect. If a connection attempt takes longer than the duration specified intimeout, aSocketExceptionwill be thrown. Note: if the duration specified intimeoutis greater than the OS level timeout, a timeout may occur sooner than specified intimeout. Stdin.hasTerminaladded, which is true if stdin is attached to a terminal.WebSocketadded staticuserAgentproperty.RandomAccessFile.closereturnsFuture<void>- Added
IOOverrides.socketConnect. - Added Dart-styled constants to
ZLibOptions,FileMode,FileLock,FileSystemEntityType,FileSystemEvent,ProcessStartMode,ProcessSignal,InternetAddressType,InternetAddress,SocketDirection,SocketOption,RawSocketEvent, andStdioType, and deprecated the oldSCREAMING_CAPSconstants. - Added the Dart-styled top-level constants
zlib,gzip, andsystemEncoding, and deprecated the oldSCREAMING_CAPStop-level constants. - Removed the top-level
FileModeconstantsREAD,WRITE,APPEND,WRITE_ONLY, andWRITE_ONLY_APPEND. Please use e.g.FileMode.readinstead. - Added
X509Certificate.der,X509Certificate.pem, andX509Certificate.sha1. - Added
FileSystemEntity.fromRawPathconstructor to allow for the creation ofFileSystemEntityusingUint8Listbuffers. - Dart-styled constants have been added for
HttpStatus,HttpHeaders,ContentType,HttpClient,WebSocketStatus,CompressionOptions, andWebSocket. TheSCREAMING_CAPSconstants are marked deprecated. Note thatHttpStatus.CONTINUEis nowHttpStatus.continue_, and that e.g.HttpHeaders.FIELD_NAMEis nowHttpHeaders.fieldNameHeader. - Deprecated
Platform.packageRoot, which is only used forpackages/directory resolution which is no longer supported. It will now always return null, which is a value that was always possible for it to return previously. - Adds
HttpClient.connectionTimeout. - Adds
{Socket,RawSocket,SecureSocket}.startConnect. These return aConnectionTask, which can be used to cancel an in-flight connection attempt.
dart:isolate
- Make
Isolate.spawntake a type parameter representing the argument type of the provided function. This allows functions with arguments types other thanObjectin strong mode. - Rename
IMMEDIATEandBEFORE_NEXT_EVENTonIsolatetoimmediateandbeforeNextEvent. - Deprecated
Isolate.packageRoot, which is only used forpackages/directory resolution which is no longer supported. It will now always return null, which is a value that was always possible for it to return previously. - Deprecated
packageRootparameter inIsolate.spawnUri, which is was previously used only forpackages/directory resolution. That style of resolution is no longer supported in Dart 2.
dart.math
- Renamed
E,LN10,LN,LOG2E,LOG10E,PI,SQRT1_2andSQRT2toe,ln10,ln,log2e,log10e,pi,sqrt1_2andsqrt2.
dart.mirrors
- Added
IsolateMirror.loadUri, which allows dynamically loading additional code. - Marked
MirrorsUsedas deprecated. TheMirrorsUsedannotation was only used to inform the dart2js compiler about how mirrors were used, but dart2js no longer supports the mirrors library altogether.
dart:typed_data
- Added
Unmodifiableview classes over allListtypes. - Renamed
BYTES_PER_ELEMENTtobytesPerElementon all typed data lists. - Renamed constants
XXXXthroughWWWWonFloat32x4andInt32x4to lower-casexxxxthroughwwww. - Renamed
EndinannesstoEndianand its constants fromBIG_ENDIAN,LITTLE_ENDIANandHOST_ENDIANtolittle,bigandhost.
Dart VM
Support for MIPS has been removed.
Dart
intis now restricted to 64 bits. On overflow, arithmetic operations wrap around, and integer literals larger than 64 bits are not allowed. See https://github.com/dart-lang/sdk/blob/main/docs/language/informal/int64.md for details.The Dart VM no longer attempts to perform
packages/directory resolution (for loading scripts, and inIsolate.resolveUri). Users relying onpackages/directories should switch to.packagesfiles.
Dart for the Web
Expose JavaScript Promise APIs using Dart futures. For example,
BackgroundFetchManager.getis defined as:Future<BackgroundFetchRegistration> get(String id)
It can be used like:
BackgroundFetchRegistration result = await fetchMgr.get(‘abc’);
The underlying JS Promise-to-Future mechanism will be exposed as a public API in the future.
Dart Dev Compiler (DDC)
dartdevc will no longer throw an error from
ischecks that return a different result in weak mode (SDK issue 28988). For example:main() { List l = []; // Prints "false", does not throw. print(l is List<String>); }
Failed
ascasts onIterable<T>,Map<T>,Future<T>, andStream<T>are no longer ignored. These failures were ignored to make it easier to migrate Dart 1 code to strong mode, but ignoring them is a hole in the type system. This closes part of that hole. (We still need to stop ignoring “as” cast failures on function types, and implicit cast failures on the above types and function types.)
dart2js
dart2js now compiles programs with Dart 2.0 semantics. Apps are expected to be bigger than before, because Dart 2.0 has many more implicit checks (similar to the
--checkedflag in Dart 1.0).We exposed a
--omit-implicit-checksflag which removes most of the extra implicit checks. Only use this if you have enough test coverage to know that the app will work well without the checks. If a check would have failed and it is omitted, your app may crash or behave in unexpected ways. This flag is similar to--trust-type-annotationsin Dart 1.0.dart2js replaced its front-end with the common front-end (CFE). Thanks to the CFE, dart2js errors are more consistent with all other Dart tools.
dart2js replaced its source-map implementation. There aren’t any big differences, but more data is emitted for synthetic code generated by the compiler.
dart:mirrorssupport was removed. Frameworks are encouraged to use code-generation instead. Conditional imports indicate that mirrors are not supported, and any API in the mirrors library will throw at runtime.The generated output of dart2js can now be run as a webworker.
dart:isolatesupport was removed. To launch background tasks, please use webworkers instead. APIs for webworkers can be accessed fromdart:htmlor JS-interop.dart2js no longer supports the
--package-rootflag. This flag was deprecated in favor of--packageslong ago.
Tool Changes****Analyzer
The analyzer will no longer issue a warning when a generic type parameter is used as the type in an instance check. For example:
test<T>() { print(3 is T); // No warning }
New static checking of
@visibleForTestingelements. Accessing a method, function, class, etc. annotated with@visibleForTestingfrom a file not in atest/directory will result in a new hint (issue 28273).Static analysis now respects functions annotated with
@alwaysThrows(issue 31384).New hints added:
NULL_AWARE_BEFORE_OPERATORwhen an operator is used after a null-aware access. For example:NULL_AWARE_IN_LOGICAL_OPERATORwhen an expression with null-aware access is used as a condition in logical operators. For example:
The command line analyzer (dartanalyzer) and the analysis server no longer treat directories named
packagesspecially. Previously they had ignored these directories - and their contents - from the point of view of analysis. Now they’ll be treated just as regular directories. This special-casing ofpackagesdirectories was to support using symlinks for package: resolution; that functionality is now handled by.packagesfiles.New static checking of duplicate shown or hidden names in an export directive (issue 33182).
The analysis server will now only analyze code in Dart 2 mode (‘strong mode’). It will emit warnings for analysis options files that have
strong-mode: falseset (and will emit a hint forstrong-mode: true, which is no longer necessary).The dartanalyzer
--strongflag is now deprecated and ignored. The command-line analyzer now only analyzes code in strong mode.
dartfmt
Support
assert()in const constructor initializer lists.Better formatting for multi-line strings in argument lists.
Force splitting an empty block as the then body of an if with an else.
Support metadata annotations on enum cases.
Add
--fixto remove unneedednewandconstkeywords, and change:to=before named parameter default values.Change formatting rules around static methods to uniformly format code with and without
newandconst.Format expressions inside string interpolation.
Pub
Pub has a brand new version solver! It supports all the same features as the old version solver, but it’s much less likely to stall out on difficult package graphs, and it’s much clearer about why a solution can’t be found when version solving fails.
Remove support for transformers,
pub build, andpub serve. Use the new build system instead.There is now a default SDK constraint of
<2.0.0for any package with no existing upper bound. This allows us to move more safely to 2.0.0. All new packages published on pub will now require an upper bound SDK constraint so future major releases of Dart don’t destabilize the package ecosystem.All SDK constraint exclusive upper bounds are now treated as though they allow pre-release versions of that upper bound. For example, the SDK constraint
>=1.8.0 <2.0.0now allows pre-release SDK versions such as2.0.0-beta.3.0. This allows early adopters to try out packages that don’t explicitly declare support for the new version yet. You can disable this functionality by setting thePUB_ALLOW_PRERELEASE_SDKenvironment variable tofalse.Allow depending on a package in a subdirectory of a Git repository. Git dependencies may now include a
pathparameter, indicating that the package exists in a subdirectory of the Git repository. For example:dependencies: foobar: git: url: git://github.com/dart-lang/multi_package_repo path: pkg/foobar
Added an
--executablesoption topub depscommand. This will list all available executables that can be run withpub run.The Flutter
sdksource will now look for packages influtter/bin/cache/pkg/as well asflutter/packages/. In particular, this means that packages can depend on thesky_enginepackage from thesdksource (issue 1775).Pub now caches compiled packages and snapshots in the
.dart_tool/pubdirectory, rather than the.pubdirectory (issue 1795).Other bug fixes and improvements.
1.24.3 - 2017-12-14
- Fix for constructing a new SecurityContext that contains the built-in certificate authority roots (issue 24693).
Core library changes
dart:io- Unified backends for
SecureSocket,SecurityContext, andX509Certificateto be consistent across all platforms. AllSecureSocket,SecurityContext, andX509Certificateproperties and methods are now supported on iOS and OSX.
- Unified backends for
1.24.2 - 2017-06-22
- Fixes for debugging in Dartium.
- Fix DevConsole crash with JS (issue 29873).
- Fix debugging in WebStorm, NULL returned for JS objects (issue 29854).
1.24.1 - 2017-06-14
- Bug fixes for dartdevc support in
pub serve.- Fixed module config invalidation logic so modules are properly recalculated when package layout changes.
- Fixed exception when handling require.js errors that aren’t script load errors.
- Fixed an issue where requesting the bootstrap.js file before the dart.js file would result in a 404.
- Fixed a Safari issue during bootstrapping (note that Safari is still not officially supported but does work for trivial examples).
- Fix for a Dartium issue where there was no sound in checked mode (issue 29810).
1.24.0 - 2017-06-12****Language
During a dynamic type check,
voidis not required to benullanymore. In practice, this makes overridingvoidfunctions with non-voidfunctions safer.During static analysis, a function or setter declared using
=>with return typevoidnow allows the returned expression to have any type. For example, assuming the declarationint x;, it is now type correct to havevoid f() => ++x;.A new function-type syntax has been added to the language. Warning: In Dart 1.24, this feature is incomplete, and not stable in the Analyzer.
Intuitively, the type of a function can be constructed by textually replacing the function’s name with
Functionin its declaration. For instance, the type ofvoid foo() {}would bevoid Function(). The new syntax may be used wherever a type can be written. It is thus now possible to declare fields containing functions without needing to write typedefs:void Function() x;. The new function type has one restriction: it may not contain the old-style function-type syntax for its parameters. The following is thus illegal:void Function(int f()).typedefshave been updated to support this new syntax.Examples:
typedef F = void Function(); // F is the name for a `void` callback. int Function(int) f; // A field `f` that contains an int->int function.
class A<T> { // The parameter `callback` is a function that takes a `T` and returns // `void`. void forEach(void Function(T) callback); }
// The new function type supports generic arguments. typedef Invoker = T Function<T>(T Function() callback);
Core library changes
dart:async,dart:core,dart:io- Adding to a closed sink, including
IOSink, is no longer not allowed. In 1.24, violations are only reported (on stdout or stderr), but a future version of the Dart SDK will change this to throwing aStateError.
- Adding to a closed sink, including
dart:convert- BREAKING Removed the deprecated
ChunkedConverterclass. - JSON maps are now typed as
Map<String, dynamic>instead ofMap<dynamic, dynamic>. A JSON-map is not aHashMaporLinkedHashMapanymore (but just aMap).
- BREAKING Removed the deprecated
dart:io- Added
Platform.localeName, needed for accessing the locale on platforms that don’t store it in an environment variable. - Added
ProcessInfo.currentRssandProcessInfo.maxRssfor inspecting the Dart VM process current and peak resident set size. - Added
RawSynchronousSocket, a basic synchronous socket implementation.
- Added
dart:web APIs have been updated to align with Chrome v50. This change includes a large number of changes, many of which are breaking. In some cases, new class names may conflict with names that exist in existing code.dart:htmlREMOVED classes:
Bluetooth,BluetoothDevice,BluetoothGattCharacteristic,BluetoothGattRemoteServer,BluetoothGattService,BluetoothUuid,CrossOriginConnectEvent,DefaultSessionStartEvent,DomSettableTokenList,MediaKeyError,PeriodicSyncEvent,PluginPlaceholderElement,ReadableStream,StashedMessagePort,SyncRegistrationREMOVED members:
texImage2DCanvaswas removed fromRenderingContext.endClipandstartClipwere removed fromAnimation.afterandbeforewere removed fromCharacterData,ChildNodeandElement.keyLocationwas removed fromKeyboardEvent. Uselocationinstead.generateKeyRequest,keyAddedEvent,keyErrorEvent,keyMessageEvent,mediaGroup,needKeyEvent,onKeyAdded,onKeyError,onKeyMessage, andonNeedKeywere removed fromMediaElement.getStorageUpdateswas removed fromNavigatorstatuswas removed fromPermissionStatusgetAvailabilitywas removed fromPreElement
Other behavior changes:
- URLs returned in CSS or html are formatted with quoted string. Like
url("http://google.com")instead ofurl(http://google.com). - Event timestamp property type changed from
inttonum. - Chrome introduced slight layout changes of UI objects. In addition many height/width dimensions are returned in subpixel values (
numinstead of whole numbers). setRangeTextwith aselectionModevalue of ‘invalid’ is no longer valid. Only "select", "start", "end", “preserve” are allowed.
- URLs returned in CSS or html are formatted with quoted string. Like
dart:svg- A large number of additions and removals. Review your use of
dart:svgcarefully.
- A large number of additions and removals. Review your use of
dart:web_audio- new method on
AudioContext-createIirFilterreturns a new classIirFilterNode.
- new method on
dart:web_glnew classes:
CompressedTextureAstc,ExtColorBufferFloat,ExtDisjointTimerQuery, andTimerQueryExt.ExtFragDepthadded:readPixels2andtexImage2D2.
Strong Mode
Removed ad hoc
Future.theninference in favor of usingFutureOr. Prior to addingFutureOrto the language, the analyzer implemented an ad hoc type inference forFuture.then(and overrides) treating it as if the onValue callback was typed to returnFutureOrfor the purposes of inference. This ad hoc inference has been removed now thatFutureOrhas been added.Packages that implement
Futuremust either type theonValueparameter to.thenas returningFutureOr<T>, or else must leave the type of the parameter entirely to allow inference to fill in the type.During static analysis, a function or setter declared using
=>with return typevoidnow allows the returned expression to have any type.
Tool Changes
Dartium
Dartium is now based on Chrome v50. See Core library changes above for details on the changed APIs.
Pub
pub buildandpub serveAdded support for the Dart Development Compiler.
Unlike dart2js, this new compiler is modular, which allows pub to do incremental re-builds for
pub serve, and potentiallypub buildin the future.In practice what that means is you can edit your Dart files, refresh in Chrome (or other supported browsers), and see your edits almost immediately. This is because pub is only recompiling your package, not all packages that you depend on.
There is one caveat with the new compiler, which is that your package and your dependencies must all be strong mode clean. If you are getting an error compiling one of your dependencies, you will need to file bugs or send pull requests to get them strong mode clean.
There are two ways of opting into the new compiler:
Use the new
--web-compilerflag, which supportsdartdevc,dart2jsornoneas options. This is the easiest way to try things out without changing the default.Add config to your pubspec. There is a new
webkey which supports a single key calledcompiler. This is a map from mode names to compiler to use. For example, to default to dartdevc in debug mode you can add the following to your pubspec:web: compiler: debug: dartdevc
You can also use the new compiler to run your tests in Chrome much more quickly than you can with dart2js. In order to do that, run `pub serve test --web-compiler=dartdevc`, and then run `pub run test -p chrome --pub-serve=8080`.
* The `--no-dart2js` flag has been deprecated in favor of `--web-compiler=none`.
* `pub build` will use a failing exit code if there are errors in any transformer.
* `pub publish`
* Added support for the UNLICENSE file.
* Packages that depend on the Flutter SDK may be published.
* `pub get` and `pub upgrade`
* Don't dump a stack trace when a network error occurs while fetching packages.
dartfmt
- Preserve type parameters in new generic function typedef syntax.
- Add self-test validation to ensure formatter bugs do not cause user code to be lost.
Infrastructure changes
- As of this release, we’ll show a warning when using the MIPS architecture. Unless we learn about any critical use of Dart on MIPS in the meantime, we’re planning to deprecate support for MIPS starting with the next stable release.
1.23.0 - 2017-04-21****Strong Mode
- Breaking change - it is now a strong mode error if a mixin causes a name conflict between two private members (field/getter/setter/method) from a different library. (SDK issue 28809).
lib1.dart:
class A { int _x; }
class B { int _x; }
lib2.dart:
import 'lib1.dart’;
class C extends A with B {}
error • The private name _x, defined by B, conflicts with the same name defined by A at tmp/lib2.dart:3:24 • private_collision_in_mixin_application
Breaking change - strong mode will prefer the expected type to infer generic types, functions, and methods (SDK issue 27586).
main() { List<Object> foo = /*infers: <Object>*/['hello’, ‘world’]; var bar = /*infers: <String>*/['hello’, ‘world’]; }
Strong mode inference error messages are improved (SDK issue 29108).
import 'dart:math’; test(Iterable/* fix is to add <num> here */ values) { num n = values.fold(values.first as num, max); }
Now produces the error on the generic function "max":
Couldn't infer type parameter 'T'. Tried to infer 'dynamic' for 'T' which doesn't work: Function type declared as '<T extends num>(T, T) → T' used where '(num, dynamic) → num' is required. Consider passing explicit type argument(s) to the generic.Strong mode supports overriding fields,
@virtualis no longer required (SDK issue 28120).class C { int x = 42; } class D extends C { get x { print(“x got called”); return super.x; } } main() { print(new D().x); }
Strong mode down cast composite warnings are no longer issued by default. (SDK issue 28588).
void test() { List untyped = []; List<int> typed = untyped; // No down cast composite warning }
To opt back into the warnings, add the following to the .analysis_options file for your project.
analyzer:
errors:
strong_mode_down_cast_composite: warning
Core library changes
dart:core- Added
Uri.isSchemefunction to check the scheme of a URI. Example:uri.isScheme("http"). Ignores case when comparing. - Make
UriData.parsevalidate its input better. If the data is base-64 encoded, the data is normalized wrt. alphabet and padding, and it contains invalid base-64 data, parsing fails. Also normalizes non-base-64 data.
- Added
dart:io- Added functions
File.lastAccessed,File.lastAccessedSync,File.setLastModified,File.setLastModifiedSync,File.setLastAccessed, andFile.setLastAccessedSync. - Added
{Stdin,Stdout}.supportsAnsiEscapes.
- Added functions
Dart VM
- Calls to
print()andStdout.write*()now correctly print unicode characters to the console on Windows. Calls toStdout.add*()behave as before.
Tool changes
Analysis
dartanalyzernow follows the same rules as the analysis server to find an analysis options file, stopping when an analysis options file is found:- Search up the directory hierarchy looking for an analysis options file.
- If analyzing a project referencing the Flutter package, then use the default Flutter analysis options found in
package:flutter. - If in a Bazel workspace, then use the analysis options in
package:dart.analysis_options/default.yamlif it exists. - Use the default analysis options rules.
- In addition, specific to
dartanalyzer:- an analysis options file can be specified on the command line via
--optionsand that file will be used instead of searching for an analysis options file. - any analysis option specified on the command line (e.g.
--strongor--no-strong) takes precedence over any corresponding value specified in the analysis options file.
- an analysis options file can be specified on the command line via
Dartium, dart2js, and DDC
- Imports to
dart:ioare allowed, but the imported library is not supported and will likely fail on most APIs at runtime. This change was made as a stopgap measure to make it easier to write libraries that share code between platforms (like packagehttp). This might change again when configuration specific imports are supported.
- Imports to
Pub
- Now sends telemetry data to
pub.dartlang.orgto allow better understanding of why a particular package is being accessed. pub publish- Warns if a package imports a package that’s not a dependency from within
lib/orbin/, or a package that’s not a dev dependency from withinbenchmark/,example/,test/ortool/. - No longer produces “UID too large” errors on OS X. All packages are now uploaded with the user and group names set to "pub".
- No longer fails with a stack overflow when uploading a package that uses Git submodules.
- Warns if a package imports a package that’s not a dependency from within
pub getandpub upgrade- Produce more informative error messages if they’re run directly in a package that uses Flutter.
- Properly unlock SDK and path dependencies if they have a new version that’s also valid according to the user’s pubspec.
- Now sends telemetry data to
dartfmt
- Support new generic function typedef syntax.
- Make the precedence of cascades more visible.
- Fix a couple of places where spurious newlines were inserted.
- Correctly report unchanged formatting when reading from stdin.
- Ensure space between
-and--. Code that does this is pathological, but it technically meant dartfmt could change the semantics of the code. - Preserve a blank line between enum cases.
- Other small formatting tweaks.
1.22.1 - 2017-02-22
Patch release, resolves two issues:
Dart VM crash: Issue 28072
Dart VM bug combining types, await, and deferred loading: Issue 28678
1.22.0 - 2017-02-14****Language
Breaking change: ‘Generalized tear-offs’ are no longer supported, and will cause errors. We updated the language spec and added warnings in 1.21, and are now taking the last step to fully de-support them. They were previously only supported in the VM, and there are almost no known uses of them in the wild.
The
assert()statement has been expanded to support an optional secondmessageargument (SDK issue 27342).The message is displayed if the assert fails. It can be any object, and it is accessible as
AssertionError.message. It can be used to provide more user friendly exception outputs. As an example, the following assert:assert(configFile != null, “Tool config missing. Please see https://goo.gl/k8iAi for details.”);
would produce the following exception output:
Unhandled exception: 'file:///Users/mit/tmp/tool/bin/main.dart': Failed assertion: line 9 pos 10: 'configFile != null': Tool config missing. Please see https://goo.gl/k8iAi for details. #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:33) #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:29) #2 main (file:///Users/mit/tmp/tool/bin/main.dart:9:10)The
Nulltype has been moved to the bottom of the type hierarchy. As such, it is considered a subtype of every other type. Thenullliteral was always treated as a bottom type. Now the named classNullis too:const empty = <Null>[];
String concatenate(List<String> parts) => parts.join(); int sum(List<int> numbers) => numbers.fold(0, (sum, n) => sum + n);
concatenate(empty); // OK. sum(empty); // OK.
Introduce
covariantmodifier on parameters. It indicates that the parameter (and the corresponding parameter in any method that overrides it) has looser override rules. In strong mode, these require a runtime type check to maintain soundness, but enable an architectural pattern that is useful in some code.It lets you specialize a family of classes together, like so:
abstract class Predator { void chaseAndEat(covariant Prey p); }
abstract class Prey {}
class Mouse extends Prey {}
class Seal extends Prey {}
class Cat extends Predator { void chaseAndEat(Mouse m) => … }
class Orca extends Predator { void chaseAndEat(Seal s) => … }
This isn’t statically safe, because you could do:
Predator predator = new Cat(); // Upcast. predator.chaseAndEat(new Seal()); // Cats can’t eat seals!
To preserve soundness in strong mode, in the body of a method that uses a covariant override (here,
Cat.chaseAndEat()), the compiler automatically inserts a check that the parameter is of the expected type. So the compiler gives you something like:class Cat extends Predator { void chaseAndEat(o) { var m = o as Mouse; … } }
Spec mode allows this unsound behavior on all parameters, even though users rarely rely on it. Strong mode disallowed it initially. Now, strong mode lets you opt into this behavior in the places where you do want it by using this modifier. Outside of strong mode, the modifier is ignored.
Change instantiate-to-bounds rules for generic type parameters when running in strong mode. If you leave off the type parameters from a generic type, we need to decide what to fill them in with. Dart 1.0 says just use
dynamic, but that isn’t sound:class Abser<T extends num> { void absThis(T n) { n.abs(); } }
var a = new Abser(); // Abser<dynamic>. a.absThis(“not a num”);
We want the body of
absThis()to be able to safely assumenis at least anum– that’s why there’s a constraint on T, after all. Implicitly usingdynamicas the type parameter in this example breaks that.Instead, strong mode uses the bound. In the above example, it fills it in with
num, and then the second line where a string is passed becomes a static error.However, there are some cases where it is hard to figure out what that default bound should be:
class RuhRoh<T extends Comparable<T>> {}
Strong mode’s initial behavior sometimes produced surprising, unintended results. For 1.22, we take a simpler approach and then report an error if a good default type argument can’t be found.
Core libraries
Define
FutureOr<T>for code that works with either a future or an immediate value of some type. For example, say you do a lot of text manipulation, and you want a handy function to chain a bunch of them:typedef String StringSwizzler(String input);
String swizzle(String input, List<StringSwizzler> swizzlers) { var result = input; for (var swizzler in swizzlers) { result = swizzler(result); }
return result; }
This works fine:
main() { var result = swizzle("input", [ (s) => s.toUpperCase(), (s) => () => s * 2) ]); print(result); // "INPUTINPUT". }
Later, you realize you’d also like to support swizzlers that are asynchronous (maybe they look up synonyms for words online). You could make your API strictly asynchronous, but then users of simple synchronous swizzlers have to manually wrap the return value in a
Future.value(). Ideally, yourswizzle()function would be "polymorphic over asynchrony". It would allow both synchronous and asynchronous swizzlers. Becauseawaitaccepts immediate values, it is easy to implement this dynamically:Future<String> swizzle(String input, List<StringSwizzler> swizzlers) async { var result = input; for (var swizzler in swizzlers) { result = await swizzler(result); }
return result; }
main() async { var result = swizzle("input", [ (s) => s.toUpperCase(), (s) => new Future.delayed(new Duration(milliseconds: 40), () => s * 2) ]); print(await result); }
What should the declared return type on StringSwizzler be? In the past, you had to use
dynamicorObject, but that doesn’t tell the user much. Now, you can do:typedef FutureOr<String> StringSwizzler(String input);
Like the name implies,
FutureOr<String>is a union type. It can be aStringor aFuture<String>, but not anything else. In this case, that’s not super useful beyond just stating a more precise type for readers of the code. It does give you a little better error checking in code that uses the result of that.FutureOr<T>becomes really important in generic methods likeFuture.then(). In those cases, having the type system understand this magical union type helps type inference figure out the type argument ofthen()based on the closure you pass it.Previously, strong mode had hard-coded rules for handling
Future.then()specifically.FutureOr<T>exposes that functionality so third-party APIs can take advantage of it too.
Tool changes
Dart2Js
- Remove support for (long-time deprecated) mixin typedefs.
Pub
Avoid using a barback asset server for executables unless they actually use transformers. This makes precompilation substantially faster, produces better error messages when precompilation fails, and allows globally-activated executables to consistently use the
Isolate.resolvePackageUri()API.On Linux systems, always ignore packages’ original file owners and permissions when extracting those packages. This was already the default under most circumstances.
Properly close the standard input stream of child processes started using
pub run.Handle parse errors from the package cache more gracefully. A package whose pubspec can’t be parsed will now be ignored by
pub get --offlineand deleted bypub cache repair.Make
pub runrun executables in spawned isolates. This lets them handle signals and use standard IO reliably.Fix source-maps produced by dart2js when running in
pub serve: URL references to assets from packages match the location wherepub serveserves them (packages/package_name/instead of../packages/package_name/).
Infrastructure changes
- The SDK now uses GN rather than gyp to generate its build files, which will now be exclusively ninja flavored. Documentation can be found on our wiki. Also see the help message of
tools/gn.py. This change is in response to the deprecation of gyp. Build file generation with gyp will continue to be available in this release by setting the environment variableDART_USE_GYPbefore runninggclient syncorgclient runhooks, but this will be removed in a future release.
1.21.1 - 2017-01-13
Patch release, resolves one issue:
- Dart VM: Snapshots of generic functions fail. Issue 28072
1.21.0 - 2016-12-07****Language
Support generic method syntax. Type arguments are not available at runtime. For details, check the informal specification.
Support access to initializing formals, e.g., the use of
xto initializeyinclass C { var x, y; C(this.x): y = x; }. Please check the informal specification for details.Don’t warn about switch case fallthrough if the case ends in a
rethrowstatement. (SDK issue 27650)Also don’t warn if the entire switch case is wrapped in braces - as long as the block ends with a
break,continue,rethrow,returnorthrow.Allow
=as well as:as separator for named parameter default values.enableFlags({bool hidden: false}) { … }
can now be replaced by
enableFlags({bool hidden = false}) { … }
(SDK issue 27559)
Core library changes
dart:core:Set.differencenow takes aSet<Object>as argument. (SDK issue 27573)dart:developer- Added
Serviceclass.- Allows inspecting and controlling the VM service protocol HTTP server.
- Provides an API to access the ID of an
Isolate.
- Added
Tool changes
Dart Dev Compiler
- Support calls to
loadLibrary()on deferred libraries. Deferred libraries are still loaded eagerly. (SDK issue 27343)
- Support calls to
1.20.1 - 2016-10-13
Patch release, resolves one issue:
- Dartium: Fixes a bug that caused crashes. No issue filed.
Strong Mode
It is no longer a warning when casting from dynamic to a composite type (SDK issue 27766).
main() { dynamic obj = <int>[1, 2, 3]; // This is now allowed without a warning. List<int> list = obj; }
1.20.0 - 2016-10-11****Dart VM
We have improved the way that the VM locates the native code library for a native extension (e.g.
dart-ext:import). We have updated this article on native extensions to reflect the VM’s improved behavior.Linux builds of the VM will now use the
tcmalloclibrary for memory allocation. This has the advantages of better debugging and profiling support and faster small allocations, with the cost of slightly larger initial memory footprint, and slightly slower large allocations.We have improved the way the VM searches for trusted root certificates for secure socket connections on Linux. First, the VM will look for trusted root certificates in standard locations on the file system (
/etc/pki/tls/certs/ca-bundle.crtfollowed by/etc/ssl/certs), and only if these do not exist will it fall back on the builtin trusted root certificates. This behavior can be overridden on Linux with the new flags--root-certs-fileand--root-certs-cache. The former is the path to a file containing the trusted root certificates, and the latter is the path to a directory containing root certificate files hashed usingc_rehash.The VM now throws a catchable
Errorwhen method compilation fails. This allows easier debugging of syntax errors, especially when testing. (SDK issue 23684)
Core library changes
dart:core: Remove deprecatedResourceclass. Use the class inpackage:resourceinstead.dart:asyncFuture.waitnow catches synchronous errors and returns them in the returned Future. (SDK issue 27249)- More aggressively returns a
FutureonStream.canceloperations. Discourages to returnnullfromcancel. (SDK issue 26777) - Fixes a few bugs where the cancel future wasn’t passed through transformations.
dart:io- Added
WebSocket.addUtf8Textto allow sending a pre-encoded text message without a round-trip UTF-8 conversion. (SDK issue 27129)
- Added
Strong Mode
Breaking change - it is an error if a generic type parameter cannot be inferred (SDK issue 26992).
class Cup<T> { Cup(T t); } main() { // Error because: // - if we choose Cup<num> it is not assignable to `cOfInt`, // - if we choose Cup<int> then `n` is not assignable to int. num n; C<int> cOfInt = new C(n); }
New feature - use
@checkedto override a method and tighten a parameter type (SDK issue 25578).import ‘package:meta/meta.dart’ show checked; class View { addChild(View v) {} } class MyView extends View { // this override is legal, it will check at runtime if we actually // got a MyView. addChild(@checked MyView v) {} } main() { dynamic mv = new MyView(); mv.addChild(new View()); // runtime error }
New feature - use
@virtualto allow field overrides in strong mode (SDK issue 27384).import ‘package:meta/meta.dart’ show virtual; class Base { @virtual int x; } class Derived extends Base { int x;
// Expose the hidden storage slot: int get superX => super.x; set superX(int v) { super.x = v; } }
Breaking change - infer list and map literals from the context type as well as their values, consistent with generic methods and instance creation (SDK issue 27151).
import 'dart:async’; main() async { var b = new Future<B>.value(new B()); var c = new Future<C>.value(new C()); var/*infer List<Future<A>>*/ list = [b, c]; var/*infer List<A>*/ result = await Future.wait(list); } class A {} class B extends A {} class C extends A {}
Tool changes
dartfmt- upgraded to v0.2.10- Don’t crash on annotations before parameters with trailing commas.
- Always split enum declarations if they end in a trailing comma.
- Add
--set-exit-if-changedto set the exit code on a change.
Pub
- Pub no longer generates a
packages/directory by default. Instead, it generates a.packagesfile, called a package spec. To generate apackages/directory in addition to the package spec, use the--packages-dirflag withpub get,pub upgrade, andpub downgrade. See the Good-bye symlinks article for details.
- Pub no longer generates a
1.19.1 - 2016-09-08
Patch release, resolves one issue:
- Dartdoc: Fixes a bug that prevented generation of docs. (Dartdoc issue 1233)
1.19.0 - 2016-08-26****Language changes
- The language now allows a trailing comma after the last argument of a call and the last parameter of a function declaration. This can make long argument or parameter lists easier to maintain, as commas can be left as-is when reordering lines. For details, see SDK issue 26644.
Tool Changes
dartfmt- upgraded to v0.2.9+1- Support trailing commas in argument and parameter lists.
- Gracefully handle read-only files.
- About a dozen other bug fixes.
Pub
Added a
--no-packages-dirflag topub get,pub upgrade, andpub downgrade. When this flag is passed, pub will not generate apackages/directory, and will remove that directory and any symlinks to it if they exist. Note that this replaces the unsupported--no-package-symlinksflag.Added the ability for packages to declare a constraint on the Flutter SDK:
environment: flutter: ^0.1.2 sdk: >=1.19.0 <2.0.0
A Flutter constraint will only be satisfiable when pub is running in the context of the
flutterexecutable, and when the Flutter SDK version matches the constraint.Added
sdkas a new package source that fetches packages from a hard-coded SDK. Currently only theflutterSDK is supported:dependencies: flutter_driver: sdk: flutter version: ^0.0.1
A Flutter
sdkdependency will only be satisfiable when pub is running in the context of theflutterexecutable, and when the Flutter SDK contains a package with the given name whose version matches the constraint.tarfiles on Linux are now created with0as the user and group IDs. This fixes a crash when publishing packages while using Active Directory.Fixed a bug where packages from a hosted HTTP URL were considered the same as packages from an otherwise-identical HTTPS URL.
Fixed timer formatting for timers that lasted longer than a minute.
Eliminate some false negatives when determining whether global executables are on the user’s executable path.
dart2jsdart2dart(akadart2js --output-type=dart) has been removed (this was deprecated in Dart 1.11).
Dart VM
- The dependency on BoringSSL has been rolled forward. Going forward, builds of the Dart VM including secure sockets will require a compiler with C++11 support. For details, see the Building wiki page.
Strong Mode
New feature - an option to disable implicit casts (SDK issue 26583), see the documentation for usage instructions and examples.
New feature - an option to disable implicit dynamic (SDK issue 25573), see the documentation for usage instructions and examples.
Breaking change - infer generic type arguments from the constructor invocation arguments (SDK issue 25220).
var map = new Map<String, String>();
// infer: Map<String, String> var otherMap = new Map.from(map);
Breaking change - infer local function return type (SDK issue 26414).
void main() { // infer: return type is int f() { return 40; } int y = f() + 2; // type checks print(y); }
Breaking change - allow type promotion from a generic type parameter (SDK issue 26414).
void fn/*<T>*/(/*=T*/ object) { if (object is String) { // Treat `object` as `String` inside this block. // But it will require a cast to pass it to something that expects `T`. print(object.substring(1)); } }
Breaking change - smarter inference for Future.then (SDK issue 25944). Previous workarounds that use async/await or
.then/*<Future<SomeType>>*/should no longer be necessary.// This will now infer correctly. Future<List<int>> t2 = f.then((_) => [3]); // This infers too. Future<int> t2 = f.then((_) => new Future.value(42));
Breaking change - smarter inference for async functions (SDK issue 25322).
void test() async { List<int> x = await [4]; // was previously inferred List<int> y = await new Future.value([4]); // now inferred too }
Breaking change - sideways casts are no longer allowed (SDK issue 26120).
1.18.1 - 2016-08-02
Patch release, resolves two issues and improves performance:
Debugger: Fixes a bug that crashes the VM (SDK issue 26941)
VM: Fixes an optimizer bug involving closures, try, and await (SDK issue 26948)
Dart2js: Speeds up generated code on Firefox (https://codereview.chromium.org/2180533002)
1.18.0 - 2016-07-27****Core library changes
dart:core- Improved performance when parsing some common URIs.
- Fixed bug in
Uri.resolve(SDK issue 26804).
dart:io- Adds file locking modes
FileLock.BLOCKING_SHAREDandFileLock.BLOCKING_EXCLUSIVE.
- Adds file locking modes
1.17.1 - 2016-06-10
Patch release, resolves two issues:
VM: Fixes a bug that caused crashes in async functions. (SDK issue 26668)
VM: Fixes a bug that caused garbage collection of reachable weak properties. (https://codereview.chromium.org/2041413005)
1.17.0 - 2016-06-08****Core library changes
dart:convert- Deprecate
ChunkedConverterwhich was erroneously added in 1.16.
- Deprecate
dart:coreUri.replacesupports iterables as values for the query parameters.Uri.parseIPv6Addressreturns aUint8List.
dart:io- Added
NetworkInterface.listSupported, which istruewhenNetworkInterface.listis supported, andfalseotherwise. Currently,NetworkInterface.listis not supported on Android.
- Added
Tool Changes
Pub
TAR files created while publishing a package on Mac OS and Linux now use a more portable format.
Errors caused by invalid arguments now print the full usage information for the command.
SDK constraints for dependency overrides are no longer considered when determining the total SDK constraint for a lockfile.
A bug has been fixed in which a lockfile was considered up-to-date when it actually wasn’t.
A bug has been fixed in which
pub get --offlinewould crash when a prerelease version was selected.
Dartium and content shell
- Debugging Dart code inside iframes improved, was broken.
1.16.1 - 2016-05-24
Patch release, resolves one issue:
- VM: Fixes a bug that caused intermittent hangs on Windows. (SDK issue 26400)
1.16.0 - 2016-04-26****Core library changes
dart:convertAdded
BASE64URLcodec and correspondingBase64Codec.urlSafeconstructor.Introduce
ChunkedConverterand deprecate chunked methods onConverter.
dart:htmlThere have been a number of BREAKING changes to align APIs with recent changes in Chrome. These include:
Chrome’s
ShadowRootinterface no longer has the methodsgetElementById,getElementsByClassName, andgetElementsByTagName, e.g.,elem.shadowRoot.getElementsByClassName(‘clazz’)
should become:
elem.shadowRoot.querySelectorAll(‘.clazz’)
The
clipboardDataproperty has been removed fromKeyEventandEvent. It has been moved to the newClipboardEventclass, which is now used bycopy,cut, andpasteevents.The
layerproperty has been removed fromKeyEventandUIEvent. It has been moved toMouseEvent.The
Point get pageproperty has been removed fromUIEvent. It still exists onMouseEventandTouch.
There have also been a number of other additions and removals to `dart:html`, `dart:indexed_db`, `dart:svg`, `dart:web_audio`, and `dart:web_gl` that correspond to changes to Chrome APIs between v39 and v45. Many of the breaking changes represent APIs that would have caused runtime exceptions when compiled to Javascript and run on recent Chrome releases.
dart:io- Added
SecurityContext.alpnSupported, which is true if a platform supports ALPN, and false otherwise.
- Added
JavaScript interop
For performance reasons, a potentially BREAKING change was added for libraries that use JS interop. Any Dart file that uses @JS annotations on declarations (top-level functions, classes or class members) to interop with JavaScript code will require that the file have the annotation @JS() on a library directive.
@JS() library my_library;
The analyzer will enforce this by generating the error:
The @JS() annotation can only be used if it is also declared on the library directive.
If part file uses the @JS() annotation, the library that uses the part should have the @JS() annotation e.g.,
// library_1.dart @JS() library library_1;
import 'package:js/js.dart’;
part 'part_1.dart’;
// part_1.dart part of library_1;
@JS(“frameworkStabilizers”) external List<FrameworkStabilizer> get frameworkStabilizers;
If your library already has a JS module e.g.,
@JS(‘array.utils’) library my_library;
Then your library will work without any additional changes.
Analyzer
Static checking of
for instatements. These will now produce static warnings:// Not Iterable. for (var i in 1234) { … }
// String cannot be assigned to int. for (int n in <String>["a", “b”]) { … }
Tool Changes
Pub
pub servenow provides caching headers that should improve the performance of requesting large files multiple times.Both
pub getandpub upgradenow have a--no-precompileflag that disables precompilation of executables and transformed dependencies.pub publishnow resolves symlinks when publishing from a Git repository. This matches the behavior it always had when publishing a package that wasn’t in a Git repository.
Dart Dev Compiler
The experimental
dartdevcexecutable has been added to the SDK.It will help early adopters validate the implementation and provide feedback.
dartdevcis not yet ready for production usage.Read more about the Dart Dev Compiler here.
1.15.0 - 2016-03-09****Core library changes
dart:async- Made
StreamViewclass aconstclass.
- Made
dart:core- Added
Uri.queryParametersAllto handle multiple query parameters with the same name.
- Added
dart:io- Added
SecurityContext.usePrivateKeyBytes,SecurityContext.useCertificateChainBytes,SecurityContext.setTrustedCertificatesBytes, andSecurityContext.setClientAuthoritiesBytes. - Breaking The named
directoryargument ofSecurityContext.setTrustedCertificateshas been removed. - Added support to
SecurityContextfor PKCS12 certificate and key containers. - All calls in
SecurityContextthat accept certificate data now accept an optional named parameterpassword, similar toSecurityContext.usePrivateKeyBytes, for use as the password for PKCS12 data.
- Added
Tool changes
Dartium and content shell
- The Chrome-based tools that ship as part of the Dart SDK - Dartium and content shell - are now based on Chrome version 45 (instead of Chrome 39).
- Dart browser libraries (
dart:html,dart:svg, etc) have not been updated.- These are still based on Chrome 39.
- These APIs will be updated in a future release.
- Note that there are experimental APIs which have changed in the underlying browser, and will not work with the older libraries. For example,
Element.animate.
dartfmt- upgraded to v0.2.4- Better handling for long collections with comments.
- Always put member metadata annotations on their own line.
- Indent functions in named argument lists with non-functions.
- Force the parameter list to split if a split occurs inside a function-typed parameter.
- Don’t force a split for before a single named argument if the argument itself splits.
Service protocol changes
- Fixed a documentation bug where the field
extensionRPCsinIsolatewas not marked optional.
Experimental language features
Added support for configuration-specific imports. On the VM and
dart2js, they can be enabled with--conditional-directives.The analyzer requires additional configuration:
analyzer: language: enableConditionalDirectives: true
Read about configuring the analyzer for more details.
1.14.2 - 2016-02-10
Patch release, resolves three issues:
VM: Fixed a code generation bug on x64. (SDK commit 834b3f02)
dart:io: Fixed EOF detection when reading some special device files. (SDK issue 25596)Pub: Fixed an error using hosted dependencies in SDK version 1.14. (Pub issue 1386)
1.14.1 - 2016-02-04
Patch release, resolves one issue:
- Debugger: Fixes a VM crash when a debugger attempts to set a break point during isolate initialization. (SDK issue 25618)
1.14.0 - 2016-01-28****Core library changes
dart:async- Added
Future.anystatic method. - Added
Stream.fromFuturesconstructor.
- Added
dart:convertBase64Decoder.convertnow takes optionalstartandendparameters.
dart:core- Added
currentgetter toStackTraceclass. Uriclass added support for data URIs- Added two new constructors:
dataFromBytesanddataFromString. - Added a
datagetter fordata:URIs with a newUriDataclass for the return type.
- Added two new constructors:
- Added
growableparameter toList.filledconstructor. - Added microsecond support to
DateTime:DateTime.microsecond,DateTime.microsecondsSinceEpoch, andnew DateTime.fromMicrosecondsSinceEpoch.
- Added
dart:mathRandomadded asecureconstructor returning a cryptographically secure random generator which reads from the entropy source provided by the embedder for every generated random value.
dart:ioPlatformadded a staticisIOSgetter andPlatform.operatingSystemmay now returnios.Platformadded a staticpackageConfiggetter.- Added support for WebSocket compression as standardized in RFC 7692.
- Compression is enabled by default for all WebSocket connections.
- The optionally named parameter
compressionon the methodsWebSocket.connect,WebSocket.fromUpgradedSocket, andWebSocketTransformer.upgradeand theWebSocketTransformerconstructor can be used to modify or disable compression using the newCompressionOptionsclass.
- The optionally named parameter
dart:isolate- Added experimental support for Package Resolution Configuration.
- Added
packageConfigandpackageRootinstance getters toIsolate. - Added a
resolvePackageUrimethod toIsolate. - Added named arguments
packageConfigandautomaticPackageResolutionto theIsolate.spawnUriconstructor.
- Added
- Added experimental support for Package Resolution Configuration.
Tool changes
dartfmtBetter line splitting in a variety of cases.
Other optimizations and bug fixes.
Pub
Breaking: Pub now eagerly emits an error when a pubspec’s “name” field is not a valid Dart identifier. Since packages with non-identifier names were never allowed to be published, and some of them already caused crashes when being written to a
.packagesfile, this is unlikely to break many people in practice.Breaking: Support for
barbackversions prior to 0.15.0 (released July- has been dropped. Pub will no longer install these older barback versions.
pub servenow GZIPs the assets it serves to make load times more similar to real-world use-cases.pub depsnow supports a--no-devflag, which causes it to emit the dependency tree as it would be if nodev_dependencieswere in use. This makes it easier to see your package’s dependency footprint as your users will experience it.pub global runnow detects when a global executable’s SDK constraint is no longer met and errors out, rather than trying to run the executable anyway.Pub commands that check whether the lockfile is up-to-date (
pub run,pub deps,pub serve, andpub build) now do additional verification. They ensure that any path dependencies’ pubspecs haven’t been changed, and they ensure that the current SDK version is compatible with all dependencies.Fixed a crashing bug when using
pub global runon a global script that didn’t exist.Fixed a crashing bug when a pubspec contains a dependency without a source declared.
1.13.2 - 2016-01-06
Patch release, resolves one issue:
- dart2js: Stack traces are not captured correctly (SDK issue [25235] (https://github.com/dart-lang/sdk/issues/25235))
1.13.1 - 2015-12-17
Patch release, resolves three issues:
VM type propagation fix: Resolves a potential crash in the Dart VM (SDK commit [dff13be] (https://github.com/dart-lang/sdk/commit/dff13bef8de104d33b04820136da2d80f3c835d7))
dart2js crash fix: Resolves a crash in pkg/js and dart2js (SDK issue [24974] (https://github.com/dart-lang/sdk/issues/24974))
Pub get crash on ARM: Fixes a crash triggered when running ‘pub get’ on ARM processors such as those on a Raspberry Pi (SDK issue [24855] (https://github.com/dart-lang/sdk/issues/24855))
1.13.0 - 2015-11-18****Core library changes
dart:asyncStreamControlleradded getters foronListen,onPause, andonResumewith the corresponding newtypedef void ControllerCallback().StreamControlleradded a getter foronCancelwith the corresponding newtypedef ControllerCancelCallback();StreamTransformerinstances created withfromHandlerswith nohandleErrorcallback now forward stack traces along with errors to the resulting streams.
dart:convert- Added support for Base-64 encoding and decoding.
- Added new classes
Base64Codec,Base64Encoder, andBase64Decoder. - Added new top-level
const Base64Codec BASE64.
- Added new classes
- Added support for Base-64 encoding and decoding.
dart:coreUriaddedremoveFragmentmethod.String.allMatches(implementingPattern.allMatches) is now lazy, as allallMatchesimplementations are intended to be.Resourceis deprecated, and will be removed in a future release.
dart:developer- Added
Timelineclass for interacting with Observatory’s timeline feature. - Added
ServiceExtensionHandler,ServiceExtensionResponse, andregisterExtensionwhich enable developers to provide their own VM service protocol extensions.
- Added
dart:html,dart:indexed_db,dart:svg,dart:web_audio,dart:web_gl,dart:web_sql- The return type of some APIs changed from
doubletonum. Dartium is now using JS interop for most operations. JS does not distinguish between numeric types, and will return a number as an int if it fits in an int. This will mostly cause an error if you assign to something typeddoublein checked mode. You may need to insert atoDouble()call or acceptnum. Examples of APIs that are affected includeElement.getBoundingClientRectandTextMetrics.width.
- The return type of some APIs changed from
dart:ioBreaking: Secure networking has changed, replacing the NSS library with the BoringSSL library.
SecureSocket,SecureServerSocket,RawSecureSocket,RawSecureServerSocket,HttpClient, andHttpServernow all use aSecurityContextobject which contains the certificates and keys used for secure TLS (SSL) networking.This is a breaking change for server applications and for some client applications. Certificates and keys are loaded into the
SecurityContextfrom PEM files, instead of from an NSS certificate database. Information about how to change applications that use secure networking is at https://www.dartlang.org/server/tls-ssl.htmlHttpClientno longer sends URI fragments in the request. This is not allowed by the HTTP protocol. TheHttpServerstill gracefully receives fragments, but discards them before delivering the request.To allow connections to be accepted on the same port across different isolates, set the
sharedargument totruewhen creating server socket andHttpServerinstances.- The deprecated
ServerSocketReferenceandRawServerSocketReferenceclasses have been removed. - The corresponding
referenceproperties onServerSocketandRawServerSockethave been removed.
- The deprecated
dart:isolatespawnUriadded anenvironmentnamed argument.
Tool changes
dart2jsand Dartium now support improved Javascript Interoperability via the js package.docgenanddartdocgenno longer ship in the SDK. Thedocgensources have been removed from the repository.This is the last release to ship the VM’s "legacy debug protocol". We intend to remove the legacy debug protocol in Dart VM 1.14.
The VM’s Service Protocol has been updated to version 3.0 to take care of a number of issues uncovered by the first few non-observatory clients. This is a potentially breaking change for clients.
Dartium has been substantially changed. Rather than using C++ calls into Chromium internals for DOM operations it now uses JS interop. The DOM objects in
dart:htmland related libraries now wrap a JavaScript object and delegate operations to it. This should be mostly transparent to users. However, performance and memory characteristics may be different from previous versions. There may be some changes in which DOM objects are wrapped as Dart objects. For example, if you get a reference to a Window object, even through JS interop, you will always see it as a Dart Window, even when used cross-frame. We expect the change to using JS interop will make it much simpler to update to new Chrome versions.
1.12.2 - 2015-10-21****Core library changes
dart:io- A memory leak in creation of Process objects is fixed.
1.12.1 - 2015-09-08****Tool changes
Pub
Pub will now respect
.gitignorewhen validating a package before it’s published. For example, if aLICENSEfile exists but is ignored, that is now an error.If the package is in a subdirectory of a Git repository and the entire subdirectory is ignored with
.gitignore, pub will act as though nothing was ignored instead of uploading an empty package.The heuristics for determining when
pub getneeds to be run before various commands have been improved. There should no longer be false positives when non-dependency sections of the pubspec have been modified.
1.12.0 - 2015-08-31****Language changes
- Null-aware operators
??: if null operator.expr1 ?? expr2evaluates toexpr1if notnull, otherwiseexpr2.??=: null-aware assignment.v ??= exprcausesvto be assignedexpronly ifvisnull.x?.p: null-aware access.x?.pevaluates tox.pifxis notnull, otherwise evaluates tonull.x?.m(): null-aware method invocation.x?.m()invokesmonly ifxis notnull.
Core library changes
dart:asyncStreamControlleradded setters for theonListen,onPause,onResumeandonCancelcallbacks.
dart:convertLineSplitteradded asplitstatic method returning anIterable.
dart:coreUriclass now perform path normalization when a URI is created. This removes most..and.sequences from the URI path. Purely relative paths (no scheme or authority) are allowed to retain some leading “dot” segments. Also addedhasAbsolutePath,hasEmptyPath, andhasSchemeproperties.
dart:developer- New
logfunction to transmit logging events to Observatory.
- New
dart:htmlNodeTreeSanitizeradded theconst trustedfield. It can be used instead of defining aNullTreeSanitizerclass when callingsetInnerHtmlor other methods that create DOM from text. It is also more efficient, skipping the creation of aDocumentFragment.
dart:io- Added two new file modes,
WRITE_ONLYandWRITE_ONLY_APPENDfor opening a file write only. eaeecf2 - Change stdout/stderr to binary mode on Windows. 4205b29
- Added two new file modes,
dart:isolate- Added
onError,onExitanderrorsAreFatalparameters toIsolate.spawnUri.
- Added
dart:mirrorsInstanceMirror.delegatemoved up toObjectMirror.- Fix InstanceMirror.getField optimization when the selector is an operator.
- Fix reflective NoSuchMethodErrors to match their non-reflective counterparts when due to argument mismatches. (VM only)
Tool changes
Documentation tools
dartdocis now the default tool to generate static HTML for API docs. Learn more.docgenanddartdocgenhave been deprecated. Currently plan is to remove them in 1.13.
Formatter (
dartfmt)Over 50 bugs fixed.
Optimized line splitter is much faster and produces better output on complex code.
Observatory
Allocation profiling.
New feature to display output from logging.
Heap snapshot analysis works for 64-bit VMs.
Improved ability to inspect typed data, regex and compiled code.
Ability to break on all or uncaught exceptions from Observatory’s debugger.
Ability to set closure-specific breakpoints.
‘anext’ - step past await/yield.
Preserve when a variable has been expanded/unexpanded in the debugger.
Keep focus on debugger input box whenever possible.
Echo stdout/stderr in the Observatory debugger. Standalone-only so far.
Minor fixes to service protocol documentation.
Pub
Breaking: various commands that previously ran
pub getimplicitly no longer do so. Instead, they merely check to make sure the “.packages” file is newer than the pubspec and the lock file, and fail if it’s not.Added support for
--verbosity=errorand--verbosity=warning.pub servenow collapses multiple GET requests into a single line of output. For full output, use--verbose.pub depshas improved formatting for circular dependencies on the entrypoint package.pub runandpub global runBreaking: to match the behavior of the Dart VM, executables no longer run in checked mode by default. A
--checkedflag has been added to run them in checked mode manually.Faster start time for executables that don’t import transformed code.
Binstubs for globally-activated executables are now written in the system encoding, rather than always in
UTF-8. To update existing executables, runpub cache repair.
pub getandpub upgradePub will now generate a “.packages” file in addition to the “packages” directory when running
pub getor similar operations, per the package spec proposal. Pub now has a--no-package-symlinksflag that will stop “packages” directories from being generated at all.An issue where HTTP requests were sometimes made even though
--offlinewas passed has been fixed.A bug with
--offlinethat caused an unhelpful error message has been fixed.Pub will no longer time out when a package takes a long time to download.
pub publishPub will emit a non-zero exit code when it finds a violation while publishing.
.gitignorefiles will be respected even if the package isn’t at the top level of the Git repository.
Barback integration
A crashing bug involving transformers that only apply to non-public code has been fixed.
A deadlock caused by declaring transformer followed by a lazy transformer (such as the built-in
$dart2jstransformer) has been fixed.A stack overflow caused by a transformer being run multiple times on the package that defines it has been fixed.
A transformer that tries to read a non-existent asset in another package will now be re-run if that asset is later created.
VM Service Protocol Changes
BREAKING The service protocol now sends JSON-RPC 2.0-compatible server-to-client events. To reflect this, the service protocol version is now 2.0.
The service protocol now includes a
"jsonrpc"property in its responses, as opposed to"json-rpc".The service protocol now properly handles requests with non-string ids. Numeric ids are no longer converted to strings, and null ids now don’t produce a response.
Some RPCs that didn’t include a
"jsonrpc"property in their responses now include one.
1.11.2 - 2015-08-03****Core library changes
- Fix a bug where
WebSocket.close()would crash if called afterWebSocket.cancel().
1.11.1 - 2015-07-02****Tool changes
- Pub will always load Dart SDK assets from the SDK whose
pubexecutable was run, even if aDART_SDKenvironment variable is set.
1.11.0 - 2015-06-25****Core library changes
dart:coreIterableadded anemptyconstructor. dcf0286Iterablecan now be extended directly. An alternative to extendingIterableBasefromdart:collection.Listadded anunmodifiableconstructor. r45334Mapadded anunmodifiableconstructor. r45733intadded agcdmethod. a192ef4intadded amodInversemethod. f6f338cStackTraceadded afromStringconstructor. 68dd6f6Uriadded adirectoryconstructor. d8dbb4a- List iterators may not throw
ConcurrentModificationErroras eagerly in release mode. In checked mode, the modification check is still as eager as possible. r45198
dart:developer- NEW- Replaces the deprecated
dart:profilerlibrary. - Adds new functions
debuggerandinspect. 6e42aec
- Replaces the deprecated
dart:ioFileSystemEntityadded auriproperty. 8cf32dcPlatformadded astatic resolvedExecutableproperty. c05c8c6
dart:htmlElementmethods,appendHtmlandinsertAdjacentHtmlnow takenodeValidatorandtreeSanitizerparameters, and the inputs are consistently sanitized. r45818 announcement
dart:isolate- BREAKING The positional
priorityparameter ofIsolate.pingandIsolate.killis now a named parameter namedpriority. - BREAKING Removed the
Isolate.AS_EVENTpriority. IsolatemethodspingandaddOnExitListenernow have a named parameterresponse. r45092Isolate.spawnUriadded a named argumentchecked.- Remove the experimental state of the API.
- BREAKING The positional
dart:profiler- DEPRECATED- This library will be removed in 1.12. Use
dart:developerinstead.
- This library will be removed in 1.12. Use
Tool changes
- This is the first release that does not include the Eclipse-based Dart Editor. See dartlang.org/tools for alternatives.
- This is the last release that ships the (unsupported) dart2dart (aka
dart2js --output-type=dart) utility as part of dart2js
1.10.0 - 2015-04-29****Core library changes
dart:convert- POTENTIALLY BREAKING Fix behavior of
HtmlEscape. It no longer escapes no-break space (U+00A0) anywhere or forward slash (/,U+002F) in element context. Slash is still escaped usingHtmlEscapeMode.UNKNOWN. r45003, r45153, r45189
- POTENTIALLY BREAKING Fix behavior of
dart:coreUri.parseaddedstartandendpositional arguments.
dart:html- POTENTIALLY BREAKING
CssClassSetmethod arguments must now be 'tokens’, i.e. non-empty strings with no white-space characters. The implementation was incorrect for class names containing spaces. The fix is to forbid spaces and provide a faster implementation. Announcement
- POTENTIALLY BREAKING
dart:ioProcessResultnow exposes a constructor.importandIsolate.spawnUrinow supports the Data URI scheme on the VM.
Tool Changes****pub
Running
pub run foowithin a package now runs thefooexecutable defined by thefoopackage. The previous behavior ranbin/foo. This makes it easy to run binaries in dependencies, for instancepub run test.On Mac and Linux, signals sent to
pub runand forwarded to the child command.
1.9.3 - 2015-04-14
This is a bug fix release which merges a number of commits from bleeding_edge.
dart2js: Addresses as issue with minified Javascript output with CSP enabled - r44453
Editor: Fixes accidental updating of files in the pub cache during rename refactoring - r44677
Editor: Fix for issue 23032 regarding skipped breakpoints on Windows - r44824
dart:mirrors: Fix
MethodMirror.sourcewhen the method is on the first line in a script - r44957, r44976pub: Fix for issue 23084: Pub can fail to load transformers necessary for local development - r44876
1.9.1 - 2015-03-25****Language changes
Support for
async,await,sync*,async*,yield,yield*, andawait for. See the the language tour for more details.Enum support is fully enabled. See the language tour for more details.
Tool changes
The formatter is much more comprehensive and generates much more readable code. See its tool page for more details.
The analysis server is integrated into the IntelliJ plugin and the Dart editor. This allows analysis to run out-of-process, so that interaction remains smooth even for large projects.
Analysis supports more and better hints, including unused variables and unused private members.
Core library changes****Highlights
There’s a new model for shared server sockets with no need for a
Socketreference.A new, much faster regular expression engine.
The Isolate API now works across the VM and
dart2js.
Details
For more information on any of these changes, see the corresponding documentation on the Dart API site.
dart:async:Future.waitadded a new named argument,cleanUp, which is a callback that releases resources allocated by a successfulFuture.The
SynchronousStreamControllerclass was added as an explicit name for the type returned when thesyncargument is passed tonew StreamController.
dart:collection: Thenew SplayTreeSet.from(Iterable)constructor was added.dart:convert:Utf8Encoder.convertandUtf8Decoder.convertadded optionalstartandendarguments.dart:core:RangeErroradded new static helper functions:checkNotNegative,checkValidIndex,checkValidRange, andcheckValueInInterval.intadded themodPowfunction.Stringadded thereplaceFirstMappedandreplaceRangefunctions.
dart:io:Support for locking files to prevent concurrent modification was added. This includes the
File.lock,File.lockSync,File.unlock, andFile.unlockSyncfunctions as well as theFileLockclass.Support for starting detached processes by passing the named
modeargument (aProcessStartMode) toProcess.start. A process can be fully attached, fully detached, or detached except for its standard IO streams.HttpServer.bindandHttpServer.bindSecureadded thev6Onlynamed argument. If this is true, only IPv6 connections will be accepted.HttpServer.bind,HttpServer.bindSecure,ServerSocket.bind,RawServerSocket.bind,SecureServerSocket.bindandRawSecureServerSocket.bindadded thesharednamed argument. If this is true, multiple servers or sockets in the same Dart process may bind to the same address, and incoming requests will automatically be distributed between them.Deprecation: the experimental
ServerSocketReferenceandRawServerSocketReferenceclasses, as well as getters that returned them, are marked as deprecated. Thesharednamed argument should be used instead. These will be removed in Dart 1.10.Socket.connectandRawSocket.connectadded thesourceAddressnamed argument, which specifies the local address to bind when making a connection.The static
Process.killPidmethod was added to kill a process with a given PID.Stdoutadded thenonBlockinginstance property, which returns a non-blockingIOSinkthat writes to standard output.
dart:isolate:The static getter
Isolate.currentwas added.The
IsolatemethodsaddOnExitListener,removeOnExitListener,setErrorsFatal,addOnErrorListener, andremoveOnErrorListenernow work on the VM.Isolates spawned via
Isolate.spawnnow allow most objects, including top-level and static functions, to be sent between them.
1.8.5 - 2015-01-21
Code generation for SIMD on ARM and ARM64 is fixed.
A possible crash on MIPS with newer GCC toolchains has been prevented.
A segfault when using
rethrowwas fixed (issue 21795).
1.8.3 - 2014-12-10
Breakpoints can be set in the Editor using file suffixes (issue 21280).
IPv6 addresses are properly handled by
HttpClientindart:io, fixing a crash in pub (issue 21698).Issues with the experimental
async/awaitsyntax have been fixed.Issues with a set of number operations in the VM have been fixed.
ListBaseindart:collectionalways returns anIterablewith the correct type argument.
1.8.0 - 2014-11-28
dart:collection:SplayTreeadded thetoSetfunction.dart:convert: TheJsonUtf8Encoderclass was added.dart:core:The
IndexErrorclass was added for errors caused by an index being outside its expected range.The
new RangeError.indexconstructor was added. It forwards tonew IndexError.RangeErroradded three new properties.invalidPropertyis the value that caused the error, andstartandendare the minimum and maximum values that the value is allowed to assume.new RangeError.valueandnew RangeError.rangeadded an optionalmessageargument.The
new String.fromCharCodesconstructor added optionalstartandendarguments.
dart:io:Support was added for the Application-Layer Protocol Negotiation extension to the TLS protocol for both the client and server.
SecureSocket.connect,SecureServerSocket.bind,RawSecureSocket.connect,RawSecureSocket.secure,RawSecureSocket.secureServer, andRawSecureServerSocket.bindadded asupportedProtocolsnamed argument for protocol negotiation.RawSecureServerSocketadded asupportedProtocolsfield.RawSecureSocketandSecureSocketadded aselectedProtocolfield which contains the protocol selected during protocol negotiation.
1.7.0 - 2014-10-15****Tool changes
pubnow generates binstubs for packages that are globally activated so that they can be put on the user’sPATHand used as normal executables. See thepub global activatedocumentation.When using
dart2js, deferred loading now works with multiple Dart apps on the same page.
Core library changes
dart:async:Zone,ZoneDelegate, andZoneSpecificationadded theerrorCallbackfunction, which allows errors that have been programmatically added to aFutureorStreamto be intercepted.dart:io:Breaking change:
HttpClient.closemust be called for all clients or they will keep the Dart process alive until they time out. This fixes the handling of persistent connections. Previously, the client would shut down immediately after a request.Breaking change:
HttpServerno longer compresses all traffic by default. The newautoCompressproperty can be set totrueto re-enable compression.
dart:isolate:Isolate.spawnUriadded the optionalpackageRootargument, which controls how it resolvespackage:URIs.