Dart 3.6 adds digit separators to the language. To use them, set your package's SDK constraint lower bound to 3.6 or greater (sdk: '^3.6.0'
).
Digits in number literals (decimal integer literals, double literals, scientific notation literals, and hexadecimal literals) can now include underscores between digits, as “digit separators.” The separators do not change the value of a literal, but can serve to make the number more readable.
100__000_000__000_000__000_000 // one hundred million million millions! 0x4000_0000_0000_0000 0.000_000_000_01 0x00_14_22_01_23_45 // MAC address
Separators are not allowed at the start of a number (this would be parsed as an identifier), at the end of a number, or adjacent to another character in a number, like .
, x
, or the e
in scientific notation.
throw
expression has been changed from the “unknown type” to Object
. This makes the type system more self-consistent, because it reflects the fact that it's not legal to throw null
. This change is not expected to make any difference in practice.dart:io
Breaking Change #52444: Removed the Platform()
constructor, which has been deprecated since Dart 3.1.
Breaking Change #53618: HttpClient
now responds to a redirect that is missing a “Location” header by throwing RedirectException
, instead of StateError
.
dart:js_interop
JSArrayBuffer
, JSDataView
, and concrete typed array types e.g. JSInt8Array
.length
and []
/[]=
operators to JSArray
.toJSCaptureThis
so this
is passed in from JavaScript to the callback as the first parameter.from
method on JSArray
to create a JSArray
from a given JavaScript iterable or array-like object.dart.library.js
is now false on conditional imports in dart2wasm. Note that it was already a static error to import dart:js
directly (see #55266).ZLibDecoder
would incorrectly attempt to decompress data past the end of the zlib footer (issue #56481).dart
from PATH
could result in some commands not working as expected (issues #56080, #56306, #56499).setContextRoots
requests or being provided incorrect context roots in multi-package workspaces (issue #56475).include:
in analysis_options.yaml
file in a nested folder in the workspace (issue#56464).dart compile wasm
when optimizations are enabled (issue #56423).dart2wasm
compiler in unsound -O3
/ -O4
modes where a implicit setter for a field of generic type will store null
instead of the field value (issue #56374).dart2wasm
compiler that can trigger in certain situations when using partial instantiations of generic tear-offs (constructors or static methods) in constant expressions (issue #56440).StructuralParameterType
objects. In some corner cases cases the lacking implementation resulted in a crash of the compiler (issue #56457).Breaking Change #55418: The context used by the compiler to perform type inference on the operand of an await
expression has been changed to match the behavior of the analyzer. This change is not expected to make any difference in practice.
Breaking Change #55436: The context used by the compiler to perform type inference on the right hand side of an “if-null” expression (e1 ?? e2
) has been changed to match the behavior of the analyzer. change is expected to have low impact on real-world code. But in principle it could cause compile-time errors or changes in runtime behavior by changing inferred types. The old behavior can be restored by supplying explicit types.
dart:core
DateTime
on the web platform now stores microseconds. The web implementation is now practically compatible with the native implementation, where it is possible to round-trip a timestamp in microseconds through a DateTime
value without rounding the lower digits. This change might be breaking for apps that rely in some way on the .microsecond
component always being zero, for example, expecting only three fractional second digits in the toString()
representation. Small discrepancies in arithmetic due to rounding of web integers may still occur for extreme values, (1) microsecondsSinceEpoch
outside the safe range, corresponding to dates with a year outside of 1685..2255, and (2) arithmetic (add
, subtract
, difference
) where the Duration
argument or result exceeds 570 years.dart:io
Breaking Change #55786: SecurityContext
is now final
. This means that SecurityContext
can no longer be subclassed. SecurityContext
subclasses were never able to interoperate with other parts of dart:io
.
A ConnectionTask
can now be created using an existing Future<Socket>
. Fixes #55562.
dart:typed_data
Breaking Change #53785: The unmodifiable view classes for typed data have been removed. These classes were deprecated in Dart 3.4.
To create an unmodifiable view of a typed-data object, use the asUnmodifiableView()
methods added in Dart 3.3.
Added superinterface TypedDataList
to typed data lists, implementing both List
and TypedData
. Allows abstracting over all such lists without losing access to either the List
or the TypedData
members. A ByteData
is still only a TypedData
, not a list.
dart:js_interop
Breaking Change #55508: importModule
now accepts a JSAny
instead of a String
to support other JS values as well, like TrustedScriptURL
s.
Breaking Change #55267: isTruthy
and not
now return JSBoolean
instead of bool
to be consistent with the other operators.
Breaking Change ExternalDartReference
no longer implements Object
. ExternalDartReference
now accepts a type parameter T
with a bound of Object?
to capture the type of the Dart object that is externalized. ExternalDartReferenceToObject.toDartObject
now returns a T
. ExternalDartReferenceToObject
and ObjectToExternalDartReference
are now extensions on T
and ExternalDartReference<T>
, respectively, where T extends Object?
. See #55342 and #55536 for more details.
Fixed some consistency issues with Function.toJS
across all compilers. Specifically, calling Function.toJS
on the same function gives you a new JS function (see issue #55515), the maximum number of arguments that are passed to the JS function is determined by the static type of the Dart function, and extra arguments are dropped when passed to the JS function in all compilers (see #48186).
unintended_html_in_doc_comment
lint.invalid_runtime_check_with_js_interop_types
lint.document_ignores
lint.dart pub downgrade --tighten
to restrict lower bounds of dependencies' constraints to the minimum that can be resolved.The Dart VM only executes sound null safe code, running of unsound null safe code using the option --no-sound-null-safety
has been removed.
Dart_NewListOf
and Dart_IsLegacyType
functions are removed from Dart C API.
Dart_DefaultCanonicalizeUrl
is removed from the Dart C API.
This is a patch release that:
Fixes an issue where pub would crash when failing to fetch advisories from the server. (issue pub#4269).
Fixes an issue where const bool.fromEnvironment('dart.library.ffi')
is true and conditional import condition dart.library.ffi
is true in dart2wasm. (issue #55948).
Fixes an issue where FFI calls with variadic arguments on MacOS Arm64 would mangle the arguments. (issue #55943).
This is a patch release that:
Fixes an issue where DART_VM_OPTIONS
were not correctly parsed for standalone Dart executables created with dart compile exe
(issue #55818).
Fixes a bug in dart2wasm that can result in a runtime error that says array.new_fixed()
has a constant larger than 10000 (issue #55873).
Adds support for --enable-experiment
flag to dart compile
wasm (issue #55894).
Fixes an issue in dart2wasm compiler that can result in incorrect nullability of type parameter (see #55895).
Disallows dart:ffi
imports in user code in dart2wasm (e.g. issue [#53910]) as dart2wasm's currently only supports a small subset of dart:ffi
(issue #55890).
This is a patch release that:
Marks dart compile wasm
as no longer experimental.
Fixes two bugs in exception handling in async
functions in dart2wasm (issues #55347, #55457).
Fixes restoration of this
variable in sync*
and async
functions in dart2wasm.
Implements missing control flow constructs (exceptions, switch/case with yields) in sync*
in dart2wasm (issues #51342, #51343).
Fixes a bug dart2wasm compiler that surfaces as a compiler crash when indexing lists where the compiler proofs the list to be constant and the index is out-of-bounds (issue #55817).
This is a patch release that:
Fixes a bug in the CFE which could manifest as compilation errors of Flutter web apps when compiled with dart2wasm (issue #55714).
Fixes a bug in the pub client, such that dart run
will not interfere with Flutter l10n (at least for most cases) (issue #55758).
Dart 3.4 makes improvements to the type analysis of conditional expressions (e1 ? e2 : e3
), if-null expressions (e1 ?? e2
), if-null assignments (e1 ??= e2
), and switch expressions (switch (e) { p1 => e1, ... }
). To take advantage of these improvements, set your package's SDK constraint lower bound to 3.4 or greater (sdk: '^3.4.0'
).
Breaking Change #54640: The pattern context type schema for cast patterns has been changed from Object?
to _
(the unknown type), to align with the specification. This change is not expected to make any difference in practice.
Breaking Change #54828: The type schema used by the compiler front end to perform type inference on the operand of a null-aware spread operator (...?
) in map and set literals has been made nullable, to match what currently happens in list literals. This makes the compiler front end behavior consistent with that of the analyzer. This change is expected to be very low impact.
dart:async
ParallelWaitError
to get some meta-information that it can expose in its toString
, and the Iterable<Future>.wait
and (Future,...,Future).wait
extension methods now provide that information. Should make a ParallelWaitError
easier to log.dart:cli
waitFor
is removed in 3.4.dart:ffi
Struct.create
and Union.create
to create struct and union views of the sequence of bytes stored in a subtype of TypedData
.dart:io
Breaking change #53863: Stdout
has a new field lineTerminator
, which allows developers to control the line ending used by stdout
and stderr
. Classes that implement Stdout
must define the lineTerminator
field. The default semantics of stdout
and stderr
are not changed.
Deprecates FileSystemDeleteEvent.isDirectory
, which always returns false
.
dart:js_interop
Fixes an issue with several comparison operators in JSAnyOperatorExtension
that were declared to return JSBoolean
but really returned bool
. This led to runtime errors when trying to use the return values. The implementation now returns a JSBoolean
to align with the interface. See issue #55024 for more details.
Added ExternalDartReference
and related conversion functions toExternalReference
and toDartObject
. This is a faster alternative to JSBoxedDartObject
, but with fewer safety guarantees and fewer interoperability capabilities. See #55187 for more details.
On dart2wasm, JSBoxedDartObject
now is an actual JS object that wraps the opaque Dart value instead of only externalizing the value. Like the JS backends, you'll now get a more useful error when trying to use it in another Dart runtime.
Added isA
helper to make type checks easier with interop types. See #54138 for more details.
dart:typed_data
BREAKING CHANGE #53218 #53785: The unmodifiable view classes for typed data are deprecated.
To create an unmodifiable view of a typed-data object, use the asUnmodifiableView()
methods added in Dart 3.3:
Uint8List data = ...; final readOnlyView = data.asUnmodifiableView(); // readOnlyView has type Uint8List, and throws if attempted modified.
The reason for this change is to allow more flexibility in the implementation of typed data, so the native and web platforms can use different strategies to ensure that typed data has good performance.
The deprecated types will be removed in Dart 3.5.
Improved code completion. Fixed over 50% of completion correctness bugs, tagged analyzer-completion-correctness
in the issue tracker.
Support for new annotations introduced in version 1.14.0 of the meta package.
Support for the @doNotSubmit
annotation, noting that any usage of an annotated member should not be submitted to source control.
Support for the @mustBeConst
annotation, which indicates that an annotated parameter only accepts constant arguments.
unnecessary_library_name
lint.missing_code_block_language_in_doc_comment
lint.""
for all dart.library.foo
strings, where dart:foo
is not an available library. Instead there will only be entries for the available libraries, like dart.library.core
, where the value was, and still is, "true"
. This should have no effect on const bool.fromEnvironment(...)
or const String.fromEnvironment(...)
without a defaultValue
argument, an argument which was always ignored previously. It changes the behavior of const bool.hasEnvironment(...)
on such an input, away from always being true
and therefore useless.Dependency resolution and dart pub outdated
will now surface if a dependency is affected by a security advisory, unless the advisory is listed under a ignored_advisories
section in the pubspec.yaml
file. To learn more about pub's support for security advisories, visit dart.dev/go/pub-security-advisories.
path
-dependencies inside git
-dependencies are now resolved relative to the git repo.
All dart pub
commands can now be run from any subdirectory of a project. Pub will find the first parent directory with a pubspec.yaml
and operate relative it.
New command dart pub unpack
that downloads a package from pub.dev and extracts it to a subfolder of the current directory.
This can be useful for inspecting the code, or playing with examples.
Dart VM flags and options can now be provided to any executable generated using dart compile exe
via the DART_VM_OPTIONS
environment variable. DART_VM_OPTIONS
should be set to a list of comma-separated flags and options with no whitespace. Options that allow for multiple values to be provided as comma-separated values are not supported (e.g., --timeline-streams=Dart,GC,Compiler
).
Example of a valid DART_VM_OPTIONS
environment variable:
DART_VM_OPTIONS=--random_seed=42,--verbose_gc
Dart VM no longer supports external strings: Dart_IsExternalString
, Dart_NewExternalLatin1String
and Dart_NewExternalUTF16String
functions are removed from Dart C API.
This is a patch release that:
@JS
annotation were actually using the invocation’s enclosing library's @JS
annotation. (issue #55430).This is a patch release that:
This is a patch release that:
DateTime.timeZoneName
on Windows, which was checking whether current date is in the summer or standard time rather than checking if the given moment is in the summer or standard time (issue #55240).This is a patch release that:
@JS
annotation on the library (issue #55057).await
expression, unless the extension type itself implements Future
(issue #55095).Dart 3.3 adds extension types to the language. To use them, set your package's SDK constraint lower bound to 3.3 or greater (sdk: '^3.3.0'
).
An extension type wraps an existing type with a different, static-only interface. It works in a way which is in many ways similar to a class that contains a single final instance variable holding the wrapped object, but without the space and time overhead of an actual wrapper object.
Extension types are introduced by extension type declarations. Each such declaration declares a new named type (not just a new name for the same type). It declares a representation variable whose type is the representation type. The effect of using an extension type is that the representation (that is, the value of the representation variable) has the members declared by the extension type rather than the members declared by its “own” type (the representation type). Example:
extension type Meters(int value) { String get label => '${value}m'; Meters operator +(Meters other) => Meters(value + other.value); } void main() { var m = Meters(42); // Has type `Meters`. var m2 = m + m; // OK, type `Meters`. // int i = m; // Compile-time error, wrong type. // m.isEven; // Compile-time error, no such member. assert(identical(m, m.value)); // Succeeds. }
The declaration Meters
is an extension type that has representation type int
. It introduces an implicit constructor Meters(int value);
and a getter int get value
. m
and m.value
is the very same object, but m
has type Meters
and m.value
has type int
. The point is that m
has the members of Meters
and m.value
has the members of int
.
Extension types are entirely static, they do not exist at run time. If o
is the value of an expression whose static type is an extension type E
with representation type R
, then o
is just a normal object whose run-time type is a subtype of R
, exactly like the value of an expression of type R
. Also the run-time value of E
is R
(for example, E == R
is true). In short: At run time, an extension type is erased to the corresponding representation type.
A method call on an expression of an extension type is resolved at compile-time, based on the static type of the receiver, similar to how extension method calls work. There is no virtual or dynamic dispatch. This, combined with no memory overhead, means that extension types are zero-cost wrappers around their representation value.
While there is thus no performance cost to using extension types, there is a safety cost. Since extension types are erased at compile time, run-time type tests on values that are statically typed as an extension type will check the type of the representation object instead, and if the type check looks like it tests for an extension type, like is Meters
, it actually checks for the representation type, that is, it works exactly like is int
at run time. Moreover, as mentioned above, if an extension type is used as a type argument to a generic class or function, the type variable will be bound to the representation type at run time. For example:
void main() { var meters = Meters(3); // At run time, `Meters` is just `int`. print(meters is int); // Prints "true". print(<Meters>[] is List<int>); // Prints "true". // An explicit cast is allowed and succeeds as well: List<Meters> meterList = <int>[1, 2, 3] as List<Meters>; print(meterList[1].label); // Prints "2m". }
Extension types are useful when you are willing to sacrifice some run-time encapsulation in order to avoid the overhead of wrapping values in instances of wrapper classes, but still want to provide a different interface than the wrapped object. An example of that is interop, where you may have data that are not Dart objects to begin with (for example, raw JavaScript objects when using JavaScript interop), and you may have large collections of objects where it's not efficient to allocate an extra object for each element.
Breaking Change #54056: The rules for private field promotion have been changed so that an abstract getter is considered promotable if there are no conflicting declarations. There are no conflicting declarations if there are no non-final fields, external fields, concrete getters, or noSuchMethod
forwarding getters with the same name in the same library. This makes the implementation more consistent and allows type promotion in a few rare scenarios where it wasn't previously allowed. It is unlikely, but this change could cause a breakage by changing an inferred type in a way that breaks later code. For example:
class A { int? get _field; } class B extends A { final int? _field; B(this._field); } test(A a) { if (a._field != null) { var x = a._field; // Previously had type `int?`; now has type `int` ... x = null; // Previously allowed; now causes a compile-time error. } }
Affected code can be fixed by adding an explicit type annotation. For example, in the above snippet, var x
can be changed to int? x
.
It's also possible that some continuous integration configurations might fail if they have been configured to treat warnings as errors, because the expanded type promotion could lead to one of the following warnings:
unnecessary_non_null_assertion
unnecessary_cast
invalid_null_aware_operator
These warnings can be addressed in the usual way, by removing the unnecessary operation in the first two cases, or changing ?.
to .
in the third case.
To learn more about other rules surrounding type promotion, check out the guide on Fixing type promotion failures.
dart:core
String.fromCharCodes
now allow start
and end
to be after the end of the Iterable
argument, just like skip
and take
does on an Iterable
.dart:ffi
@Native
can now be used on fields.Native.addressOf
.elementAt
pointer arithmetic extension methods on core Pointer
types are now deprecated. Migrate to the new -
and +
operators instead.@FfiNative
annotation has been removed. Usages should be updated to use the @Native
annotation.dart:js_interop
JSAny
were previously represented using a custom erasure of @staticInterop
types that were compiler-specific. They are now represented as extension types where their representation types are compiler-specific. This means that user-defined @staticInterop
types that implemented JSAny
or JSObject
can no longer do so and need to use JSObject.fromInteropObject
. Going forward, it's recommended to use extension types to define interop APIs. Those extension types can still implement JS types.JSArray
and JSPromise
are now generic types whose type parameter is a subtype of JSAny?
. Conversions to and from these types are changed to account for the type parameters of the Dart or JS type, respectively.dart:js_interop
extension members are moved to different extensions on the same type or a supertype to better organize the API surface. See JSAnyUtilityExtension
and JSAnyOperatorExtension
for the new extensions. This shouldn't make a difference unless the extension names were explicitly used.importModule
to allow users to dynamically import modules using the JS import()
expression.dart:js_interop_unsafe
has
helper to make hasProperty
calls more concise.dart:typed_data
BREAKING CHANGE (https://github.com/dart-lang/sdk/issues/53218) The unmodifiable view classes for typed data are deprecated. Instead of using the constructors for these classes to create an unmodifiable view, e.g.
Uint8List data = ... final readOnlyView = UnmodifiableUint8ListView(data);
use the new asUnmodifiableView()
methods:
Uint8List data = ... final readOnlyView = data.asUnmodifiableView();
The reason for this change is to allow more flexibility in the implementation of typed data so the native and web platforms can use different strategies for ensuring typed data has good performance.
The deprecated types will be removed in a future Dart version.
dart:nativewrappers
base
so that none of their subtypes can be implemented. Implementing subtypes can lead to crashes when passing such native wrapper to a native call, as it will try to unwrap a native field that doesn't exist.dart create
command now uses v3 of package:lints
, including multiple new recommended lints by default. To learn more about the updated collection of lints, check out the package:lints
3.0.0 changelog entry.dart:js_util
, package:js
, and dart:js
are now disallowed from being imported when compiling with dart2wasm
. Prefer using dart:js_interop
and dart:js_interop_unsafe
.Type arguments of package:js
interop types are now printed as any
instead of being omitted. This is simply a change to the textual representation of package js types that have type arguments. These type arguments are still completely ignored by the type system at runtime.
Removed “implements <...>” text from the Chrome custom formatter display for Dart classes. This information provides little value and keeping it imposes an unnecessary maintenance cost.
Invocation
that is passed to noSuchMethod
will no longer have a minified memberName
, even when dart2js is invoked with --minify
. See #54201 for more details.pubspec.yaml
files by adding an # ignore: <diagnostic_id>
comment.dart doc
comment directives are now reported.flutter_style_todos
lint now has a quick fix.iterable_contains_unrelated_type
and list_remove_unrelated_type
lints. Consider migrating to the expanded collection_methods_unrelated_type
lint.always_require_non_null_named_parameters
avoid_returning_null
,avoid_returning_null_for_future
This is a patch release that:
This is a patch release that:
Adjusts the nullablity computations in the implementation of the upper bound algorithm in the compiler frontend (issue #53999).
Fixes missing closure code completion entries for function parameters for LSP-based editors like VS Code (issue #54112).
This is a patch release that:
Fixes the left/mobile sidebar being empty on non-class pages in documentation generated with dart doc
(issue #54073).
Fixes a JSON array parsing bug that causes a segmentation fault when flutter test
is invoked with the --coverage
flag (SDK issue #54059, Flutter issue #124145).
Upgrades Dart DevTools to version 2.28.3 (issue #54085).
Dart 3.2 adds the following features. To use them, set your package's SDK constraint lower bound to 3.2 or greater (sdk: '^3.2.0'
).
Private field promotion: In most circumstances, the types of private final fields can now be promoted by null checks and is
tests. For example:
class Example { final int? _privateField; Example(this._privateField); f() { if (_privateField != null) { // _privateField has now been promoted; you can use it without // null checking it. int i = _privateField; // OK } } } // Private field promotions also work from outside of the class: f(Example x) { if (x._privateField != null) { int i = x._privateField; // OK } }
To ensure soundness, a field is not eligible for field promotion in the following circumstances:
C
in the library whose interface contains a getter with the same name, but C
does not have an implementation of that getter (such unimplemented getters aren‘t safe for field promotion, because they are implicitly forwarded to noSuchMethod
, which might not return the same value each time it’s called).Breaking Change #53167: Use a more precise split point for refutable patterns. Previously, in an if-case statement, if flow analysis could prove that the scrutinee expression was guaranteed to throw an exception, it would sometimes fail to propagate type promotions implied by the pattern to the (dead) code that follows. This change makes the type promotion behavior of if-case statements consistent regardless of whether the scrutinee expression throws an exception.
No live code is affected by this change, but there is a small chance that the change in types will cause a compile-time error to appear in some dead code in the user's project, where no compile-time error appeared previously.
dart:async
broadcast
parameter to Stream.empty
constructor.dart:cli
waitFor
is disabled by default and slated for removal in 3.4. Attempting to call this function will now throw an exception. Users that still depend on waitFor
can enable it by passing --enable_deprecated_wait_for
flag to the VM.dart:convert
utf8.encode()
and Utf8Codec.encode()
from List<int>
to Uint8List
.dart:developer
Service.getIsolateID
method.getIsolateId
method to Service
.getObjectId
method to Service
.dart:ffi
NativeCallable.isolateLocal
constructor. This creates NativeCallable
s with the same functionality as Pointer.fromFunction
, except that NativeCallable
accepts closures.NativeCallable.keepIsolateAlive
method, which determines whether the NativeCallable
keeps the isolate that created it alive.NativeCallable
constructors can now accept closures. Previously NativeCallable
s had the same restrictions as Pointer.fromFunction
, and could only create callbacks for static functions.NativeCallable.nativeFunction
now throws an error if is called after the NativeCallable
has already been close
d. Calls to close
after the first are now ignored.dart:io
Breaking change #53005: The headers returned by HttpClientResponse.headers
and HttpRequest.headers
no longer include trailing whitespace in their values.
Breaking change #53227: Folded headers values returned by HttpClientResponse.headers
and HttpRequest.headers
now have a space inserted at the fold point.
dart:isolate
Isolate.packageConfigSync
and Isolate.resolvePackageUriSync
APIs.dart:js_interop
JSNumber.toDart
is removed in favor of toDartDouble
and toDartInt
to make the type explicit. Object.toJS
is also removed in favor of Object.toJSBox
. Previously, this function would allow Dart objects to flow into JS unwrapped on the JS backends. Now, there's an explicit wrapper that is added and unwrapped via JSBoxedDartObject.toDart
. Similarly, JSExportedDartObject
is renamed to JSBoxedDartObject
and the extensions ObjectToJSExportedDartObject
and JSExportedDartObjectToObject
are renamed to ObjectToJSBoxedDartObject
and JSBoxedDartObjectToObject
in order to avoid confusion with @JSExport
.dart:js_interop
types like JSNumber
when used in an external API. This only affects dart:js_interop
classes and not package:js
or other forms of JS interop.dart:js_interop
types: @staticInterop
types can subtype only JSObject
and JSAny
from the set of JS types in dart:js_interop
. Subtyping other types from dart:js_interop
would result in confusing type errors before, so this makes it a static error.dart:js_interop
and @staticInterop
APIs: Static interop APIs will now use the same global context as non-static interop instead of globalThis
to avoid a greater migration. Static interop APIs, either through dart:js_interop
or the @staticInterop
annotation, have used JavaScript‘s globalThis
as the global context. This is relevant to things like external top-level members or external constructors, as this is the root context we expect those members to reside in. Historically, this was not the case in dart2js and DDC. We used either self
or DDC’s global
in non-static interop APIs with package:js
. So, static interop APIs will now use one of those global contexts. Functionally, this should matter in only a very small number of cases, like when using older browser versions. dart:js_interop
's globalJSObject
is also renamed to globalContext
and returns the global context used in the lowerings.dart:js_interop
External APIs: External JS interop APIs when using dart:js_interop
are restricted to a set of allowed types. Namely, this includes the primitive types like String
, JS types from dart:js_interop
, and other static interop types (either through @staticInterop
or extension types).dart:js_interop
isNull
and isUndefined
: null
and undefined
can only be discerned in the JS backends. dart2wasm conflates the two values and treats them both as Dart null. Therefore, these two helper methods should not be used on dart2wasm and will throw to avoid potentially erroneous code.dart:js_interop
typeofEquals
and instanceof
: Both APIs now return a bool
instead of a JSBoolean
. typeofEquals
also now takes in a String
instead of a JSString
.dart:js_interop
JSAny
and JSObject
: These types can only be implemented, and no longer extended, by user @staticInterop
types.dart:js_interop
JSArray.withLength
: This API now takes in an int
instead of JSNumber
.Symbol
s and BigInt
s are now associated with their own interceptor and should not be used with package:js
classes. These types were being intercepted with the assumption that they are a subtype of JavaScript's Object
, but this is incorrect. This lead to erroneous behavior when using these types as Dart Object
s. See #53106 for more details. Use dart:js_interop
's JSSymbol
and JSBigInt
with extension types to interop with these types.Symbol
s and BigInt
s are now associated with their own interceptor and should not be used with package:js
classes. These types were being intercepted with the assumption that they are a subtype of JavaScript's Object
, but this is incorrect. This lead to erroneous behavior when using these types as Dart Object
s. See #53106 for more details. Use dart:js_interop
's JSSymbol
and JSBigInt
with extension types to interop with these types.dart create
command has a new cli
template to quickly create Dart command-line applications with basic argument parsing capabilities. To learn more about using the template, run dart help create
.--enable-experiment
command-line option to enable language experiments.annotate_redeclares
lint.use_build_context_synchronously
lint as stable.dart pub upgrade --tighten
which will update dependencies' lower bounds in pubspec.yaml
to match the current version.dart pub get
/add
/upgrade
will now show if a dependency changed between direct, dev and transitive dependency.dart pub upgrade
no longer shows unchanged dependencies.This is a patch release that:
This is a patch release that:
This is a patch release that:
Fixes a bug in dart2js which would cause the compiler to crash when using @staticInterop
@anonymous
factory constructors with type parameters (see issue #53579 for more details).
The standalone Dart VM now exports symbols only for the Dart_* embedding API functions, avoiding conflicts with other DSOs loaded into the same process, such as shared libraries loaded through dart:ffi
, that may have different versions of the same symbols (issue [#53503]).
Fixes an issue with super slow access to variables while debugging. The fix avoids searching static functions in the imported libraries as references to members are fully resolved by the front-end. (issue #53541)
This is a patch release that:
Fixes a bug in dart2js which crashed the compiler when a typed record pattern was used outside the scope of a function body, such as in a field initializer. For example final x = { for (var (int a,) in someList) a: a };
(issue #53449)
Fixes an expedient issue of users seeing an unhandled exception pause in the debugger, please see https://github.com/dart-lang/sdk/issues/53450 for more details. The fix uses try/catch in lookupAddresses instead of Future error so that we don't see an unhandled exception pause in the debugger (issue #53450)
This is a patch release that:
final ((:a, :b), c) = record;
(issue #53352).dart:async
interface
modifier to purely abstract classes: MultiStreamController
, StreamConsumer
, StreamIterator
and StreamTransformer
. As a result, these types can only be implemented, not extended or mixed in.dart:core
Uri.base
on native platforms now respects IOOverrides
overriding current directory (#39796).dart:ffi
NativeCallable
class, which can be used to create callbacks that allow native code to call into Dart code from any thread. See NativeCallable.listener
. In future releases, NativeCallable
will be updated with more functionality, and will become the recommended way of creating native callbacks for all use cases, replacing Pointer.fromFunction
.dart:io
sameSite
to the Cookie
class.SameSite
.FileSystemEvent
is sealed
. This means that FileSystemEvent
cannot be extended or implemented.Platform
is instantiated.Platform.lineTerminator
which exposes the character or characters that the operating system uses to separate lines of text, e.g., "\r\n"
on Windows.dart:js_interop
ObjectLiteral
is removed from dart:js_interop
. It‘s no longer needed in order to declare an object literal constructor with inline classes. As long as an external constructor has at least one named parameter, it’ll be treated as an object literal constructor. If you want to create an object literal with no named members, use {}.jsify()
.package:js
@staticInterop
and external
extension members: external
@staticInterop
members and external
extension members can no longer be used as tear-offs. Declare a closure or a non-external
method that calls these members, and use that instead.@staticInterop
and external
extension members: external
@staticInterop
members and external
extension members will generate slightly different JS code for methods that have optional parameters. Whereas before, the JS code passed in the default value for missing optionals, it will now pass in only the provided members. This aligns with how JS parameters work, where omitted parameters are actually omitted. For example, calling external void foo([int a, int b])
as foo(0)
will now result in foo(0)
, and not foo(0, null)
.analysis_options.yaml
file:This is a patch release that:
TypeError
or NoSuchMethodError
to be thrown at runtime (issue #53001).This is a patch release that:
is
or as
expressions involving record types with named fields (issue #52869).This is a patch release that:
ListFactorySpecializer
during Flutter web builds (issue #52403).This is a patch release that:
dart format
now handles formatting nullable record types with no fields (dart_style issue #1224).This is a patch release that:
interface
modifiers on the purely abstract classes MultiStreamController
, StreamConsumer
, StreamIterator
and StreamTransformer
(issue #52334).InternetAddress.tryParse
is used (issue #52423).This is a patch release that:
dart doc
(issue #3392).This is a patch release that:
void
in a switch case expression (issue #52191).when
and as
as variable names in patterns (issue #52260).Dart 3.0 adds the following features. To use them, set your package's SDK constraint lower bound to 3.0 or greater (sdk: '^3.0.0'
).
Records: Records are anonymous immutable data structures that let you aggregate multiple values together, similar to tuples in other languages. With records, you can return multiple values from a function, create composite map keys, or use them any other place where you want to bundle a couple of objects together.
For example, using a record to return two values:
(double x, double y) geoLocation(String name) { if (name == 'Nairobi') { return (-1.2921, 36.8219); } else { ... } }
Pattern matching: Expressions build values out of smaller pieces. Conversely, patterns are an expressive tool for decomposing values back into their constituent parts. Patterns can call getters on an object, access elements from a list, pull fields out of a record, etc. For example, we can destructure the record from the previous example like so:
var (lat, long) = geoLocation('Nairobi'); print('Nairobi is at $lat, $long.');
Patterns can also be used in switch cases. There, you can destructure values and also test them to see if they have a certain type or value:
switch (object) { case [int a]: print('A list with a single integer element $a'); case ('name', _): print('A two-element record whose first field is "name".'); default: print('Some other object.'); }
Also, as you can see, non-empty switch cases no longer need break;
statements.
Breaking change: Dart 3.0 interprets switch cases as patterns instead of constant expressions. Most constant expressions found in switch cases are valid patterns with the same meaning (named constants, literals, etc.). You may need to tweak a few constant expressions to make them valid. This only affects libraries that have upgraded to language version 3.0.
Switch expressions: Switch expressions allow you to use patterns and multi-way branching in contexts where a statement isn't allowed:
return TextButton( onPressed: _goPrevious, child: Text(switch (page) { 0 => 'Exit story', 1 => 'First page', _ when page == _lastPage => 'Start over', _ => 'Previous page', }), );
If-case statements and elements: A new if construct that matches a value against a pattern and executes the then or else branch depending on whether the pattern matches:
if (json case ['user', var name]) { print('Got user message for user $name.'); }
There is also a corresponding if-case element that can be used in collection literals.
Sealed classes: When you mark a type sealed
, the compiler ensures that switches on values of that type exhaustively cover every subtype. This enables you to program in an algebraic datatype style with the compile-time safety you expect:
sealed class Amigo {} class Lucky extends Amigo {} class Dusty extends Amigo {} class Ned extends Amigo {} String lastName(Amigo amigo) => switch (amigo) { Lucky _ => 'Day', Ned _ => 'Nederlander', };
In this last example, the compiler reports an error that the switch doesn't cover the subclass Dusty
.
Class modifiers: New modifiers final
, interface
, base
, and mixin
on class
and mixin
declarations let you control how the type can be used. By default, Dart is flexible in that a single class declaration can be used as an interface, a superclass, or even a mixin. This flexibility can make it harder to evolve an API over time without breaking users. We mostly keep the current flexible defaults, but these new modifiers give you finer-grained control over how the type can be used.
Breaking change: Class declarations from libraries that have been upgraded to Dart 3.0 can no longer be used as mixins by default. If you want the class to be usable as both a class and a mixin, mark it mixin class
. If you want it to be used only as a mixin, make it a mixin
declaration. If you haven't upgraded a class to Dart 3.0, you can still use it as a mixin.
Breaking change #50902: Dart reports a compile-time error if a continue
statement targets a label that is not a loop (for
, do
and while
statements) or a switch
member. Fix this by changing the continue
to target a valid labeled statement.
Breaking change language/#2357: Starting in language version 3.0, Dart reports a compile-time error if a colon (:
) is used as the separator before the default value of an optional named parameter. Fix this by changing the colon (:
) to an equal sign (=
).
mixin
classes in the platform libraries can no longer be mixed in, unless they are explicitly marked as mixin class
. The following existing classes have been made mixin classes:Iterable
IterableMixin
(now alias for Iterable
)IterableBase
(now alias for Iterable
)ListMixin
SetMixin
MapMixin
LinkedListEntry
StringConversionSink
dart:core
Added bool.parse
and bool.tryParse
static methods.
Added DateTime.timestamp()
constructor to get current time as UTC.
The type of RegExpMatch.pattern
is now RegExp
, not just Pattern
.
Breaking change #49529:
List
constructor, as it wasn't null safe. Use list literals (e.g. []
for an empty list or <int>[]
for an empty typed list) or List.filled
.onError
argument on int.parse
, double.parse
, and num.parse
. Use the tryParse
method instead.proxy
and Provisional
annotations. The original proxy
annotation has no effect in Dart 2, and the Provisional
type and provisional
constant were only used internally during the Dart 2.0 development process.Deprecated.expires
getter. Use Deprecated.message
instead.CastError
error. Use TypeError
instead.FallThroughError
error. The kind of fall-through previously throwing this error was made a compile-time error in Dart 2.0.NullThrownError
error. This error is never thrown from null safe code.AbstractClassInstantiationError
error. It was made a compile-time error to call the constructor of an abstract class in Dart 2.0.CyclicInitializationError
. Cyclic dependencies are no longer detected at runtime in null safe code. Such code will fail in other ways instead, possibly with a StackOverflowError.NoSuchMethodError
default constructor. Use the NoSuchMethodError.withInvocation
named constructor instead.BidirectionalIterator
class. Existing bidirectional iterators can still work, they just don't have a shared supertype locking them to a specific name for moving backwards.Breaking change when migrating code to Dart 3.0: Some changes to platform libraries only affect code when that code is migrated to language version 3.0.
The Function
type can no longer be implemented, extended or mixed in. Since Dart 2.0 writing implements Function
has been allowed for backwards compatibility, but it has not had any effect. In Dart 3.0, the Function
type is final
and cannot be subtyped, preventing code from mistakenly assuming it works.
The following declarations can only be implemented, not extended:
Comparable
Exception
Iterator
Pattern
Match
RegExp
RegExpMatch
StackTrace
StringSink
None of these declarations contained any implementation to inherit, and are marked as interface
to signify that they are only intended as interfaces.
The following declarations can no longer be implemented or extended:
MapEntry
OutOfMemoryError
StackOverflowError
Expando
WeakReference
Finalizer
The MapEntry
value class is restricted to enable later optimizations. The remaining classes are tightly coupled to the platform and not intended to be subclassed or implemented.
dart:async
Added extension member wait
on iterables and 2-9 tuples of futures.
Breaking change #49529:
DeferredLibrary
class. Use the deferred as
import syntax instead.dart:collection
Added extension members nonNulls
, firstOrNull
, lastOrNull
, singleOrNull
, elementAtOrNull
and indexed
on Iterable
s. Also exported from dart:core
.
Deprecated the HasNextIterator
class (#50883).
Breaking change when migrating code to Dart 3.0: Some changes to platform libraries only affect code when it is migrated to language version 3.0.
Queue
LinkedList
LinkedListEntry
HasNextIterator
(Also deprecated.)HashMap
LinkedHashMap
HashSet
LinkedHashSet
DoubleLinkedQueue
ListQueue
SplayTreeMap
SplayTreeSet
dart:developer
Breaking change #49529:
MAX_USER_TAGS
constant. Use maxUserTags
instead.Callbacks passed to registerExtension
will be run in the zone from which they are registered.
Breaking change #50231:
dart:ffi
@FfiNative
annotation is now deprecated. Usages should be replaced with the new @Native
annotation.dart:html
registerElement
and registerElement2
methods in Document
and HtmlDocument
have been removed. See #49536 for details.dart:math
Random
interface can only be implemented, not extended.dart:io
name
and signalNumber
to the ProcessSignal
class.NetworkInterface.listSupported
. Has always returned true since Dart 2.3.httpEnableTimelineLogging
parameter name transition from enable
to enabled
. See #43638.NetworkProfiling
to accommodate new String
ids that are introduced in vm_service:11.0.0dart:js_util
delete
and the typeof
functionality.jsify
is now permissive and has inverse semantics to dartify
.jsify
and dartify
both handle types they understand natively more efficiently.callMethod
has been aligned with the other methods and now takes Object
instead of String
.--serve-observatory
flag.-k
, --kernel
, and --dart-sdk
.--nativeNonNullAsserts
, which ensures web library APIs are sound in their nullability, is by default set to true in sound mode. For more information on the flag, see NATIVE_NULL_ASSERTIONS.md.--native-null-assertions
, which ensures web library APIs are sound in their nullability, is by default set to true in sound mode, unless -O3
or higher is passed, in which case they are not checked. For more information on the flag, see NATIVE_NULL_ASSERTIONS.md.dart compile js
, flutter build
, or build_web_compilers
. This is not expected to be a visible change.sync*
and async*
functions with =>
bodies.<
in collection literals.dart analyze
are now considered “fatal” (will result in a non-zero exit code). The previous behavior, where such hints (now warnings) are not fatal, can be achieved by using the --no-fatal-warnings
flag. This behavior can also be altered, on a code-by-code basis, by changing the severity of rules in an analysis options file.@Since
annotation. When code in a package uses a Dart SDK element annotated with @Since
, analyzer will report a warning if the package‘s Dart SDK constraint allows versions of Dart which don’t include that element.Updates the Linter to 1.35.0
, which includes changes that
implicit_reopen
unnecessary_breaks
type_literal_in_constant_pattern
invalid_case_patterns
enable_null_safety
invariant_booleans
prefer_bool_in_asserts
prefer_equal_for_default_values
super_goes_last
unnecessary_parenthesis
false-positives with null-aware expressions.void_checks
to allow assignments of Future<dynamic>?
to parameters typed FutureOr<void>?
.use_build_context_synchronously
in if conditions.avoid_private_typedef_functions
with generalized type aliases.unnecessary_parenthesis
to detect some doubled parens.void_checks
to allow returning Never
as void.no_adjacent_strings_in_list
to support set literals and for- and if-elements.avoid_types_as_parameter_names
to handle type variables.avoid_positional_boolean_parameters
to handle typedefs.avoid_redundant_argument_values
to check parameters of redirecting constructors.prefer_const_literals_to_create_immutables
.use_build_context_synchronously
to check context properties.unnecessary_parenthesis
support for property accesses and method invocations.unnecessary_parenthesis
to allow parentheses in more null-aware cascade contexts.unreachable_from_main
to track static elements.unnecessary_null_checks
to not report on arguments passed to Future.value
or Completer.complete
.always_use_package_imports
and prefer_relative_imports
as incompatible rules.only_throw_errors
to not report on Never
-typed expressions.unnecessary_lambdas
to not report with late final
variables.avoid_function_literals_in_foreach_calls
to not report with nullable- typed targets.deprecated_member_use_from_same_package
which replaces the soft-deprecated analyzer hint of the same name.public_member_api_docs
to not require docs on enum constructors.prefer_void_to_null
to not report on as-expressions.The null safety migration tool (dart migrate
) has been removed. If you still have code which needs to be migrated to null safety, please run dart migrate
using Dart version 2.19, before upgrading to Dart version 3.0.
To preserve compatibility with null-safe code pre Dart 3, Pub will interpret a language constraint indicating a language version of 2.12
or higher and an upper bound of <3.0.0
as <4.0.0
.
For example >=2.19.2 <3.0.0
will be interpreted as >=2.19.2 <4.0.0
.
dart pub publish
will no longer warn about dependency_overrides
. Dependency overrides only take effect in the root package of a resolution.
dart pub token add
now verifies that the given token is valid for including in a header according to RFC 6750 section 2.1. This means they must contain only the characters: ^[a-zA-Z0-9._~+/=-]+$
. Before a failure would happen when attempting to send the authorization header.
dart pub get
and related commands will now by default also update the dependencies in the example
folder (if it exists). Use --no-example
to avoid this.
On Windows the PUB_CACHE
has moved to %LOCALAPPDATA%
, since Dart 2.8 the PUB_CACHE
has been created in %LOCALAPPDATA%
when one wasn't present. Hence, this only affects users with a PUB_CACHE
created by Dart 2.7 or earlier. If you have path/to/.pub-cache/bin
in PATH
you may need to update your PATH
.
This is a patch release that:
Out of Memory
exception due to a VM bug. (issue #50537).This is a patch release that:
Dart_CObject_Type
. (issue #51459).This is a patch release that:
This is a patch release that:
Updates DDC test and builder configuration. (issue #51481).
Protects the Dart Analysis Server against extreme memory usage by limiting the number of plugins per analysis context to 1. (issue #50981).
This is a patch release that:
Fixes a VM crash when mixing the use of double and float calculations in debug/jit configuration. (issue #50622).
Fixes the compiler crashing when attempting to inline a method with lots of optional parameters with distinct default values. (issue #119220).
Fixes the part_of_different_library
error encountered when using PackageBuildWorkspace
. (issue #51087).
This is a patch release that:
Fixes pub get
behaviour: In Dart 2.19.0 a dart pub get
with a pubspec.lock
created by a 2.18 SDK will unlock all constraints, effectively like a pub upgrade
(issue #51166).
Stops rewriting SDK constraints: In Dart 3, a SDK constraint like >=2.12.0 <3.0.0
gets interpreted by the pub client as >=2.12.0 <4.0.0
to allow for backwards compatibility (issue #51101).
This change was intended for Dart 3.0.0 and later, but was landed already in 2.19.0. It is now being removed in 2.19.1, as it can give confusing messages such as:
Because library requires SDK version >=2.19.2 <4.0.0, version solving failed.
This reinterpretation no longer happens in Dart 2.19.1.
Fixes a VM crash caused by incorrect sharing of RegExp between isolates (issue #51130).
Breaking change #49635: Flag additional code as unreachable due to types Null
and Never
. Several unusual constructs that lead to unreachable code are now recognized by flow analysis:
Control flow after an expression of the form e ?? other
or e ??= other
, where e
has static type Null
and other
has static type Never
, is considered unreachable.
Control flow predicated on an expression of the form e is Never
evaluating to true
is considered unreachable.
Control flow predicated on an expression of the form e is! Never
evaluating to false
is considered unreachable.
Control flow on the RHS of a null-aware access such as e?.property...
, e?.property = ...
or e?.method(...)
, where e
has static type Null
, is considered unreachable (Note: this can arise in the presence of extension methods).
Previously, these behaviors only took effect if e
was a reference to a local variable.
Additionally, a type test of the form v is Never
(where v
is a local variable) no longer promotes v
to type Never
.
Breaking Change #49687: Don‘t delegate inaccessible private names to noSuchMethod
. If a concrete class implements an interface containing a member with a name that’s private to different library, and does not inherit an implementation of that interface member, a invocation of that member will result in an exception getting thrown. Previously, such attempts would result in the call being diverted to the noSuchMethod
method.
This change closes a loophole in Dart's privacy system, where another library can provide a different implementation of a supposedly private member using noSuchMethod
, and paves the way for a future implementation of promotion for private final fields (see #2020).
Breaking Change #50383: Report a compile-time error for all cyclic dependencies during top-level type inference.
Previously, some of these dependencies were ignored, based on an analysis determining that they could not influence the inferred type. However, this analysis was complex, differed slightly among tools, and had become much more complex due to other changes (especially, enhanced flow analysis).
With this change, all tools treat these cyclic dependencies in the same way, the analysis is well-understood, and, arguably, the code is more readable.
Breakage is mitigated by adding a declared type to one top-level declaration per cycle which is now an error.
library;
). A library directive can be used for library-level annotations (such as @deprecated
) and for library-level documentation comments, and with this new feature, you don't have to provide a unique name for each library directive. Instead, a name can simply be omitted (see #1073).dart:convert
DEFAULT_BUFFER_SIZE
in JsonUtf8Encoder
has been removed.dart:core
FallThroughError
. Has not been thrown since Dart 2.0 (see #49529).copyWith
extension method on DateTime
(see [#24644]).RangeError.checkValidIndex
in favor of IndexError.check
.IndexError
constructor in favor of IndexError.withLength
constructor.NullThrownError
and CyclicInitializationError
. Neither error is thrown by null safe code. #49529: https://github.com/dart-lang/sdk/issues/49529 [#24644]: https://github.com/dart-lang/sdk/issues/24644dart:developer
kInvalidParams
, kExtensionError
, kExtensionErrorMax
, and kExtensionErrorMin
in ServiceExtensionResponse
have been removed. They have been replaced by invalidParams
, extensionError
, extensionErrorMax
, and extensionErrorMin
.UserTag.MAX_USER_TAGS
in favor of UserTag.maxUserTags
.dart:ffi
Pointer
has changed to Never
in preparation of completely removing the runtime type argument. Pointer.toString
has changed to not report any type argument.dart:html
slice
to SharedArrayBuffer
.registerElement
and registerElement2
in Document
and HtmlDocument
. These APIs were based on the deprecated Web Components v0.5 specification and are not supported by browsers today. These APIs are expected to be deleted in a future release. See the related breaking change request #49536.dart:io
Breaking change #49305: Disallow negative or hexadecimal content-length headers.
Breaking change #49647: File.create
now takes new optional exclusive
bool
parameter, and when it is true
the operation will fail if target file already exists.
Breaking change #49878: Calling ResourceHandle.toFile()
, ResourceHandle.toSocket()
, ResourceHandle.toRawSocket()
or ResourceHandle.toRawDatagramSocket()
, more than once now throws a StateError
.
The previous behavior would allow multiple Dart objects to refer to the same file descriptor, which would produce errors when one object was closed or garbage collected.
Adds three new FileSystemException
subclasses to handle common error cases:
PathAccessException
: The necessary access rights are not available.PathExistsException
: The path being created already exists.PathNotFoundException
: The path being accessed does not exist.dart:isolate
Isolate.run
to run a function in a new isolate.SendPort.send
is again applying strict checks to the contents of the message when sending messages between isolates that are not known to share the same code (e.g. an isolate spawned via Isolate.spawnUri
). These checks were accidentally relaxed in an earlier Dart version allowing all classes from dart:core
and dart:collection
through. This for example means that you can't send an instance of a HashMap
to an isolate spawned via Isolate.spawnUri
. See SendPort.send
documentation for the full list of restrictions.dart:mirrors
MirrorsUsed
and Comment
have been removed. MirrorsUsed
was experimental and deprecated; Comment
was previously used internally in dart2js. Both are no longer functional.package:js
@staticInterop
:external
generative constructors. Use external factory
s for these classes instead, and the behavior should be identical. This includes use of synthetic constructors. See #48730 and #49941 for more details.external void method<T>(T t)
. Use a non-external
extension method for type parameters instead. See #49350 for more details.@JS
annotation. You can also have the @anonymous
annotation with these two annotations for an object literal constructor, but it isn't required.mustBeOverridden
annotation, and quick fixescombinators_ordering
, dangling_library_doc_comments
, implicit_call_tearoffs
, library_annotations
, and unnecessary_library_directive
.body_might_complete_normally_catch_error
, cast_from_null_always_fails
, cast_from_nullable_always_fails
, deprecated_colon_for_default_value
, and duplicate_export
invalid_override_different_default_values
Updated the Linter to 1.31.0
, which includes changes that
collection_methods_unrelated_type
.combinators_ordering
.dangling_library_doc_comments
.enable_null_safety
.implicit_call_tearoffs
.library_annotations
.unnecessary_library_directive
.unreachable_from_main
.use_string_in_part_of_directives
.no_leading_underscores_for_local_identifiers
to not report super formals as local variables.unnecessary_overrides
false negatives.cancel_subscriptions
for nullable fields.library_names
to support unnamed libraries.unnecessary_parenthesis
support for as-expressions.use_build_context_synchronously
to check for context property accesses.comment_references
.unnecessary_brace_in_string_interps
for this
expressions .use_build_context_synchronously
for BuildContext.mounted
.flutter_style_todos
to handle more cases.use_build_context_synchronously
to check for BuildContext
s in named expressions.exhaustive_cases
to check parenthesized expressionsavoid_redundant_argument_values
to work with enum declarations.avoid_redundant_argument_values
when referencing required parameters in legacy libraries.use_super_parameters
false positives with repeated super parameter references.use_late_for_private_fields_and_variables
to handle enums.prefer_contains
false positives when a start index is non-zero.noop_primitive_operations
to catch .toString()
in string interpolations.public_member_api_docs
to report diagnostics on extension names (instead of bodies).use_colored_box
and use_decorated_box
to not over-report on containers without a child.unnecessary_parenthesis
false positives on a map-or-set literal at the start of an expression statement.prefer_final_locals
false positives reporting on fields.unnecessary_overrides
to allow overrides on @Protected
members.avoid_multiple_declarations_per_line
false positives in for
statements.prefer_final_locals
false positives on declaration lists with at least one non-final variable.use_build_context_synchronously
to handle await
s in if
conditions.avoid_escaping_inner_quotes
.avoid_null_checks_in_equality_operators
.avoid_positional_boolean_parameters
.avoid_returning_null
.avoid_returning_null
.avoid_returning_this
.cascade_invocations
.diagnostic_describe_all_properties
.flutter_style_todos
.join_return_with_statement
.parameter_assignments
.prefer_const_constructors
.prefer_constructors_over_static_methods
.prefer_constructors_over_static_methods
.prefer_contains
.prefer_foreach
.prefer_interpolation_to_compose_strings
.prefer_interpolation_to_compose_strings
.recursive_getters
.tighten_type_of_initializing_formals
.unnecessary_lambdas
.use_late_for_private_fields_and_variables
.Treats packages with sdk constraint lower bound >=2.12.0
or more and upper bound <3.0.0
as compatible with <4.0.0
.
Introduces content-hashes in pubspec.lock, to protect against corrupted package repositories.
These will show up in the lock file on the first run of dart pub get
.
See https://dart.dev/go/content-hashes for more details.
New flag dart pub get --enforce-lockfile
will fetch dependencies, but fail if anything deviates from pubspec.lock
. Useful for ensuring reproducible runs in CI and production.
Remove remaining support for .packages
files. The flag --legacy-packages-file
is no longer supported.
The client will now default to the pub.dev
repository instead of pub.dartlang.org
. This will cause a change in pubspec.lock
.
Support a new field funding
in pubspec.yaml
.
Validate the CRC32c checksum of downloaded archives and retry on failure.
dart pub add foo:<constraint>
with an existing dependency will now update the constraint rather than fail.
Update dart pub publish
to allow dependency_overrides
in pubspec.yaml
. They will still cause a publication warning. Note that only dependency_overrides
from the root package effect resolution.
Update dart pub publish
to require a working resolution. If publishing a breaking release of mutually dependent packages use dependency_overrides
to obtain a resolution.
dart pub add
will now allow adding multiple packages from any source using the same YAML syntax as in pubspec.yaml
.
For example:
$ dart pub add retry:^1.0.0 'dev:foo{"git":"https://github.com/foo/foo"}'
dart pub publish
will now give a warning if dart analyze
reports any diagnostics.
dart pub get
now fails gracefully when run from inside the pub-cache.
dart pub publish
now shows the file sizes of large files in your package to prevent accidental publication of large unrelated files.
Fix a bug in dart pub upgrade --major-versions
where packages not requiring major updates would be held back unless needed.
This is a patch release that fixes crashes during hot reload (issue flutter/flutter#113540).
This is a patch release that fixes a regression in code coverage computation (issue #49887).
This is a patch release that:
Uri.parse
.dart:core
Security advisory CVE-2022-3095: There is a auth bypass vulnerability in Dart SDK, specifically dart:uri
core library, used to parse and validate URLs. This library is vulnerable to the backslash-trick wherein backslash is not recognized as equivalent to forward slash in URLs.
The Uri
class has been changed to parse a backslash in the path or the authority separator of a URI as a forward slash. This affects the Uri
constructor‘s path
parameter, and the Uri.parse
method. This change was made to not diverge as much from the browser URL
behavior. The Dart Uri
class is still not an implementation of the same standard as the browser’s URL
implementation.
This is a patch release that fixes a crash caused by incorrect type inference (issues flutter/flutter#110715 and flutter/flutter#111088).
The following features are new in the Dart 2.18 language version. To use them, you must set the lower bound on the SDK constraint for your package to 2.18 or greater (sdk: '>=2.18.0 <3.0.0'
).
Enhanced type inference for generic invocations with function literals: Invocations of generic methods/constructors that supply function literal arguments now have improved type inference. This primarily affects the Iterable.fold
method. For example, in previous versions of Dart, the compiler would fail to infer an appropriate type for the parameter a
:
void main() { List<int> ints = [1, 2, 3]; var maximum = ints.fold(0, (a, b) => a < b ? b : a); }
With this improvement, a
receives its type from the initial value, 0
.
On rare occasions, the wrong type will be inferred, leading to a compile-time error, for example in this code, type inference will infer that a
has a type of Null
:
void main() { List<int> ints = [1, 2, 3]; var maximumOrNull = ints.fold(null, (a, b) => a == null || a < b ? b : a); }
This can be worked around by supplying the appropriate type as an explicit type argument to fold
:
void main() { List<int> ints = [1, 2, 3]; var maximumOrNull = ints.fold<int?>(null, (a, b) => a == null || a < b ? b : a); }
Object
is no longer supported:class Base {} class Mixin extends Base {} class C extends Base with Mixin {}This should instead be written using a mixin declaration of
Mixin
:class Base {} mixin Mixin on Base {} class C extends Base with Mixin {}This feature has not been supported in most compilation targets for some time but is now completely removed.
dart:async
Stream.fromIterable
stream can now be listened to more than once.dart:collection
BidirectionalIterator
.dart:core
unencodedPath
positional argument to Uri.http
and Uri.https
to default to an empty path.dart:html
connectionState
attribute and connectionstatechange
listener to RtcPeerConnection
.dart:io
Breaking Change #49045: The uri
property of RedirectException
in dart:io
has been changed to be nullable. Programs must be updated to handle the null
case.
Breaking Change #34218: Constants in dart:io
's networking APIs following the SCREAMING_CAPS
convention have been removed (they were previously deprecated). Please use the corresponding lowerCamelCase
constants instead.
Breaking Change #45630: The Dart VM no longer automatically restores the initial terminal settings upon exit. Programs that change the Stdin
settings lineMode
and echoMode
are now responsible for restoring the settings upon program exit. E.g. a program disabling echoMode
will now need to restore the setting itself and handle exiting by the appropriate signals if desired:
import 'dart:io'; import 'dart:async'; main() { bool echoWasEnabled = stdin.echoMode; try { late StreamSubscription subscription; subscription = ProcessSignal.sigint.watch().listen((ProcessSignal signal) { stdin.echoMode = echoWasEnabled; subscription.cancel(); Process.killPid(pid, signal); /* Die by the signal. */ }); stdin.echoMode = false; } finally { stdin.echoMode = echoWasEnabled; } }
This change is needed to fix #36453 where the dart programs not caring about the terminal settings can inadvertently corrupt the terminal settings when e.g. piping into less.
Furthermore the echoMode
setting now only controls the echo
local mode and no longer sets the echonl
local mode on POSIX systems (which controls whether newline are echoed even if the regular echo mode is disabled). The echonl
local mode is usually turned off in common shell environments. Programs that wish to control the echonl
local mode can use the new echoNewlineMode
setting.
The Windows console code pages (if not UTF-8) and ANSI escape code support (if disabled) remain restored when the VM exits.
dart:js_util
dartify
and a number of minor helper functions.Implementation of async
/async*
/sync*
is revamped in Dart VM, both in JIT and AOT modes. This also affects Flutter except Flutter Web.
Besides smaller code size and better performance of async methods, the new implementation carries a few subtle changes in behavior:
If async
method returns before reaching the first await
, it now returns a completed Future. Previously async
methods completed resulting Future in separate microtasks.
Stack traces no longer have duplicate entries for async
methods.
New implementation now correctly throws an error if null
occurs as an argument of a logical expression (&&
and ||
) which also contains an await
.
New implementation avoids unnecessary extending the liveness of local variables in async
/async*
/sync*
methods, which means that unused objects stored in local variables in such methods might be garbage collected earlier than they were before (see issue #36983 for details).
Breaking Change #48272: The .packages
file has been fully discontinued. Historically when the commands dart pub get
or flutter pub get
are executed, pub resolved all dependencies, and installs those dependencies to the local pub cache. It furthermore created a mapping from each used package to their location on the local file system, and wrote that into two files:
.dart_tool/package_config.json
.packages
(deprecated in Dart 2.8.0)As of Dart 2.18.0, the .packages
is now fully desupported, and all tools distributed in, and based on, the Dart SDK no longer support it, and thus solely use the .dart_tool/package_config.json
file. If you've run dart pub get
or flutter pub get
with any Dart SDK from the past few years you already have a .dart_tool/package_config.json
and thus should not be impacted. You can delete any old .packages
files.
If you have any third-party tools that for historical reasons depend on a .packages
we will support the ability to generate a .packages
by passing the flag --legacy-packages-file
to dart pub get
. This support will be removed in a following stable release.
Breaking change #46100: The standalone dart2js
and dartdevc
tools have been removed as previously announced. dart2js
is replaced by the dart compile js
command, dartdevc
is no longer exposed as a command-line tool.
Breaking change #46100: The standalone dartanalyzer
tool has been removed as previously announced. dartanalyzer
is replaced by the dart analyze
command.
abstract_field_constructor_initializer
, abstract_class_member
, always_put_control_body_on_new_line
, avoid_print
, avoid_renaming_method_parameters
, discarded_futures
, enum_with_abstract_member
, non_bool_condition
, super_formal_parameter_without_associated_named
, unawaited_futures
, unnecessary_final
unused_element_parameter
,deprecated_export_use
Updated the Linter to 1.25.0
, which includes changes that
discarded_futures
.unnecessary_null_aware_operator_on_extension_on_nullable
.unnecessary_to_list_in_spreads
.no_duplicate_case_values
lines_longer_than_80_chars
, prefer_const_constructors_in_immutables
, and prefer_initializing_formals
.prefer_final_parameters
to support super parameters.unawaited_futures
to handle string interpolated futures.use_colored_box
to not flag nullable colors,no_leading_underscores_for_local_identifiers
to lint local function declarations.avoid_init_to_null
to correctly handle super initializing defaults that are non-null.no_leading_underscores_for_local_identifiers
to allow identifiers with just underscores.flutter_style_todos
to support usernames that start with a digit.require_trailing_commas
to handle functions in asserts and multi-line strings.unsafe_html
to allow assignments to img.src
.unnecessary_null_checks
to properly handle map literal entries.dart pub get
and dart pub upgrade
no longer create the .packages
file. For details, see breaking change #48272 above.dart pub outdated
now shows which of your dependencies are discontinued.dart pub publish
will now list all the files it is about to publish.This is a patch release that:
This is a patch release that:
This is a patch release that:
This is a patch release that fixes:
dart pub login
command (issue #3424).This is a patch release that fixes:
late
Finalizable
variables (issue #49024).dart compile
on macOS 10.15 (issue #49010).The following features are new in the Dart 2.17 language version. To use them, you must set the lower bound on the SDK constraint for your package to 2.17 or greater (sdk: '>=2.17.0 <3.0.0'
).
Enhanced enums with members: Enum declarations can now define members including fields, constructors, methods, getters, etc. For example:
enum Water { frozen(32), lukewarm(100), boiling(212); final int tempInFahrenheit; const Water(this.tempInFahrenheit); @override String toString() => "The $name water is $tempInFahrenheit F."; }
Constructors must be const
since enum values are always constants. If the constructor takes arguments, they are passed when the enum value is declared.
The above enum can be used like so:
void main() { print(Water.frozen); // prints "The frozen water is 32 F." }
Super parameters: When extending a class whose constructor takes parameters, the subclass constructor needs to provide arguments for them. Often, these are passed as parameters to the subclass constructor, which then forwards them to the superclass constructor. This is verbose because the subclass constructor must list the name and type of each parameter in its parameter list, and then explicitly forward each one as an argument to the superclass constructor.
@roy-sianez suggested allowing super.
before a subclass constructor parameter to implicitly forward it to the corresponding superclass constructor parameter. Applying this feature to Flutter eliminated nearly 2,000 lines of code. For example, before:
class CupertinoPage<T> extends Page<T> { const CupertinoPage({ required this.child, this.maintainState = true, this.title, this.fullscreenDialog = false, LocalKey? key, String? name, Object? arguments, String? restorationId, }) : super( key: key, name: name, arguments: arguments, restorationId: restorationId, ); // ... }
And using super parameters:
class CupertinoPage<T> extends Page<T> { const CupertinoPage({ required this.child, this.maintainState = true, this.title, this.fullscreenDialog = false, super.key, super.name, super.arguments, super.restorationId, }); // ... }
From our analysis, over 90% of explicit superclass constructor calls can be completely eliminated, using super.
parameters instead.
Named args everywhere: In a function call, Dart requires positional arguments to appear before named arguments. This can be frustrating for arguments like collection literals and function expressions that look best as the last argument in the argument list but are positional, like the test()
function in the test package:
main() { test('A test description', () { // Very long function body here... }, skip: true); }
It would be better if the skip
argument appeared at the top of the call to test()
so that it wasn‘t easily overlooked, but since it’s named and the test body argument is positional, skip
must be placed at the end.
Dart 2.17 removes this restriction. Named arguments can be freely interleaved with positional arguments, allowing code like:
main() { test(skip: true, 'A test description', () { // Very long function body here... }); }
dart:core
Finalizer
and WeakReference
which can potentially detect when objects are “garbage collected”.isMimeType
method to UriData
class, to allow case-insensitive checking of the MIME type.isCharset
and isEncoding
methods to UriData
class, to allow case-insensitive and alternative-encoding-name aware checking of the MIME type “charset” parameter.UriData.fromString
and UriData.fromBytes
recognize and omit a “text/plain” mimeType
even if it is not all lower-case.dart:ffi
ref=
and []=
methods to the StructPointer
and UnionPointer
extensions. They copy a compound instance into a native memory region.AbiSpecificInteger
s for common C types:char
unsigned char
signed char
short
unsigned short
int
unsigned int
long
unsigned long
long long
unsigned long long
uintptr_t
size_t
wchar_t
NativeFinalizer
which can potentially detect when objects are “garbage collected”. NativeFinalizer
s run native code where dart:core
's Finalizer
s run Dart code on finalization.dart:html
scrollIntoViewIfNeeded
to Element
. Previously, this method was nested within scrollIntoView
based on the ScrollAlignment
value. scrollIntoView
is unchanged for now, but users who intend to use the native Element.scrollIntoViewIfNeeded
should use the new scrollIntoViewIfNeeded
definition instead.Performance.mark
and Performance.measure
to accept their different overloads. mark
can now accept a markOptions
map, and measure
can now accept a startMark
and endMark
, or a measureOptions
map. Both methods return their correct return types now as well - PerformanceEntry?
and PerformanceMeasure?
, respectively.dart:indexed_db
IdbFactory.supportsDatabaseNames
has been deprecated. It will always return false
.dart:io
Breaking Change #47887: HttpClient
has a new connectionFactory
property, which allows socket creation to be customized. Classes that implement HttpClient
may be broken by this change. Add the following method to your classes to fix them:
void set connectionFactory( Future<ConnectionTask<Socket>> Function( Uri url, String? proxyHost, int? proxyPort)? f) => throw UnsupportedError("connectionFactory not implemented");
Breaking Change #48093: HttpClient
has a new keyLog
property, which allows TLS keys to be logged for debugging purposes. Classes that implement HttpClient
may be broken by this change. Add the following method to your classes to fix them:
void set keyLog(Function(String line)? callback) => throw UnsupportedError("keyLog not implemented");
Breaking Change #34218: Constants in dart:io
following the SCREAMING_CAPS
convention have been removed (they were previously deprecated). Please use the corresponding lowerCamelCase
constants instead.
Breaking Change #48513: Add a new allowLegacyUnsafeRenegotiation
property to SecurityContext
, which allows TLS renegotiation for client secure sockets.
Add a optional keyLog
parameter to SecureSocket.connect
and SecureSocket.startConnect
.
Deprecate SecureSocket.renegotiate
and RawSecureSocket.renegotiate
, which were no-ops.
Breaking change #46100: The standalone dart2js
tool has been marked deprecated as previously announced. Its replacement is the dart compile js
command. Should you find any issues, or missing features, in the replacement command, kindly file an issue.
Breaking change #46100: The standalone dartdevc
tool has been marked deprecated as previously announced and will be deleted in a future Dart stable release. This tool was intended for use only by build systems like bazel, build_web_compilers
and flutter_tools
. The functionality remains available for those systems, but it is no longer exposed as a command-line tool in the SDK. Please share any concerns in the breaking change tracking issue.
Breaking change #46100: The standalone dartdoc
tool has been removed as previously announced. Its replacement is the dart doc
command.
The template names used in the dart create
command have been simplified, and the current template names are now the set shown below. (Note: for backwards compatibility the former template names can still be used.)
[console] (default) A command-line application. [package] A package containing shared Dart libraries. [server-shelf] A server app using package:shelf. [web] A web app that uses only core Dart libraries.
always_use_package_imports
, avoid_void_async
, cascade_invocations
, default_list_constructor
, must_call_super
, no_leading_underscores_for_local_identifiers
, null_check_on_nullable_type_parameter
, prefer_function_declarations_over_variables
, sort_constructors_first
, sort_unnamed_constructors_first
, undefined_enum_constant
, unnecessary_late
, unnecessary_null_aware_assignments
, use_enums
, use_raw_strings
, use_super_parameters
, var_return_type
unnecessary_final
compound_implements_finalizable
Updated the Linter to 1.22.0
, which includes changes that
invariant_booleans
.depend_on_referenced_packages
to treat flutter_gen
as a virtual package, not needing an explicit dependency.unnecessary_null_checks
and null_check_on_nullable_type_parameter
to handle list/set/map literals, and yield
and await
expressions.unnecessary_null_aware_assignments
property-access false positives.use_super_parameters
.use_enums
.use_colored_box
.sort_constructors
.always_use_package_imports
, avoid_print
, and avoid_relative_lib_imports
.avoid_void_async
to skip main
functions.prefer_final_parameters
to not super on super params.unnecessary_late
to report on variable names.null_check_on_nullable_type_parameter
stable.Updated dartdoc to 5.1.0, which includes changes that
[...]
linkscategoryOrder
optionThis is a patch release that fixes a dart2js crash when building some Flutter web apps (issue #47916).
This is a patch release that fixes an AOT precompiler crash when building some Flutter apps (issue flutter/flutter#97301).
dart:core
Error.throwWithStackTrace
which can throw
an error with an existing stack trace, instead of creating a new stack trace.dart:ffi
Abi
and AbiSpecificInteger
. These enable specifying integers which have different sizes/signs per ABI (hardware and OS combination).dart:io
HttpClient
no longer transmits some headers (i.e. authorization
, www-authenticate
, cookie
, cookie2
) when processing redirects to a different domain.Directory.rename
will no longer delete a directory if newPath
specifies one. Instead, a FileSystemException
will be thrown.Platform.packageRoot
API has been removed. It had been marked deprecated in 2018, as it doesn't work with any Dart 2.x release.sourcePort
parameter to Socket.connect
, Socket.startConnect
, RawSocket.connect
and RawSocket.startConnect
dart:isolate
Isolate.packageRoot
API has been removed. It had been marked deprecated in 2018, as it doesn't work with any Dart 2.x release.dartanalyzer
tool has been marked deprecated as previously announced. Its replacement is the dart analyze
command. Should you find any issues, or missing features, in the replacement command, kindly file an issue.dartdoc
tool has been marked deprecated as previously announced. Its replacement is the dart doc
command. Should you find any issues, or missing features, in the replacement command, kindly file an issue.pub
tool has been removed. Its replacement is the dart pub
command. Should you find any issues, or missing features, in the replacement command, kindly file an issue.Fixed race conditions in dart pub get
, dart run
and dart pub global run
. It should now be safe to run these concurrently.
If (when) Pub crashes it will save a verbose log in $PUB_CACHE/log/pub_log.txt
This can be used for filing issues to the issue tracker.
dart --verbose pub [command]
will also cause the log file to be written.
dart pub global activate --source=git
now takes arguments --git-path
to specify the path of the activated package in the pubspec and --git-ref
to specify the branch or revision to check out.
dart pub add
can now add multiple packages in one command.
dart pub token add
can now add a token for pub.dev.
dart pub uploader
has been removed. To manage uploaders for a package use the https://pub.dev/<packagename>/admin
web-interface.
Pub now supports a separate pubspec_overrides.yaml
file that can contain dependency_overrides
. This makes it easier to avoid checking the local overrides into version control.
Updated the Linter to 1.18.0
, which includes changes that
camel_case_types
to cover enums.no_leading_underscores_for_local_identifiers
to not mis-flag field formal parameters with default values.prefer_function_declarations_over_variables
to not mis-flag non-final fields.prefer_contains
.exhaustive_cases
to skip deprecated values that redirect to other values.unnecessary_late
.prefer_initializing_formals
.secure_pubspec_urls
to check issue_tracker
and repository
entries.conditional_uri_does_not_exist
.missing_whitespace_between_adjacent_strings
.avoid_final_parameters
.no_leading_underscores_for_library_prefixes
.no_leading_underscores_for_local_identifiers
.secure_pubspec_urls
.sized_box_shrink_expand
.use_decorated_box
.omit_local_variable_types
.This is a patch release that fixes:
dart pub publish
for servers with a path in the URL (pr dart-lang/pub#3244).Security advisory CVE-2021-22567: Bidirectional Unicode text can be interpreted and compiled differently than how it appears in editors and code-review tools. Exploiting this an attacker could embed source that is invisible to a code reviewer but that modifies the behavior of a program in unexpected ways. Dart 2.15.0 introduces new analysis warnings that flags the use of these.
Security advisory CVE-2021-22568: A malicious third-party package repository may impersonate a user on pub.dev for up to one hour after the user has published a package to that third-party package repository using dart pub publish
. As of Dart SDK version 2.15.0 requests to third-party package repositories will no longer include an OAuth2 access_token
intended for pub.dev.
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 keyword new
(here A.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.new
is used to initialize the variable f
produces a generic function which may be used to produce an instance of G<T>
for any type T
provided when f
is called. The tear-off G<String>.new
is used to initialize the variable g
to produce a non-generic function which may only be used to produce instances of type G<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,int
may be used as an expression, producing a value of type Type
. Generic classes (e.g. List
) could be referred to by name as an expression, but no type arguments could be provided and so only the dynamic
instantiation 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>
where f
is the generic method to specialize and T
is 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 final
instance 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;
).
dart:async
unawaited
function's argument nullable, to allow calls like unawaited(foo?.bar())
.dart:cli
waitFor
functionality, and the library containing only that function, are now deprecated.dart:core
name
getter on enum values.Enum.compareByIndex
helper function for comparing enum values by index.Enum.compareByName
helper function for comparing enum values by name.Iterable<T extends Enum>
, intended for SomeEnumType.values
lists, to look up values by name.IntegerDivisionByZeroException
. Makes the class also implement Error
. Code throwing the exception will be migrated to throwing an Error
instead until the class is unused and ready to be removed. Code catching the class should move to catching Error
instead (or, for integers, check first for whether it's dividing by zero).dart:ffi
Bool
native type.dart:io
SecurityContext
class in dart:io
has been updated to set the minimum TLS protocol version to TLS1_2_VERSION (1.2) instead of TLS1_VERSION.RawSocket.sendMessage
, RawSocket.receiveMessage
that allow passing of file handle references via Unix domain sockets.dart:js_util
js_util
methods setProperty
, callMethod
, and callConstructor
have been optimized to remove checks on arguments when the checks can be elided. Also, those methods, along with getProperty
and newObject
, now support a generic type argument to specify a return type. These two changes make simple js_util
usage, like reading and writing primitive properties or calling methods with simple arguments, have zero overhead.dart:web_sql
dart:web_sql
library.dart:html
dart:web_sql
(see above), window.openDatabase
has been removed.Breaking change #46100: The standalone dart2native
tool has been removed as previously announced. Its replacements are the dart compile exe
and dart compile aot-snapshot
commands, which offer the same functionality.
Breaking change: The standalone dartfmt
tool has been removed as previously announced. Its replacement is the dart format
command.
Note that dart format
has a different set of options and defaults than dartfmt
.
When a script is dart run
it will always be precompiled, but with incremental precompilation for following runs.
Breaking change #45451: Support for dart-ext:
-style native extensions has been removed as previously announced. Use dart:ffi
to 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.
Updated the Linter to 1.14.0
, which includes changes that
annotate_overrides
, prefer_contains
, and prefer_void_to_null
.avoid_dynamic_calls
stable.avoid_null_checks_in_equality_operators
false positive with non-nullable params.avoid_print
to allow kDebugMode
-wrapped print calls.avoid_redundant_argument_values
, unnecessary_lambdas
, and unnecessary_parenthesis
.avoid_renaming_method_parameters
.camel_case_types
, file_names
, etc.).file_names
to report at the start of the file (not the entire compilation unit).while (true) { ... }
in literal_only_boolean_expressions
.omit_local_variable_types
false positives.omit_local_variable_types
to not flag a local type that is required for inference.overridden_fields
false positive with static fields.prefer_collection_literals
named typed parameter false positives.prefer_const_constructors
false positive for deferred imports.prefer_final_parameters
handling of initializing formals.prefer_generic_function_type_aliases
false positives with incomplete statements.prefer_initializing_formals
false positives with factory constructors.prefer_void_to_null
false positive with overridden properties.prefer_void_to_null
false positives on overriding returns.prefer_void_to_null
false positives.unnecessary_constructor_name
to flag unnecessary uses of .new
.unnecessary_getters_setters
to only flag the getter.unnecessary_parenthesis
false positive with function expressions.use_build_context_synchronously
false positive in awaits inside anonymous functions.use_build_context_synchronously
.use_rethrow_when_possible
false positives.void_checks
false positives with incomplete source.dart pub get
will send usage metrics for packages from pub.dev, intended for popularity analysis.dart pub token
.$XDG_CONFIG_HOME/dart/pub-credentials.json
if $XDG_CONFIG_HOME
is defined, otherwise $HOME/.config/dart/pub-credentials.json
$HOME/Library/Application Support/dart/pub-credentials.json
%APPDATA%/dart/pub-credentials.json
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_secrets
section of your pubspec.yaml
.
Fixes unicode terminal detection windows.
New flag --example
to the commands dart pub get/upgrade/downgrade/add/remove
that will result in the example/
folder dependencies to be updated after operating in the current directory.
package:js
dart:html
classes can now declare members as external
. These members are equivalent to regular extension members that use js_util
to expose the underlying JavaScript.This is a patch release that fixes:
This is a patch release that fixes:
This is a patch release that fixes:
>>>
operator on older language versions (issue #46886).pubspec.lock
paths on Windows (issue dart-lang/pub#3012).Add an unsigned shift right operator >>>
. Pad with zeroes, ignoring the sign bit. On the web platform int.>>>
shifts the low 32 bits interpreted as an unsigned integer, so a >>> b
gives the same result as a.toUnsigned(32) >>> b
on 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 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); }
dart:async
The uncaught error handlers of Zone
s 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 the unawaited_futures
lint.
dart:core
Introduce Enum
interface implemented by all enum
declarations.
The native DateTime
class now better handles local time around daylight saving changes that are not precisely one hour. (No change on the Web which uses the JavaScript Date
object.)
Adds static methods hash
, hashAll
and hashAllUnordered
to the Object
class. These can be used to combine the hash codes of multiple objects in a consistent way.
The Symbol
constructor now accepts any string as argument. Symbols are equal if they were created from the same string.
dart:ffi
DynamicLibrary.providesSymbol
function to check whether a symbol is available in a dynamic library.Union
native type for interacting with unions in native memory.dart:html
convertNativeToDart_Dictionary()
now converts objects recursively, this fixes APIs like MediaStreamTrack.getCapabilities that convert between Maps and browser Dictionaries. #44319HttpHeaders
.dart:io
HttpClient
's .authenticate
and .authenticateProxy
setter callbacks must now accept a nullable realm
argument.HttpHeaders
.dart:typed_data
ByteBuffer
, TypedData
and all its subclasses, Int32x4
, Float32x4
, Float64x2
and Endian
.dart:web_sql
dart:web_sql
is marked deprecated and will be removed in an upcoming release. Also the API window.openDatabase
in dart:html
is 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_sql
library has been documented as unsupported and deprecated for many years as well and but wasn't annotated properly until now.
Dart_NewWeakPersistentHandle
's and Dart_NewFinalizableHandle
's object
parameter no longer accepts Pointer
s and subtypes of Struct
. Expandos no longer accept Pointer
s and subtypes of Struct
s.Breaking change #46100: The standalone dart2native
tool has been marked deprecated, and now prints a warning message. Its replacements are the dart compile exe
and dart compile aot-snapshot
commands, which offer the same functionality. The dart2native
tool will be removed from the Dart SDK in Dart 2.15.
Breaking change: The standalone dartfmt
tool has been marked deprecated, and now prints a warning message. Instead, use dart format
. The dartfmt
tool will be removed from the Dart SDK in Dart 2.15.
Note that dart format
has a different set of options and defaults than dartfmt
.
The dart create
command has been updated to create projects that use the new ‘recommended’ set of lints from package:lints
. See https://dart.dev/go/core-lints for more information about these lints.
The dart analyze
command has been extended to support specifying multiple files or directories to analyze; see also https://github.com/dart-lang/sdk/issues/45352.
The dartanalyzer
command's JSON output mode has been changed to emit the JSON output on stdout instead of stderr.
/* */
comments.FormatCommand
when formatting stdin.Updated the Linter to 1.8.0
, which includes changes that
prefer_is_not_empty
.no_logic_in_create_state
.package_names
to allow dart identifiers as package names.package_names
(causing keywords to wrongly get flagged).avoid_classes_with_only_static_member
to check for inherited members and also flag classes with only methods.curly_braces_in_flow_control_structures
to properly flag terminating else-if
blocks.always_specify_types
to support type aliases.unnecessary_string_interpolations
w/ nullable interpolated stringsavoid_function_literals_in_foreach_calls
for nullable iterables.avoid_returning_null
w/ NNBDuse_late_for_private_fields_and_variables
in the presence of const constructors.eol_at_end_of_file
.use_full_hex_values_for_flutter_colors
.use_build_context_synchronously
.use_setters_to_change_properties
to only highlight a method name, not the entire body and doc comment.unnecessary_getters_setters
to allow otherwise “unnecessary” getters and setters with annotations.missing_whitespace_between_adjacent_strings
to allow String interpolations at the beginning and end of String literals.unnecessary_getters_setters
to allow for setters with non-basic assignments (for example, ??=
or +=
).non_constant_identifier_names
to allow for a trailing underscore.prefer_final_parameters
where first parameter is final.directives_ordering
sorting of directives with dot paths and dot-separated package names.SecurityLintCode
instead of deprecated SecurityLintCodeWithUniqueName
.avoid_types_as_parameter_names
to skip field formal parameters.prefer_interpolation_to_compose_strings
where the left operand is not a String.only_throw_errors
for misidentified type variables.depend_on_referenced_packages
.avoid_returning_null_for_future
to skip checks for null-safe libraries.use_test_throws_matchers
.sort_child_properties_last
to accept closures after child.prefer_contains
and prefer_is_empty
.noop_primitive_operations
.avoid_web_libraries_in_flutter
as stable.prefer_final_parameters
.prefer_initializing_formals
to allow assignments where identifier names don't match.directives_ordering
to checks ordering of package:
imports in code outside pub packages.use_build_context_synchronously
to short-circuit await-discovery in terminating blocks.use_build_context_synchronously
to recognize nullable types when accessed from legacy libraries.dart pub publish
now respects .pubignore
files with gitignore-style rules. .gitignore
files in the repo are still respected if they are not overridden by a .pubignore
in the same directory.
pub no longer queries git for listing the files. This implies:
.gitignore
rule..gitignore
files respected..gitignore
and .pubignore
is always case-insensitive on MacOs and Windows (as is default for git
repositories).New flag dart pub deps --json
gives 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 --directory
option 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 tar
s.
PUB_HOSTED_URL
can now include a trailing slash.
Incremental compilation is now used for compilation of executables from dependencies when using dart run <package>:<command>
.
--legacy-javascript
flag 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.package:js
classes have been changed to be more correct and consistent with Dart2JS. Like anonymous
classes, non-anonymous
classes will no longer check the underlying type in DDC. The internal type representation of these objects have changed as well, which will affect the toString
value of these types.This is a patch release that fixes:
This is a patch release that fixes:
package:meta
v1.4.0
(issue #46183).This is a patch release that fixes:
Type aliases Non-function type aliases: Type aliases (names for types introduced via the typedef
keyword) 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.
dart:collection
The SplayTreeMap
was changed to allow null
as key if the compare
function allows it. It now checks that a new key can be used as an argument to the compare
function when the member is added, even if the map is empty (in which case it just compares the key to itself).
The SplayTreeSet
was changed to checks that a new element can be used as an argument to the compare
function when the member is added, even if the set is empty (in which case it just compares the element to itself).
dart:developer
serverWebSocketUri
property to ServiceProtocolInfo
.dart:ffi
Packed
for interacting with packed structs in native memory.Array
for interacting with structs with inline arrays.Static analyses with “error” severity can once again be ignored with comments like // ignore: code
and // 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 in analysis_options.yaml
, under the analyzer
heading, with a new YAML key, cannot-ignore
. For example, to declare that “error” codes and unused_import
cannot be ignored, write the following into analysis_options.yaml
:
analyzer: cannot-ignore: - error - unused_import
required
named parameters.Updated the Linter to 1.2.1
, which includes:
iterable_contains_unrelated_type
to better support List
content checks.camel_case_types
and prefer_mixin
to support non-function type aliases.prefer_mixin
to properly make exceptions for dart.collection
legacy mixins.avoid_multiple_declarations_per_line
, use_if_null_to_convert_nulls_to_bools
, deprecated_consistency
, use_named_constants
, use_build_context_synchronously
(experimental).avoid_as
.package:js
String
s that match an @Native
annotation 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, prefer dart:html
, an @anonymous
class, or js_util
. See issue #44211 for more details.This is a patch release that fixes a Dart VM compiler crashes when compiling initializers containing async closures (issue #45306).
Security advisory: This is a patch release that fixes a vulnerability in dart:html
related to DOM clobbering. See the security advisory CVE-2021-22540 for more details. Thanks again to Vincenzo di Cicco for finding and reporting this vulnerability.
This is a patch release that fixes crashes reported by Flutter 2 users (issue flutter/flutter#78167).
This is a patch release that fixes:
+
operator (issue #45140).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.11
to 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:
required
named parameterslate
variables!
null assertion operator?..
and ?[]
null-aware operatorsBreaking change #44660: Fixed an implementation bug where this
would sometimes undergo type promotion in extensions.
dart:async
onError()
on Future
to allow better typing of error callbacks.dart:collection
Add UnmodifiableSetView
class, which allows users to guarantee that methods that could change underlying Set
instance can not be invoked.
Make it explicit that LinkedList
compares elements by identity, and update contains()
to take advantage of this.
dart:core
Set.unmodifiable()
constructor, which allows users to create unmodifiable Set
instances.dart:ffi
Breaking change #44621: Invocations with a generic T
of sizeOf<T>
, Pointer<T>.elementAt()
, Pointer<T extends Struct>.ref
, and Pointer<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, allocate
in package:ffi
will no longer be able to invoke sizeOf<T>
generically, and will be deprecated as well. Instead, the Allocator
it is introduced to dart:ffi
, and also requires a constant T
on invocations. For migration notes see the breaking change request.
Breaking change #44622: Subtypes of Struct
without 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 extend Opaque
rather than Struct
.
dart:io
HttpRequest
now correctly follows HTTP 308 redirects (HttpStatus.permanentRedirect
).dart:isolate
debugName
positional parameter to ReceivePort
and RawReceivePort
constructors, a name which can be associated with the port and displayed in tooling.Isolate.exit([port, message])
which terminates current isolate and, if port
is specified, as a last action sends out the message
out to that port
.dart:html
EventStreamSubscription.cancel
has been updated to retain its synchronous timing when running in both sound and unsound null safety modes. See issue #44157 for more details.Breaking change #42312: Dart_WeakPersistentHandle
s 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_WeakPersistentHandleFinalizer
is renamed to Dart_HandleFinalizer
and had its handle
argument removed. All API functions using that type have been updated.
--no-defer-class-types
and --no-new-deferred-split
.Remove the --use-fasta-parser
, --preview-dart-2
, and --enable-assert-initializers
command line options. These options haven't been supported in a while and were no-ops.
Report diagnostics regarding the @internal
annotation.
Improve diagnostic-reporting regarding the @doNotStore
annotation.
Introduce a diagnostic which is reported when a library member named main
is not a function.
Introduce a diagnostic which is reported when a main
function's first parameter is not a supertype of List<String>
.
Introduce diagnostics for when an // ignore
comment 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 @deprecated
field 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 @visibleForTesting
members 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>.catchError
is called with an onError
callback which does not return FutureOr<T>
.
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.
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
, and avoid_type_to_string
.
Fix crash in prefer_collection_literals
when there is no static parameter element.
Fix false negatives for prefer_collection_literals
when 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_literals
when a LinkedHashSet or LinkedHashMap instantiation is used in a place with a static type other than Set or Map.
Update to package_names
to allow leading underscores.
Fix crashes in unnecessary_null_checks
and missing_whitespace_between_adjacent_strings
.
Update to void_checks
for null safety.
Fix range error in unnecessary_string_escapes
.
Fix false positives in unnecessary_null_types
.
Fix to prefer_constructors_over_static_methods
to respect type parameters.
Update to always_require_non_null_named_parameters
to be null safety-aware.
Update to unnecessary_nullable_for_final_variable_declarations
to allow dynamic.
Update overridden_fields
to not report on abstract parent fields.
Fix to unrelated_type_equality_checks
for null safety.
Improvements to type_init_formals
to allow types not equal to the field type.
Updates to public_member_apis
to check generic type aliases.
Fix close_sinks
to handle this
-prefixed property accesses.
Fix unawaited_futures
to handle Future
subtypes.
Performance improvements to always_use_package_imports
, avoid_renaming_method_parameters
, prefer_relative_imports
and public_member_api_docs
.
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 pub
executable has been deprecated. Use dart pub
instead. See dart tool.
New command dart pub add
that adds new dependencies to your pubspec.yaml
, and a corresponding dart pub remove
that removes dependencies.
New option dart pub upgrade --major-versions
will update constraints in your pubspec.yaml
to match the resolvable column reported in dart 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 in pubspec.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-safety
will attempt to update constraints in your pubspec.yaml
, such that only null-safety migrated versions of dependencies are allowed.
New option dart pub outdated --mode=null-safety
that will analyze your dependencies for null-safety.
dart pub get
and dart pub upgrade
will highlight dependencies that have been discontinued on pub.dev.
dart pub publish
will now check your pubspec keys for likely typos.
dart pub upgrade package_foo
fetchs dependencies but ignores the pubspec.lock
for package_foo
, allowing users to only upgrade a subset of dependencies.
New command dart pub login
that logs into pub.dev.
The --server
option to dart pub publish
and dart pub uploader
are deprecated. Use publish_to
in your pubspec.yaml
or set the $PUB_HOSTED_URL
environment variable.
pub global activate
no 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.
This is a patch release that fixes a crash in the Dart VM. (issue #44563).
This is a patch release that fixes a crash in the Dart VM (issues #43941, flutter/flutter#43620, and Dart-Code/Dart-Code#2814).
This is a patch release that fixes the following issues:
This is a patch release that fixes a DDC compiler crash (issue #43589).
This is a patch release that fixes the following issues:
dart:io
Abort
method to class HttpClientRequest
, which allows users to cancel outgoing HTTP requests and stop following IO operations.path
of class Cookie
. Having characters ranging from 0x00 to 0x1f and 0x3b (“;”) will lead to a FormatException
.HttpClient
and HttpServer
classes 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
BytesBuilder
is moved from dart:io
to dart:typed_data
. It's temporarily being exported from dart:io
as well.dart:uri
Uri.https
and Uri.http
constructors' queryParams
type.dart_api_dl.cc
is renamed to dart_api_dl.c
and changed to a pure C file.Dart_FinalizableHandle
s. They do auto-delete, and the weakly referred object cannot be accessed through them.--no-defer-class-types
. See the original post on the unsoundness in the deferred loading algorithm.--no-new-deferred-split
. See the original post on the unsoundness in the deferred loading algorithm.?:
) when they are nested.external
and abstract
fields and variables.Updated the Linter to 0.1.118
, which includes:
unnecessary_nullable_for_final_variable_declarations
.prefer_asserts_in_initializer_lists
.unnecessary_string_escapes
.unsafe_html
updated to support unique error codes.diagnostic_describe_all_properties
to check for Diagnosticable
s (not DiagnosticableMixin
s).use_late
.unnecessary_lambdas
to respect deferred imports.public_member_api_docs
to check mixins.unnecessary_statements
to skip as
expressions.prefer_relative_imports
to work with path dependencies.pub run
and pub global run
accepts a --(no-)-sound-null-safety
flag, that is passed to the VM.This is a patch release that fixes DDC to handle a breaking change in Chrome (issue #43193).
This is a patch release that fixes transient StackOverflow exceptions when building Flutter applications (issue flutter/flutter#63560).
This is a patch release that fixes unhandled exceptions in some Flutter applications (issue flutter/flutter#63038).
dart:async
Stream.multi
constructor creating streams which can be listened to more than once, and where each individual listener can be controlled independently.dart:convert
U+FFFD
). When decoding UTF-8, encoded surrogates will be treated as malformed input. When decoding UTF-8 with allowMalformed: true
, the number of replacement characters emitted for malformed input sequences has been changed to match the WHATWG encoding standard.dart:io
exit
has been changed to return the Never
type instead of void
. since no code will run after it,OSError
now implements Exception
. This change means OSError
will now be caught in catch clauses catching Exception
s.InternetAddress.tryParse
.InternetAddress
with address
starting with ‘@’ and type being InternetAddressType.Unix
will create an abstract Unix Domain Socket.Directory.current
does not work with long path.dart:html
Breaking change: CssClassSet.add()
previously returned null
if the CssClassSet
corresponded to multiple elements. In order to align with the null-safe changes in the Set
interface, it will now return false
instead. The same applies for CssClassSet.toggle
.
EventStreamSubscription.cancel
method used to return null
, but since StreamSubscription.cancel
has changed to be non-nullable, this method returns an empty Future
instead. Due to an optimization on null
Future
s, this method used to complete synchronously, but now that the Future
is 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 Console
have been updated to better reflect the modern Console specification. Particularly of interest are dir
and table
which take in extra optional arguments.
dart:mirrors
Breaking change #42714: web compilers (dart2js and DDC) now produce a compile-time error if dart:mirrors
is 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:mirrors
including webdev and flutter tools, we expect few projects to run into this problem.
--fix-single-cascade-statements
.var
in --fix-function-typedefs
.?.[]
to ?[]
.// ignore: code
and // ignore_for_file: code
).Updated the Linter to 0.1.117
, which includes:
do_not_use_environment
.exhaustive_cases
.no_default_cases
(experimental).sized_box_for_whitespace
.use_is_even_rather_than_modulo
.directives_ordering
to remove third party package special-casing.prefer_is_empty
to special-case assert initializers and const contexts.prefer_mixin
to allow “legacy” SDK abstract class mixins.sized_box_for_whitespace
to address false-positives.type_annotate_public_apis
to allow inferred types in final field assignments.unnecessary_lambdas
to check for tear-off assignability.unsafe_html
to use a SecurityLintCode
(making it un-ignorable) and to include Window.open
, Element.html
and DocumentFragment.html
in unsafe API checks. Also added checks for attributes and methods on extensions.print
function, 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, the Dart_StringToUTF8
function in the Dart API will convert unpaired surrogates into replacement characters.pub run
and pub global run
accepts a --enable-experiment
flag enabling experiments in the Dart VM (and language).pub outdated
:pubspec.lock
file. 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.pub run
: Fix precompilation with relative PUB_CACHE
paths (#2486).pubspec.lock
if they are already there (#2489).This is a patch release that fixes potential memory leaks in the Dart front-end (issues #42111 and #42112).
This is a patch release that fixes the following issues:
This is a patch release that fixes an AOT compilation bug in global transformations which manifests as a NoSuchMethod exception (issue flutter/flutter#56479).
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.
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
, or with Function
have no effect (spec section 19.6). We fixed an implementation bug that may be visible on some rare scenarios.
dart:async
Breaking change #40676: Changed the return type of StreamSubscription.cancel()
to Future<void>
. Previously, it was declared to return Future
and was allowed to return null
at runtime.
Breaking change #40681: The runZoned()
function is split into two functions: runZoned()
and runZonedGuarded()
, where the latter has a required onError
parameter, 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 be null
. These operations now synchronously throw an exception if passed a null
error.
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 a null
value.
Error handling functions need no longer be prepared for null
stack traces.
dart:core
Breaking change #40674: Three members on RuneIterator
no longer return null
when accessed before the first call to moveNext()
. Instead, current
and rawIndex
return -1
and currentAsString
returns an empty string.
Breaking change #40678: The String.fromEnvironment()
default value for defaultValue
is now an empty string instead of null
. Likewise, the default value for int.fromEnvironment()
's defaultValue
parameter is zero. Under null safety, a constructor cannot return null
, so this prepares these APIs for that.
The class CastError
is deprecated, and all implementation specific classes implementing TypeError
or CastError
now implement both. In a future release, CastError
will be removed. See issue 40763 for details.
Adds StackTrace.empty
constant which is the stack trace used as default stack trace when no better alternative is available.
The class TypeError
no longer extends AssertionError
. This also means that it no longer inherits the spurious message
getter which was added to AssertionError
when the second operand to assert
was allowed. The value of that getter on a TypeError
was the same string as returned by toString()
, so it is still available.
ArgumentError.checkNotNull()
and the RangeError
static methods checkValueInInterval()
, checkValidIndex()
and checkNotNegative()
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
TimelineTask
now accept an optional filterKey
parameter. If provided, the arguments for all events associated with the task will contain an entry named filterKey
, set to the value of the filterKey
parameter provided in the constructor. This will be used by tooling to allow for better filtering of timeline events.dart:ffi
Breaking change: Changed Pointer.asFunction()
and DynamicLibrary.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 if dart:ffi
is imported directly. This breaks code where dart:ffi
is not directly imported. To fix, add:
import 'dart:ffi';
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 was
changed to dynamic
. These methods would have resulted in a runtime error if they were used.
Breaking change: Node.insertAllBefore()
erroneously had a return type of Node
, even though it was not returning anything. This has been corrected to void
.
dart:io
Class HttpParser
will 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 HttpHeaders
methods add()
and set
have been changed to:
void add(String name, Object value, {bool preserveHeaderCase: false}) void set(String name, Object value, {bool preserveHeaderCase: false})
Setting preserveHeaderCase
to true
preserves the case of the name
parameter instead of converting it to lowercase. The HttpHeader.forEach()
method provides the current case of each header.
This is breaking only for classes extending or implementing HttpHeaders
and having their own add
or set
methods without the bool preserveHeaderCase
named parameter.
Breaking change #40702: The Socket
class now throws a SocketException
if 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 return null
.
Breaking change #40483: The Process
class now throws a StateError
if the process is detached (ProcessStartMode.detached
and ProcessStartMode.detachedWithStdio
) upon accessing the exitCode
getter. It now also throws when not connected to the child process's stdio (ProcessStartMode.detached
and ProcessStartMode.inheritStdio
) upon accessing the stdin
, stdout
, and stderr
getters. Previously, these getters would all return null
.
Breaking change #40706: The dummy object returned if FileStat.stat()
or FileStat.statSync()
fail now contains Unix epoch timestamps instead of null
for the accessed
, changed
, and modified
getters.
Breaking change #40709: The HeaderValue
class now parses more strictly in two invalid edge cases. This is the class used to parse the semicolon delimited parameters used in the Accept
, 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=").parameters
now gives {"a": ""}
rather than {"a": null}
.
Invalid inputs with unbalanced double quotes are now rejected. E.g. HeaderValue.parse('v;a="b').parameters
will now throw a HttpException
instead of giving {"a": "b"}
.
The HeaderValue.toString()
method now supports parameters with null
values by omitting the value. HeaderValue("v", {"a": null, "b": "c"}).toString()
now gives v; a; b=c
. This behavior can be used to implement some features in the Accept
and Sec-WebSocket-Extensions
headers.
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 InternetAddress
of InternetAddressType.Unix
into the connect()
, startConnect()
and bind()
methods. The port
argument in those methods will be ignored. The port
getter always returns 0 for Unix domain sockets.
Class InternetAddressType
gains one more option Unix
, which represents a Unix domain address.
Class InternetAddress
:
InternetAddress
constructor gains an optional type
parameter. To create a Unix domain address, type
is set to InternetAddressType.Unix
and address
is a file path.
InternetAddress
gains a new constructor fromRawAddress()
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()
and runWithHttpOverrides()
on HttpOverrides
no longer accept zoneSpecification
and onError
parameters. Use the runZoned()
or runZonedGuarded()
functions from dart:async
directly if needing to specify those.
Class HttpClient
and HttpServer
, when receiving HttpRequest
or HttpClientResponse
, will now put a 8K size limit on its header fields and values.
dart:mirrors
MirrorSystem.neverType
.Added Dart_TypeDynamic
, Dart_TypeVoid
and Dart_TypeNever
. Type dynamic
can no longer by reached using Dart_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()
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 --kernel
option 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.js
artifacts generated by legacy DDC have been deleted from dart-sdk/lib/dev_compiler
in favor of the versions located at dart-sdk/lib/dev_compiler/kernel
.
Breaking change: Functions passed to JavaScript using the recommended package:js
interop specification must now be wrapped with a call to allowInterop
. 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 with external
. Previously the external
could 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:mirrors
library 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.
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 -O3
where checks are omitted altogether. Even with -O3
, the performance of some is
checks used by your app may improve.
When using -O3
and -O4
incorrect 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 class Foo<T>
, then it compiles expressions like foo.runtimeType.toString()
to print Foo
. With the new representation, this will show Foo<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 with external
. Previously, the external could be omitted for unused constructors. Omitting external
for a constructor which is used would cause incorrect behavior at runtime, now omitting it on any constructor is a static error.
Other dart2js changes:
--package-root
flag, which was hidden and disabled in Dart 2.0.0, has been completely removed. Passing this flag will now cause dart2js
to fail.Updated the Linter to 0.1.114
, which includes:
avoid_shadowing_type_parameters
to support extensions and mixins.non_constant_identifier_names
to allow named constructors made up of only underscores (_
).avoid_unused_constructor_parameters
to ignore unused params named in all underscores (_
)..analysis_options
.Added pub outdated
command which lists outdated package dependencies, and gives advice on how to upgrade.
pub get
and pub upgrade
now fetch version information about hosted dependencies in parallel, improving the time package resolution performance.
pub get
and pub upgrade
no longer precompile executables from dependencies by default. Instead they are precompiled on first pub run
. Use pub get --precompile
to 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.yaml
then pub publish
will reject the package.
pub publish
no longer requires the presence of a homepage
field, if the repository
field is provided.
pub publish
warns if non-pre-release packages depends on pre-release packages or pre-release Dart SDKs.
Relative paths in pubspec.lock
now use /
also on Windows to make the file sharable between machines.
Fixed language version in .dart_tool/package_config.json
for 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 publish
warns if LICENSE and README.md files are not called those exact names.
pub repair cache
downloads hosted packages in parallel.
Security advisory: This is a patch release that addresses a vulnerability in dart:html
NodeValidator related to DOM clobbering of previousSibling
. See the security advisory CVE-2020-8923 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).
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).
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
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 } ```
dart:io
IOOverrides.serverSocketBind
to aid in writing tests that wish to mock ServerSocket.bind
.dart:typed_data
.sublistView(TypedData, [start, end])
to all TypedData
classes. The constructor makes it easier, and less error-prone, to create a view of (a slice of) another TypedData
object.The Linter was updated to 0.1.104
, which includes:
unnecessary_overrides
to allow overrides when annotations (besides @override
are specified)file_names
to allow names w/ leading _
's (and improved performance)unnecessary_final
pub get
generates .dart_tool/package_config.json
in addition to .packages
to support language versioning.
pub publish
now warns about the old flutter plugin registration format.
pub publish
now warns about the author
field in pubspec.yaml being. obsolete.
Show a proper error message when git
is not installed.
This is a patch release that reduces dart2js memory usage (issue 27883), improves stability on arm64 (issue 39090) and updates the Dart FFI documentation.
[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 extension
declaration. 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 by intList
matching the List<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 Null
values in a FutureOr
context. Namely, constraints of the forms similar to Null
<: FutureOr<T>
now yield Null
as the solution for T
. For example, the following code will now print “Null”, and it was printing “dynamic” before (note that the anonymous closure () {}
in the example has Null
as its return type):
import 'dart:async'; void foo<T>(FutureOr<T> Function() f) { print(T); } main() { foo(() {}); }
dart:mirrors
.dart:developer
parent
parameter to TimelineTask
constructor to allow for linking of asynchronous timeline events in the DevTools timeline view.dart:ffi
dart:ffi
API to be more precise with types, and provide convenient access to memory through extension getters and setters. The extension members on Pointer
provide .value
and .value =
for accessing the value in native memory and []
and []=
for indexed access. The method asExternalTypedData
has been replaced with asTypedList
extension methods. And finally, Structs
do no longer have a type argument and are accessed using the extension member .ref
on Pointer
. These changes makes the code using dart:ffi
much more concise.Pointer.allocate
and Pointer.free
). Instead, memory management is available in package:ffi.Pointer.offsetBy
was removed, use cast
and elementAt
instead.dart:ffi
static errors.dart:io
enableTimelineLogging
property to HttpClient
which, when enabled, will post HTTP connection and request information to the developer timeline for all HttpClient
instances.The Linter was updated to 0.1.101
, which includes:
diagnostic_describe_all_properties
to flag properties in Diagnosticable
s with no debug methods definednoSuchMethod
exception in camel_case_extensions
when analyzing unnamed extensionsavoid_print
to catch tear-off usageavoid_web_libraries_in_flutter
(experimental)unnecessary_lambdas
for coming MethodInvocation
vs. FunctionExpressionInvocation
changesThis is a patch release with properly signed binaries required for macOS Catalina (Issue 38765).
This is a patch release that prevents type inference failures in the analyzer (Issue 38365).
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:
e as T
) and type tests (e is T
).null
, even for types which override the ==
operator.&
, |
, and ^
binary operators on booleans....
and ...?
).if
element 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:
&&
operator only evaluates its second operand if the first evaluates to true.||
operator only evaluates its second operand if the first evaluates to false.??
operator only evaluates its second operand if the first evaluates to null.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;
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 of Uint8List
:
BytesBuilder.takeBytes()
BytesBuilder.toBytes()
Datagram.data
File.readAsBytes()
(Future<Uint8List>
)File.readAsBytesSync()
InternetAddress.rawAddress
RandomAccessFile.read()
(Future<Uint8List>
)RandomAccessFile.readSync()
RawSocket.read()
Utf8Codec.encode()
(and Utf8Encoder.convert()
)In addition, the following classes were updated to implement Stream<Uint8List>
rather than Stream<List<int>>
:
HttpRequest
Socket
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 of Stream.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
value
and error
constructors on Stream
to allow easily creating single-value or single-error streams.dart:core
Update Uri
class 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 Cookie
class‘s constructor’s name
and value
optional 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 name
and value
to 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 Cookie
class‘s name
and value
setters 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.
The Linter was updated to 0.1.96
, which includes:
unnecessary_parens
Dartdoc was updated to 0.28.4
; this version includes several fixes and is based on a newer version of the analyzer package.
This is a patch release that fixes a performance regression in JIT mode, as well as a potential crash of our AOT compiler.
Fixed a performance regression where usage of Int32List
could trigger repeated deoptimizations in JIT mode (Issue 37551).
Fixed a bug where usage of a static getter with name length
could cause a crash in our AOT compiler (Issue 35121).
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.
dart:isolate
TransferableTypedData
class was added to facilitate faster cross-isolate communication of Uint8List
data.
Breaking change: Isolate.resolvePackageUri
will always throw an UnsupportedError
when compiled with dart2js or DDC. This was the only remaining API in dart:isolate
that 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 a defaultPackagesBase
hook.
dart:developer
result
, errorCode
and errorDetail
getters in ServiceExtensionResponse
to allow for better debugging of VM service extension RPC results.dart:io
Fixed Cookie
class 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 HttpClientResponse
interface has been extended with the addition of a new compressionState
getter, which specifies whether the body of a response was compressed when it was received and whether it has been automatically uncompressed via HttpClient.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 HttpClientResponse
interface as subclasses will need to implement the new getter.
dart:async
await for
allowed null
as a stream due to a bug in StreamIterator
class. This bug has now been fixed.dart:core
#36171: The RegExp
interface 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, RegExp
methods that originally returned Match
objects 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 groupThis is a breaking change for implementers of the RegExp
interface. Subclasses will need to add the new properties and may have to update the return types on overridden methods.
class A<X> {}; class B<X> extends A<void Function(X)> {};
async
can now be used in asynchronous and generator functions.NoSuchMethod
errors for failing dynamic calls. Now they include specific information about the nature of the error such as:call()
method.The Linter was updated to 0.1.91
, which includes the following changes:
prefer_const_constructors
prefer_initializing_formals
to no longer suggest API breaking changesomit_local_variable_types
to allow explicit dynamic
sunrelated_type_equality_checks
unsafe_html
prefer_null_aware_operators
to work beyond local variables.prefer_if_null_operators
.prefer_contains
false positives.unnecessary_parenthesis
false positives.prefer_asserts_in_initializer_lists
false positivescurly_braces_in_flow_control_structures
to handle more casesprefer_double_quotes
sort_child_properties_last
type_annotate_public_apis
false positive for static const
initializerspub publish
will no longer warn about missing dependencies for import statements in example/
.openid
scope.This is a patch version release with a security improvement.
Security improvement: On Linux and Android, starting a process with Process.run
, Process.runSync
, or Process.start
would first search the current directory before searching PATH
(Issue 37101). This behavior effectively put the current working directory in the front of PATH
, even if it wasn‘t in the PATH
. This release changes that behavior to only searching the directories in the PATH
environment 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/ls
if it existed, even though it is not in the PATH
. 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.
This is a patch version release with bug fixes.
The focus in this release is on the new “UI-as-code” language features which make collections more expressive and declarative.
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.
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 ...?
.
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)), ] ], ); }
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.
dart:isolate
debugName
property to Isolate
.debugName
optional parameter to Isolate.spawn
and Isolate.spawnUri
.dart:core
The VM service now requires an authentication code by default. This behavior can be disabled by providing the --disable-service-auth-codes
flag.
Support for deprecated flags ‘-c’ and ‘--checked’ has been removed.
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_info
that provide similar features to those in the visualizer.
The command-line tools in package:dart2js_info
also work with the old JSON format, so you can start using them even before you enable the new format.
In a future release --dump-info
will 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
.
The Linter was updated to 0.1.86
, which includes the following changes:
prefer_inlined_adds
, prefer_for_elements_to_map_fromIterable
, prefer_if_elements_to_conditional_expressions
, diagnostic_describe_all_properties
.file_names
to skip prefixed-extension Dart files (.css.dart
, .g.dart
, etc.).unnecessary_parenthesis
.pub publish
without mentioning the current version.pub publish
.pub global activate
ing package from a custom pub URL.pub logout
. Logs you out of the current session.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.
Sets now have a literal syntax like lists and maps do:
var set = {1, 2, 3};
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.
The DEPRECATED_MEMBER_USE
hint was split into two hints:
DEPRECATED_MEMBER_USE
reports on usage of @deprecated
members declared in a different package.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE
reports on usage of @deprecated
members declared in the same package.Upgraded the linter to 0.1.82
which adds the following improvements:
provide_deprecation_message
, and use_full_hex_values_for_flutter_colors
, prefer_null_aware_operators
.prefer_const_declarations
set literal false-positives.prefer_collection_literals
to support set literals.unnecessary_parenthesis
play nicer with cascades.hash_and_equals
to respect hashCode
fields.package:kernel
Breaking change: The klass
getter on the InstanceConstant
class in the Kernel AST API has been renamed to classNode
for consistency.
Breaking change: Updated Link
implementation to utilize true symbolic links instead of junctions on Windows. Existing junctions will continue to work with the new Link
implementation, 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 FileSystemException
will be raised with errno set to ERROR_PRIVILEGE_NOT_HELD
(Issue 33966).
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 closed IOSink
now throws a StateError
.
On the Dart VM, a soundness hole when using dart:mirrors
to reflectively invoke a method in an incorrect way that violates its static types has been fixed (Issue 35611).
This release has no language changes.
dart:core
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.hasAttribute
and Element.hasAttributeNS
. (Issue 35655).
Improved dart2js compilation of element.attributes.remove(name)
to generate element.removeAttribute(name)
, so that there is no performance reason to migrate to the above methods.
Fixed a number of dart:html
bugs:
dart:html
(Issue 34318).ondblclick
and dblclickEvent
for Angular analyzer.removeAll
on classes
; elements
parameter should be Iterable<Object>
to match Set's removeAll
not Iterable<E>
(Issue 30278).dart:io
IOSink
now throws a StateError
.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.
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-startup
and --no-fast-startup
are 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 defers Foo
, and incorrectly makes the return type Future<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 be Foo
. 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-types
causes dart2js to run both the old and new algorithms and report any cases where an invalid type was detected.
The --new-deferred-split
flag enables this new algorithm.
The --categories=*
flag is being replaced. --categories=all
was only used for testing and it is no longer supported. --categories=Server
continues to work at this time but it is deprecated, please use --server-mode
instead.
The --library-root
flag 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 --help
for more details on the new flag.
Support for declarations-casts
has been removed and the implicit-casts
option now has the combined semantics of both options. This means that users that disable implicit-casts
might now see errors that were not previously being reported.
New hints added:
NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR
and NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR_USING_NEW
inform you when a @literal
const constructor is called in a non-const context (or with new
).INVALID_LITERAL_ANNOTATION
reports when something other than a const constructor is annotated with @literal
.SUBTYPE_OF_SEALED_CLASS
reports when any class or mixin subclasses (extends, implements, mixes in, or constrains to) a @sealed
class, and the two are declared in different packages.MIXIN_ON_SEALED_CLASS
reports when a @sealed
class is used as a superclass constraint of a mixin.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:
prefer_final_in_for_each
, unnecessary_await_in_return
, use_function_type_syntax_for_parameters
, avoid_returning_null_for_future
, and avoid_shadowing_type_parameters
.invariant_booleans
status to experimental.type_annotate_public_apis
false positives on local functions.avoid_shadowing_type_parameters
to report shadowed type parameters in generic typedefs.use_setters_to_change_properties
to not wrongly lint overriding methods.cascade_invocations
to not lint awaited targets.prefer_conditional_assignment
false positives.join_return_with_assignment
false positives.cascade_invocations
false positives.prefer_bool_in_asserts
as it is redundant in Dart 2.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 class
keyword, it uses mixin
:
mixin SetMixin<E> implements Set<E> { ... }
The new syntax also enables super
calls 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 .0
at the end of the number. In releases before 2.1, you need code like this when setting a double like fontSize
:
TextStyle(fontSize: 18.0)
Now you can remove the .0
:
TextStyle(fontSize: 18)
In releases before 2.1, fontSize : 18
causes 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:core
now exports Future
and Stream
. You no longer need to import dart:async
to use those very common types.
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 super
inside a mixin, the new syntax is required. This was previously only allowed with the experimental --supermixins
flag because it has some complex interactions with the type system. The new syntax addresses those issues and lets you use super
calls 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 super
calls, 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 explicit new
:
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 new
keyword 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 core
in core.List
to 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 extends
clause 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.
dart:async
stream.take(0).drain(value)
would not correctly forward the value
through the returned Future
.StreamTransformer.fromBind
constructor.Stream.fromIterable
to send a done event after the error when the iterator's moveNext
throws, and handle if the current
getter throws (issue 33431).dart:core
HashMap.fromEntries
and LinkedHashmap.fromEntries
constructors.ArgumentError.checkNotNull
utility method.Uri
parsing more permissive about [
and ]
occurring in the path, query or fragment, and #
occurring in fragment.Future
and Stream
from dart:core
.&
, |
and ^
to bool
.UnmodifiableMapMixin
. Some maps intended to be unmodifiable incorrectly allowed new methods added in Dart 2 to succeed.provisional
annotation and the Provisional
annotation 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.instance
DedicatedWorkerGlobalScope.instance
ServiceWorkerGlobalScope.instance
WorkerGlobalScope.instance
dart:io
(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 -O
flag to tune optimization levels. For more details run dart2js -h -v
.
We recommend to enable optimizations using the -O
flag instead of individual flags for each optimization. This is because the -O
flag 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 -O1
and to deploy with -O3
.
Bumped the linter to 0.1.70
which includes the following new lints:
avoid_returning_null_for_void
sort_pub_dependencies
prefer_mixin
avoid_implementing_value_types
flutter_style_todos
avoid_void_async
prefer_void_to_null
and improvements:
prefer_iterable_whereType
.await_only_futures
null_closures
sort_constructors_first
to apply to all members.unnecessary_this
to work on field initializers.unawaited_futures
to ignore assignments within cascades.invariant_booleans
.unawaited_futures
.unawaited_futures
to check cascades.void_checks
(allowing T Function()
to be assigned to void Function()
).lines_longer_than_80_chars
.--checked
flag to pub run
to --enable-asserts
.--packages-dir
flag is now ignored.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 async
now run synchronously until the first await
statement. 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_CAPS
to lowerCamelCase
.
(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 new
keyword is optional and can be omitted. Likewise, const
can be omitted inside a const context (issue 30921).
Dartium is no longer maintained or supported.
“Strong mode” is now the official type system of the language.
The new
keyword is optional and can be omitted. Likewise, const
can be omitted inside a const context.
A string in a part of
declaration may now be used to refer to the library this file is part of. A library part can now declare its library as either:
part of name.of.library;
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 async
now run synchronously until the first await
statement. Previously, they would return to the event loop once at the top of the function body before any code runs (issue 30345).
The type void
is now a Top type like dynamic
, and Object
. 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:
An empty return;
in an async function with return type Future<Object>
does not report an error.
return exp;
where exp
has type void
in an async function is now an error unless the return type of the function is void
or dynamic
.
Mixed return statements of the form return;
and return exp;
are now allowed when exp
has type void
.
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).
Replaced UPPER_CASE
constant names with lowerCamelCase
. For example, HTML_ESCAPE
is now htmlEscape
.
The Web libraries were re-generated using Chrome 63 WebIDLs (details).
dart:async
Stream
:cast
and castFrom
.firstWhere
, lastWhere
, and singleWhere
to return Future<T>
and added an optional T orElse()
callback.StreamTransformer
: added cast
and castFrom
.StreamTransformerBase
: new class.Timer
: added tick
property.Zone
bindBinaryCallbackGuarded
, bindCallbackGuarded
, and bindUnaryCallbackGuarded
.Zone.ROOT
to Zone.root
.defaultValue
parameter on Stream.firstWhere
and Stream.lastWhere
.dart:cli
waitFor
: function that suspends a stack to wait for a Future
to complete.dart:collection
MapBase
: added mapToString
.LinkedHashMap
no longer implements HashMap
LinkedHashSet
no longer implements HashSet
.of
constructor to Queue
, ListQueue
, DoubleLinkedQueue
, HashSet
, LinkedHashSet
, SplayTreeSet
, Map
, HashMap
, LinkedHashMap
, SplayTreeMap
.Maps
class. Extend MapBase
or mix in MapMixin
instead to provide map method implementations for a class.Document
method getCSSCanvasContext
and property supportsCssCanvasContext
.Element
property xtag
no longer supported in browsers.ServiceWorker
class.MessageChannel
and MessagePort
addEventListener
automatically calls start
method to receive queued messages.dart:convert
Base64Codec.decode
return type is now Uint8List
.JsonUnsupportedObjectError
: added partialResult
propertyLineSplitter
now implements StreamTransformer<String, String>
instead of Converter
. It retains Converter
methods convert
and startChunkedConversion
.Utf8Decoder
when compiled with dart2js uses the browser's TextDecoder
in some common cases for faster decoding.ASCII
, BASE64
, BASE64URI
, JSON
, LATIN1
and UTF8
to ascii
, base64
, base64Uri
, json
, latin1
and utf8
.HtmlEscapeMode
constants UNKNOWN
, ATTRIBUTE
, SQ_ATTRIBUTE
and ELEMENT
to unknown
, attribute
, sqAttribute
and elements
.jsonEncode
, jsonDecode
, base64Encode
, base64UrlEncode
and base64Decode
top-level functions.encode
on AsciiCodec
and Latin1Codec
, and convert
on AsciiEncoder
, Latin1Encoder
, to Uint8List
.utf8.decoder.fuse(json.decoder)
to ignore leading Unicode BOM.dart:core
BigInt
class added to support integers greater than 64-bits.proxy
annotation.Provisional
class and provisional
field.pragma
annotation.RegExp
added static escape
function.Uri
class now correctly handles paths while running on Node.js on Windows.Iterable
added members cast
, castFrom
, followedBy
and whereType
.Iterable.singleWhere
added orElse
parameter.List
added +
operator, first
and last
setters, and indexWhere
and lastIndexWhere
methods, and static copyRange
and writeIterable
methods.Map
added fromEntries
constructor.Map
added addEntries
, cast
, entries
, map
, removeWhere
, update
and updateAll
members.MapEntry
: new class used by Map.entries
.IterableBase
, ListBase
, SetBase
or MapBase
(or uses the corresponding mixins) from dart:collection
, the new members are implemented automatically.of
constructor to List
, Set
, Map
.double.INFINITY
, double.NEGATIVE_INFINITY
, double.NAN
, double.MAX_FINITE
and double.MIN_POSITIVE
to double.infinity
, double.negativeInfinity
, double.nan
, double.maxFinite
and double.minPositive
.DateTime
to lower case: MONDAY
through SUNDAY
, DAYS_PER_WEEK
(as daysPerWeek
), JANUARY
through DECEMBER
and MONTHS_PER_YEAR
(as monthsPerYear
).Duration
to lower case: MICROSECONDS_PER_MILLISECOND
to microsecondsPerMillisecond
, MILLISECONDS_PER_SECOND
to millisecondsPerSecond
, SECONDS_PER_MINUTE
to secondsPerMinute
, MINUTES_PER_HOUR
to minutesPerHour
, HOURS_PER_DAY
to hoursPerDay
, MICROSECONDS_PER_SECOND
to microsecondsPerSecond
, MICROSECONDS_PER_MINUTE
to microsecondsPerMinute
, MICROSECONDS_PER_HOUR
to microsecondsPerHour
, MICROSECONDS_PER_DAY
to microsecondsPerDay
, MILLISECONDS_PER_MINUTE
to millisecondsPerMinute
, MILLISECONDS_PER_HOUR
to millisecondsPerHour
, MILLISECONDS_PER_DAY
to millisecondsPerDay
, SECONDS_PER_HOUR
to secondsPerHour
, SECONDS_PER_DAY
to secondsPerDay
, MINUTES_PER_DAY
to minutesPerDay
, and ZERO
to zero
.typeArguments
to Invocation
class.Invocation
objects directly, without going through noSuchMethod
.unaryMinus
and empty
constant symbols on the Symbol
class.UriData.dataAsBytes
to Uint8List
.tryParse
static method to int
, double
, num
, BigInt
, Uri
and DateTime
.onError
parameter on int.parse
, double.parse
and num.parse
.NoSuchMethodError
constructor.int.parse
on the VM no longer accepts unsigned hexadecimal numbers greater than or equal to 2**63
when not prefixed by 0x
. (SDK issue 32858)dart:developer
Flow
class added.Timeline.startSync
and Timeline.timeSync
now accepts an optional parameter flow
of type Flow
. The flow
parameter is used to generate flow timeline events that are enclosed by the slice described by Timeline.{start,finish}Sync
and Timeline.timeSync
.dart:html
query
and queryAll
. Use querySelector
and querySelectorAll
.dart:io
HttpStatus
added UPGRADE_REQUIRED
.IOOverrides
and HttpOverrides
added to aid in writing tests that wish to mock varios dart:io
objects.Platform.operatingSystemVersion
added that gives a platform-specific String describing the version of the operating system.ProcessStartMode.INHERIT_STDIO
added, which allows a child process to inherit the parent's stdio handles.RawZLibFilter
added for low-level access to compression and decompression routines.SecureSocket
, SecurityContext
, and X509Certificate
to be consistent across all platforms. All SecureSocket
, SecurityContext
, and X509Certificate
properties and methods are now supported on iOS and OSX.SecurityContext.alpnSupported
deprecated as ALPN is now supported on all platforms.SecurityContext
: added withTrustedRoots
named optional parameter constructor, which defaults to false.timeout
parameter to Socket.connect
, RawSocket.connect
, SecureSocket.connect
and RawSecureSocket.connect
. If a connection attempt takes longer than the duration specified in timeout
, a SocketException
will be thrown. Note: if the duration specified in timeout
is greater than the OS level timeout, a timeout may occur sooner than specified in timeout
.Stdin.hasTerminal
added, which is true if stdin is attached to a terminal.WebSocket
added static userAgent
property.RandomAccessFile.close
returns Future<void>
IOOverrides.socketConnect
.ZLibOptions
, FileMode
, FileLock
, FileSystemEntityType
, FileSystemEvent
, ProcessStartMode
, ProcessSignal
, InternetAddressType
, InternetAddress
, SocketDirection
, SocketOption
, RawSocketEvent
, and StdioType
, and deprecated the old SCREAMING_CAPS
constants.zlib
, gzip
, and systemEncoding
, and deprecated the old SCREAMING_CAPS
top-level constants.FileMode
constants READ
, WRITE
, APPEND
, WRITE_ONLY
, and WRITE_ONLY_APPEND
. Please use e.g. FileMode.read
instead.X509Certificate.der
, X509Certificate.pem
, and X509Certificate.sha1
.FileSystemEntity.fromRawPath
constructor to allow for the creation of FileSystemEntity
using Uint8List
buffers.HttpStatus
, HttpHeaders
, ContentType
, HttpClient
, WebSocketStatus
, CompressionOptions
, and WebSocket
. The SCREAMING_CAPS
constants are marked deprecated. Note that HttpStatus.CONTINUE
is now HttpStatus.continue_
, and that e.g. HttpHeaders.FIELD_NAME
is now HttpHeaders.fieldNameHeader
.Platform.packageRoot
, which is only used for packages/
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.HttpClient.connectionTimeout
.{Socket,RawSocket,SecureSocket}.startConnect
. These return a ConnectionTask
, which can be used to cancel an in-flight connection attempt.dart:isolate
Isolate.spawn
take a type parameter representing the argument type of the provided function. This allows functions with arguments types other than Object
in strong mode.IMMEDIATE
and BEFORE_NEXT_EVENT
on Isolate
to immediate
and beforeNextEvent
.Isolate.packageRoot
, which is only used for packages/
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.packageRoot
parameter in Isolate.spawnUri
, which is was previously used only for packages/
directory resolution. That style of resolution is no longer supported in Dart 2.dart.math
E
, LN10
, LN
, LOG2E
, LOG10E
, PI
, SQRT1_2
and SQRT2
to e
, ln10
, ln
, log2e
, log10e
, pi
, sqrt1_2
and sqrt2
.dart.mirrors
IsolateMirror.loadUri
, which allows dynamically loading additional code.MirrorsUsed
as deprecated. The MirrorsUsed
annotation 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
Unmodifiable
view classes over all List
types.BYTES_PER_ELEMENT
to bytesPerElement
on all typed data lists.XXXX
through WWWW
on Float32x4
and Int32x4
to lower-case xxxx
through wwww
.Endinanness
to Endian
and its constants from BIG_ENDIAN
, LITTLE_ENDIAN
and HOST_ENDIAN
to little
, big
and host
.Support for MIPS has been removed.
Dart int
is 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 in Isolate.resolveUri
). Users relying on packages/
directories should switch to .packages
files.
Expose JavaScript Promise APIs using Dart futures. For example, BackgroundFetchManager.get
is 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.
dartdevc will no longer throw an error from is
checks 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 as
casts on Iterable<T>
, Map<T>
, Future<T>
, and Stream<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 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 --checked
flag in Dart 1.0).
We exposed a --omit-implicit-checks
flag 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-annotations
in 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:mirrors
support 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:isolate
support was removed. To launch background tasks, please use webworkers instead. APIs for webworkers can be accessed from dart:html
or JS-interop.
dart2js no longer supports the --package-root
flag. This flag was deprecated in favor of --packages
long ago.
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 @visibleForTesting
elements. Accessing a method, function, class, etc. annotated with @visibleForTesting
from a file not in a test/
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_OPERATOR
when an operator is used after a null-aware access. For example:
x?.a - ''; // HINT
NULL_AWARE_IN_LOGICAL_OPERATOR
when an expression with null-aware access is used as a condition in logical operators. For example:
x.a || x?.b; // HINT
The command line analyzer (dartanalyzer) and the analysis server no longer treat directories named packages
specially. 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 of packages
directories was to support using symlinks for package: resolution; that functionality is now handled by .packages
files.
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: false
set (and will emit a hint for strong-mode: true
, which is no longer necessary).
The dartanalyzer --strong
flag is now deprecated and ignored. The command-line analyzer now only analyzes code in strong mode.
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 --fix
to remove unneeded new
and const
keywords, and change :
to =
before named parameter default values.
Change formatting rules around static methods to uniformly format code with and without new
and const
.
Format expressions inside string interpolation.
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
, and pub serve
. Use the [new build system][transformers] instead.
There is now a default SDK constraint of <2.0.0
for 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.0
now allows pre-release SDK versions such as 2.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 the PUB_ALLOW_PRERELEASE_SDK
environment variable to false
.
Allow depending on a package in a subdirectory of a Git repository. Git dependencies may now include a path
parameter, 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 --executables
option to pub deps
command. This will list all available executables that can be run with pub run
.
The Flutter sdk
source will now look for packages in flutter/bin/cache/pkg/
as well as flutter/packages/
. In particular, this means that packages can depend on the sky_engine
package from the sdk
source (issue 1775).
Pub now caches compiled packages and snapshots in the .dart_tool/pub
directory, rather than the .pub
directory (issue 1795).
Other bug fixes and improvements.
dart:io
SecureSocket
, SecurityContext
, and X509Certificate
to be consistent across all platforms. All SecureSocket
, SecurityContext
, and X509Certificate
properties and methods are now supported on iOS and OSX.pub serve
.During a dynamic type check, void
is not required to be null
anymore. In practice, this makes overriding void
functions with non-void
functions safer.
During static analysis, a function or setter declared using =>
with return type void
now allows the returned expression to have any type. For example, assuming the declaration int x;
, it is now type correct to have void 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 Function
in its declaration. For instance, the type of void foo() {}
would be void 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())
. typedefs
have 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);
dart:async
, dart:core
, dart:io
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 a StateError
.dart:convert
ChunkedConverter
class.Map<String, dynamic>
instead of Map<dynamic, dynamic>
. A JSON-map is not a HashMap
or LinkedHashMap
anymore (but just a Map
).dart:io
Platform.localeName
, needed for accessing the locale on platforms that don't store it in an environment variable.ProcessInfo.currentRss
and ProcessInfo.maxRss
for inspecting the Dart VM process current and peak resident set size.RawSynchronousSocket
, a basic synchronous socket implementation.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:html
REMOVED classes: Bluetooth
, BluetoothDevice
, BluetoothGattCharacteristic
, BluetoothGattRemoteServer
, BluetoothGattService
, BluetoothUuid
, CrossOriginConnectEvent
, DefaultSessionStartEvent
, DomSettableTokenList
, MediaKeyError
, PeriodicSyncEvent
, PluginPlaceholderElement
, ReadableStream
, StashedMessagePort
, SyncRegistration
REMOVED members:
texImage2DCanvas
was removed from RenderingContext
.endClip
and startClip
were removed from Animation
.after
and before
were removed from CharacterData
, ChildNode
and Element
.keyLocation
was removed from KeyboardEvent
. Use location
instead.generateKeyRequest
, keyAddedEvent
, keyErrorEvent
, keyMessageEvent
, mediaGroup
, needKeyEvent
, onKeyAdded
, onKeyError
, onKeyMessage
, and onNeedKey
were removed from MediaElement
.getStorageUpdates
was removed from Navigator
status
was removed from PermissionStatus
getAvailability
was removed from PreElement
Other behavior changes:
url("http://google.com")
instead of url(http://google.com)
.int
to num
.num
instead of whole numbers).setRangeText
with a selectionMode
value of ‘invalid’ is no longer valid. Only “select”, “start”, “end”, “preserve” are allowed.dart:svg
dart:svg
carefully.dart:web_audio
AudioContext
- createIirFilter
returns a new class IirFilterNode
.dart:web_gl
new classes: CompressedTextureAstc
, ExtColorBufferFloat
, ExtDisjointTimerQuery
, and TimerQueryExt
.
ExtFragDepth
added: readPixels2
and texImage2D2
.
Removed ad hoc Future.then
inference in favor of using FutureOr
. Prior to adding FutureOr
to the language, the analyzer implemented an ad hoc type inference for Future.then
(and overrides) treating it as if the onValue callback was typed to return FutureOr
for the purposes of inference. This ad hoc inference has been removed now that FutureOr
has been added.
Packages that implement Future
must either type the onValue
parameter to .then
as returning FutureOr<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 type void
now allows the returned expression to have any type.
Dartium
Dartium is now based on Chrome v50. See Core library changes above for details on the changed APIs.
Pub
pub build
and pub serve
Added 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 potentially pub build
in 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-compiler
flag, which supports dartdevc
, dart2js
or none
as options. This is the easiest way to try things out without changing the default.
Add config to your pubspec. There is a new web
key which supports a single key called compiler
. 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
dartfmt
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, @virtual
is 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
dart:core
Uri.isScheme
function to check the scheme of a URI. Example: uri.isScheme("http")
. Ignores case when comparing.UriData.parse
validate 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.dart:io
File.lastAccessed
, File.lastAccessedSync
, File.setLastModified
, File.setLastModifiedSync
, File.setLastAccessed
, and File.setLastAccessedSync
.{Stdin,Stdout}.supportsAnsiEscapes
.print()
and Stdout.write*()
now correctly print unicode characters to the console on Windows. Calls to Stdout.add*()
behave as before.Analysis
dartanalyzer
now follows the same rules as the analysis server to find an analysis options file, stopping when an analysis options file is found:package:flutter
.package:dart.analysis_options/default.yaml
if it exists.dartanalyzer
:--options
and that file will be used instead of searching for an analysis options file.--strong
or --no-strong
) takes precedence over any corresponding value specified in the analysis options file.Dartium, dart2js, and DDC
dart:io
are 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 package http
). This might change again when configuration specific imports are supported.Pub
pub.dartlang.org
to allow better understanding of why a particular package is being accessed.pub publish
lib/
or bin/
, or a package that’s not a dev dependency from within benchmark/
, example/
, test/
or tool/
.pub get
and pub upgrade
dartfmt
-
and --
. Code that does this is pathological, but it technically meant dartfmt could change the semantics of the code.Patch release, resolves two issues:
Dart VM crash: Issue 28072
Dart VM bug combining types, await, and deferred loading: Issue 28678
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 second message
argument (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 Null
type has been moved to the bottom of the type hierarchy. As such, it is considered a subtype of every other type. The null
literal was always treated as a bottom type. Now the named class Null
is 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 covariant
modifier 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 assume n
is at least a num
-- that‘s why there’s a constraint on T, after all. Implicitly using dynamic
as 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.
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, your swizzle()
function would be “polymorphic over asynchrony”. It would allow both synchronous and asynchronous swizzlers. Because await
accepts 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 dynamic
or Object
, 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 a String
or a Future<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 like Future.then()
. In those cases, having the type system understand this magical union type helps type inference figure out the type argument of then()
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.
Dart2Js
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 --offline
and deleted by pub cache repair
.
Make pub run
run 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 where pub serve
serves them (packages/package_name/
instead of ../packages/package_name/
).
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 variable DART_USE_GYP
before running gclient sync
or gclient runhooks
, but this will be removed in a future release.Patch release, resolves one issue:
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 x
to initialize y
in class 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 rethrow
statement. (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
, return
or throw
.
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)
dart:core
: Set.difference
now takes a Set<Object>
as argument. (SDK issue 27573)
dart:developer
Service
class.Isolate
.Dart Dev Compiler
loadLibrary()
on deferred libraries. Deferred libraries are still loaded eagerly. (SDK issue 27343)Patch release, resolves one issue:
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; }
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 tcmalloc
library 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.crt
followed 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-file
and --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 using c_rehash
.
The VM now throws a catchable Error
when method compilation fails. This allows easier debugging of syntax errors, especially when testing. (SDK issue 23684)
dart:core
: Remove deprecated Resource
class. Use the class in package:resource
instead.dart:async
Future.wait
now catches synchronous errors and returns them in the returned Future. (SDK issue 27249)Future
on Stream.cancel
operations. Discourages to return null
from cancel
. (SDK issue 26777)dart:io
WebSocket.addUtf8Text
to allow sending a pre-encoded text message without a round-trip UTF-8 conversion. (SDK issue 27129)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 @checked
to 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 @virtual
to 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 {}
dartfmt
- upgraded to v0.2.10
--set-exit-if-changed
to set the exit code on a change.Pub
packages/
directory by default. Instead, it generates a .packages
file, called a package spec. To generate a packages/
directory in addition to the package spec, use the --packages-dir
flag with pub get
, pub upgrade
, and pub downgrade
. See the Good-bye symlinks article for details.Patch release, resolves one issue:
dartfmt
- upgraded to v0.2.9+1
Pub
Added a --no-packages-dir
flag to pub get
, pub upgrade
, and pub downgrade
. When this flag is passed, pub will not generate a packages/
directory, and will remove that directory and any symlinks to it if they exist. Note that this replaces the unsupported --no-package-symlinks
flag.
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 flutter
executable, and when the Flutter SDK version matches the constraint.
Added sdk
as a new package source that fetches packages from a hard-coded SDK. Currently only the flutter
SDK is supported:
dependencies: flutter_driver: sdk: flutter version: ^0.0.1
A Flutter sdk
dependency will only be satisfiable when pub is running in the context of the flutter
executable, and when the Flutter SDK contains a package with the given name whose version matches the constraint.
tar
files on Linux are now created with 0
as 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.
dart2js
dart2dart
(aka dart2js --output-type=dart
) has been removed (this was deprecated in Dart 1.11).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).
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)
dart:core
Uri.resolve
(SDK issue 26804).dart:io
FileLock.BLOCKING_SHARED
and FileLock.BLOCKING_EXCLUSIVE
.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)
dart:convert
ChunkedConverter
which was erroneously added in 1.16.dart:core
Uri.replace
supports iterables as values for the query parameters.Uri.parseIPv6Address
returns a Uint8List
.dart:io
NetworkInterface.listSupported
, which is true
when NetworkInterface.list
is supported, and false
otherwise. Currently, NetworkInterface.list
is not supported on Android.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 --offline
would crash when a prerelease version was selected.
Dartium and content shell
Patch release, resolves one issue:
dart:convert
Added BASE64URL
codec and corresponding Base64Codec.urlSafe
constructor.
Introduce ChunkedConverter
and deprecate chunked methods on Converter
.
dart:html
There have been a number of BREAKING changes to align APIs with recent changes in Chrome. These include:
Chrome's ShadowRoot
interface no longer has the methods getElementById
, getElementsByClassName
, and getElementsByTagName
, e.g.,
elem.shadowRoot.getElementsByClassName('clazz')
should become:
elem.shadowRoot.querySelectorAll('.clazz')
The clipboardData
property has been removed from KeyEvent
and Event
. It has been moved to the new ClipboardEvent
class, which is now used by copy
, cut
, and paste
events.
The layer
property has been removed from KeyEvent
and UIEvent
. It has been moved to MouseEvent
.
The Point get page
property has been removed from UIEvent
. It still exists on MouseEvent
and Touch
.
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
SecurityContext.alpnSupported
, which is true if a platform supports ALPN, and false otherwise.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.
Static checking of for in
statements. 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"]) { ... }
Pub
pub serve
now provides caching headers that should improve the performance of requesting large files multiple times.
Both pub get
and pub upgrade
now have a --no-precompile
flag that disables precompilation of executables and transformed dependencies.
pub publish
now 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 dartdevc
executable has been added to the SDK.
It will help early adopters validate the implementation and provide feedback. dartdevc
is not yet ready for production usage.
Read more about the Dart Dev Compiler here.
dart:async
StreamView
class a const
class.dart:core
Uri.queryParametersAll
to handle multiple query parameters with the same name.dart:io
SecurityContext.usePrivateKeyBytes
, SecurityContext.useCertificateChainBytes
, SecurityContext.setTrustedCertificatesBytes
, and SecurityContext.setClientAuthoritiesBytes
.directory
argument of SecurityContext.setTrustedCertificates
has been removed.SecurityContext
for PKCS12 certificate and key containers.SecurityContext
that accept certificate data now accept an optional named parameter password
, similar to SecurityContext.usePrivateKeyBytes
, for use as the password for PKCS12 data.Dartium and content shell
dart:html
, dart:svg
, etc) have not been updated.Element.animate
.dartfmt
- upgraded to v0.2.4
extensionRPCs
in Isolate
was not marked optional.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.
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)
Patch release, resolves one issue:
dart:async
Future.any
static method.Stream.fromFutures
constructor.dart:convert
Base64Decoder.convert
now takes optional start
and end
parameters.dart:core
current
getter to StackTrace
class.Uri
class added support for data URIsdataFromBytes
and dataFromString
.data
getter for data:
URIs with a new UriData
class for the return type.growable
parameter to List.filled
constructor.DateTime
: DateTime.microsecond
, DateTime.microsecondsSinceEpoch
, and new DateTime.fromMicrosecondsSinceEpoch
.dart:math
Random
added a secure
constructor returning a cryptographically secure random generator which reads from the entropy source provided by the embedder for every generated random value.dart:io
Platform
added a static isIOS
getter and Platform.operatingSystem
may now return ios
.Platform
added a static packageConfig
getter.compression
on the methods WebSocket.connect
, WebSocket.fromUpgradedSocket
, and WebSocketTransformer.upgrade
and the WebSocketTransformer
constructor can be used to modify or disable compression using the new CompressionOptions
class.dart:isolate
packageConfig
and packageRoot
instance getters to Isolate
.resolvePackageUri
method to Isolate
.packageConfig
and automaticPackageResolution
to the Isolate.spawnUri
constructor.dartfmt
Better 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 .packages
file, this is unlikely to break many people in practice.
Breaking: Support for barback
versions prior to 0.15.0 (released July
pub serve
now GZIPs the assets it serves to make load times more similar to real-world use-cases.
pub deps
now supports a --no-dev
flag, which causes it to emit the dependency tree as it would be if no dev_dependencies
were in use. This makes it easier to see your package's dependency footprint as your users will experience it.
pub global run
now 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
, and pub 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 run
on a global script that didn't exist.
Fixed a crashing bug when a pubspec contains a dependency without a source declared.
Patch release, resolves one issue:
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))
dart:async
StreamController
added getters for onListen
, onPause
, and onResume
with the corresponding new typedef void ControllerCallback()
.StreamController
added a getter for onCancel
with the corresponding new typedef ControllerCancelCallback()
;StreamTransformer
instances created with fromHandlers
with no handleError
callback now forward stack traces along with errors to the resulting streams.dart:convert
Base64Codec
, Base64Encoder
, and Base64Decoder
.const Base64Codec BASE64
.dart:core
Uri
added removeFragment
method.String.allMatches
(implementing Pattern.allMatches
) is now lazy, as all allMatches
implementations are intended to be.Resource
is deprecated, and will be removed in a future release.dart:developer
Timeline
class for interacting with Observatory's timeline feature.ServiceExtensionHandler
, ServiceExtensionResponse
, and registerExtension
which enable developers to provide their own VM service protocol extensions.dart:html
, dart:indexed_db
, dart:svg
, dart:web_audio
, dart:web_gl
, dart:web_sql
double
to num
. 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 typed double
in checked mode. You may need to insert a toDouble()
call or accept num
. Examples of APIs that are affected include Element.getBoundingClientRect
and TextMetrics.width
.dart:io
Breaking: Secure networking has changed, replacing the NSS library with the BoringSSL library. SecureSocket
, SecureServerSocket
, RawSecureSocket
,RawSecureServerSocket
, HttpClient
, and HttpServer
now all use a SecurityContext
object 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 SecurityContext
from 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.html
HttpClient
no longer sends URI fragments in the request. This is not allowed by the HTTP protocol. The HttpServer
still 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 shared
argument to true
when creating server socket and HttpServer
instances.
ServerSocketReference
and RawServerSocketReference
classes have been removed.reference
properties on ServerSocket
and RawServerSocket
have been removed.dart:isolate
spawnUri
added an environment
named argument.dart2js
and Dartium now support improved JavaScript Interoperability via the js package.
docgen
and dartdocgen
no longer ship in the SDK. The docgen
sources 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:html
and 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.
dart:io
Pub
Pub will now respect .gitignore
when validating a package before it's published. For example, if a LICENSE
file 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 get
needs 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.
??
: if null operator. expr1 ?? expr2
evaluates to expr1
if not null
, otherwise expr2
.??=
: null-aware assignment. v ??= expr
causes v
to be assigned expr
only if v
is null
.x?.p
: null-aware access. x?.p
evaluates to x.p
if x
is not null
, otherwise evaluates to null
.x?.m()
: null-aware method invocation. x?.m()
invokes m
only if x
is not null
.dart:async
StreamController
added setters for the onListen
, onPause
, onResume
and onCancel
callbacks.dart:convert
LineSplitter
added a split
static method returning an Iterable
.dart:core
Uri
class 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 added hasAbsolutePath
, hasEmptyPath
, and hasScheme
properties.dart:developer
log
function to transmit logging events to Observatory.dart:html
NodeTreeSanitizer
added the const trusted
field. It can be used instead of defining a NullTreeSanitizer
class when calling setInnerHtml
or other methods that create DOM from text. It is also more efficient, skipping the creation of a DocumentFragment
.dart:io
dart:isolate
onError
, onExit
and errorsAreFatal
parameters to Isolate.spawnUri
.dart:mirrors
InstanceMirror.delegate
moved up to ObjectMirror
.Documentation tools
dartdoc
is now the default tool to generate static HTML for API docs. Learn more.
docgen
and dartdocgen
have 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 get
implicitly 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=error
and --verbosity=warning
.
pub serve
now collapses multiple GET requests into a single line of output. For full output, use --verbose
.
pub deps
has improved formatting for circular dependencies on the entrypoint package.
pub run
and pub global run
Breaking: to match the behavior of the Dart VM, executables no longer run in checked mode by default. A --checked
flag 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, run pub cache repair
.
pub get
and pub upgrade
Pub will now generate a “.packages” file in addition to the “packages” directory when running pub get
or similar operations, per the package spec proposal. Pub now has a --no-package-symlinks
flag that will stop “packages” directories from being generated at all.
An issue where HTTP requests were sometimes made even though --offline
was passed has been fixed.
A bug with --offline
that caused an unhelpful error message has been fixed.
Pub will no longer time out when a package takes a long time to download.
pub publish
Pub will emit a non-zero exit code when it finds a violation while publishing.
.gitignore
files 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 $dart2js
transformer) 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 nonexistent asset in another package will now be re-run if that asset is later created.
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.
WebSocket.close()
would crash if called after WebSocket.cancel()
.pub
executable was run, even if a DART_SDK
environment variable is set.dart:core
Iterable
added an empty
constructor. dcf0286Iterable
can now be extended directly. An alternative to extending IterableBase
from dart:collection
.List
added an unmodifiable
constructor. r45334Map
added an unmodifiable
constructor. r45733int
added a gcd
method. a192ef4int
added a modInverse
method. f6f338cStackTrace
added a fromString
constructor. 68dd6f6Uri
added a directory
constructor. d8dbb4aConcurrentModificationError
as eagerly in release mode. In checked mode, the modification check is still as eager as possible. r45198dart:developer
- NEW
dart:profiler
library.debugger
and inspect
. 6e42aecdart:io
dart:html
Element
methods, appendHtml
and insertAdjacentHtml
now take nodeValidator
and treeSanitizer
parameters, and the inputs are consistently sanitized. r45818 announcementdart:isolate
priority
parameter of Isolate.ping
and Isolate.kill
is now a named parameter named priority
.Isolate.AS_EVENT
priority.Isolate
methods ping
and addOnExitListener
now have a named parameter response
. r45092Isolate.spawnUri
added a named argument checked
.dart:profiler
- DEPRECATED
dart:developer
instead.dart2js --output-type=dart
) utility as part of dart2jsdart:convert
dart:core
Uri.parse
added start
and end
positional arguments.dart:html
CssClassSet
method 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. Announcementdart:io
ProcessResult
now exposes a constructor.import
and Isolate.spawnUri
now supports the Data URI scheme on the VM.Running pub run foo
within a package now runs the foo
executable defined by the foo
package. The previous behavior ran bin/foo
. This makes it easy to run binaries in dependencies, for instance pub run test
.
On Mac and Linux, signals sent to pub run
and forwarded to the child command.
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.source
when the method is on the first line in a script - r44957, r44976
pub: Fix for issue 23084: Pub can fail to load transformers necessary for local development - r44876
Support for async
, await
, sync*
, async*
, yield
, yield*
, and await for
. See the the language tour for more details.
Enum support is fully enabled. See the language tour for more details.
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.
There's a new model for shared server sockets with no need for a Socket
reference.
A new, much faster regular expression engine.
The Isolate API now works across the VM and dart2js
.
For more information on any of these changes, see the corresponding documentation on the Dart API site.
dart:async
:
Future.wait
added a new named argument, cleanUp
, which is a callback that releases resources allocated by a successful Future
.
The SynchronousStreamController
class was added as an explicit name for the type returned when the sync
argument is passed to new StreamController
.
dart:collection
: The new SplayTreeSet.from(Iterable)
constructor was added.
dart:convert
: Utf8Encoder.convert
and Utf8Decoder.convert
added optional start
and end
arguments.
dart:core
:
RangeError
added new static helper functions: checkNotNegative
, checkValidIndex
, checkValidRange
, and checkValueInInterval
.
int
added the modPow
function.
String
added the replaceFirstMapped
and replaceRange
functions.
dart:io
:
Support for locking files to prevent concurrent modification was added. This includes the File.lock
, File.lockSync
, File.unlock
, and File.unlockSync
functions as well as the FileLock
class.
Support for starting detached processes by passing the named mode
argument (a ProcessStartMode
) to Process.start
. A process can be fully attached, fully detached, or detached except for its standard IO streams.
HttpServer.bind
and HttpServer.bindSecure
added the v6Only
named argument. If this is true, only IPv6 connections will be accepted.
HttpServer.bind
, HttpServer.bindSecure
, ServerSocket.bind
, RawServerSocket.bind
, SecureServerSocket.bind
and RawSecureServerSocket.bind
added the shared
named 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 ServerSocketReference
and RawServerSocketReference
classes, as well as getters that returned them, are marked as deprecated. The shared
named argument should be used instead. These will be removed in Dart 1.10.
Socket.connect
and RawSocket.connect
added the sourceAddress
named argument, which specifies the local address to bind when making a connection.
The static Process.killPid
method was added to kill a process with a given PID.
Stdout
added the nonBlocking
instance property, which returns a non-blocking IOSink
that writes to standard output.
dart:isolate
:
The static getter Isolate.current
was added.
The Isolate
methods addOnExitListener
, removeOnExitListener
, setErrorsFatal
, addOnErrorListener
, and removeOnErrorListener
now work on the VM.
Isolates spawned via Isolate.spawn
now allow most objects, including top-level and static functions, to be sent between them.
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 rethrow
was fixed (issue 21795).
Breakpoints can be set in the Editor using file suffixes (issue 21280).
IPv6 addresses are properly handled by HttpClient
in dart:io
, fixing a crash in pub (issue 21698).
Issues with the experimental async
/await
syntax have been fixed.
Issues with a set of number operations in the VM have been fixed.
ListBase
in dart:collection
always returns an Iterable
with the correct type argument.
dart:collection
: SplayTree
added the toSet
function.
dart:convert
: The JsonUtf8Encoder
class was added.
dart:core
:
The IndexError
class was added for errors caused by an index being outside its expected range.
The new RangeError.index
constructor was added. It forwards to new IndexError
.
RangeError
added three new properties. invalidProperty
is the value that caused the error, and start
and end
are the minimum and maximum values that the value is allowed to assume.
new RangeError.value
and new RangeError.range
added an optional message
argument.
The new String.fromCharCodes
constructor added optional start
and end
arguments.
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
, and RawSecureServerSocket.bind
added a supportedProtocols
named argument for protocol negotiation.
RawSecureServerSocket
added a supportedProtocols
field.
RawSecureSocket
and SecureSocket
added a selectedProtocol
field which contains the protocol selected during protocol negotiation.
pub
now generates binstubs for packages that are globally activated so that they can be put on the user's PATH
and used as normal executables. See the pub global activate
documentation.
When using dart2js
, deferred loading now works with multiple Dart apps on the same page.
dart:async
: Zone
, ZoneDelegate
, and ZoneSpecification
added the errorCallback
function, which allows errors that have been programmatically added to a Future
or Stream
to be intercepted.
dart:io
:
Breaking change: HttpClient.close
must 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: HttpServer
no longer compresses all traffic by default. The new autoCompress
property can be set to true
to re-enable compression.
dart:isolate
: Isolate.spawnUri
added the optional packageRoot
argument, which controls how it resolves package:
URIs.