dtd
A package for communicating with the Dart Tooling Daemon.
4.0.0
6.4M downloads/mo
#105 most downloaded on pub.dev
dart-lang/sdk
What this package is like to depend on
Last release 1 years ago
04 Jun 2025
Release timing varies
gaps range from 8 days to 4 months
Nearly every release is documented
notes for 13 of 13 stable releases
Nothing withdrawn
no release was ever pulled
3 years old
13 releases · first in 2023
0 releases in the last 12 months
see the full history below
Release timeline
13 releases · Dec 2023 to Jun 2025Releases
latest 13-
4.0.004 Jun 2025Release notes
Open source →- Breaking Change: rename
EventParametersconstants toDtdParameters. - Breaking Change: delete the
kFileSystemServiceNameconstant in favor ofFileSystemServiceConstants.serviceName. - Breaking Change: delete the
kUnifiedAnalyticsServiceNameconstant in favor ofUnifiedAnalyticsServiceConstants.serviceName. - Added
CoreDtdServiceConstantsandFileSystemServiceConstantsfor shared use among DTD clients.
- Breaking Change: rename
-
3.0.028 May 2025Release notes
Open source →Language
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, andmixinonclassandmixindeclarations 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 amixindeclaration. 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
continuestatement targets a label that is not a loop (for,doandwhilestatements) or aswitchmember. Fix this by changing thecontinueto 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 (=).
Libraries
General changes
- Breaking Change: Non-
mixinclasses in the platform libraries can no longer be mixed in, unless they are explicitly marked asmixin class. The following existing classes have been made mixin classes:IterableIterableMixin(now alias forIterable)IterableBase(now alias forIterable)ListMixinSetMixinMapMixinLinkedListEntryStringConversionSink
dart:core-
Added
bool.parseandbool.tryParsestatic methods. -
Added
DateTime.timestamp()constructor to get current time as UTC. -
The type of
RegExpMatch.patternis nowRegExp, not justPattern. -
Breaking change #49529:
- Removed the deprecated
Listconstructor, as it wasn't null safe. Use list literals (e.g.[]for an empty list or<int>[]for an empty typed list) orList.filled. - Removed the deprecated
onErrorargument onint.parse,double.parse, andnum.parse. Use thetryParsemethod instead. - Removed the deprecated
proxyandProvisionalannotations. The originalproxyannotation has no effect in Dart 2, and theProvisionaltype andprovisionalconstant were only used internally during the Dart 2.0 development process. - Removed the deprecated
Deprecated.expiresgetter. UseDeprecated.messageinstead. - Removed the deprecated
CastErrorerror. UseTypeErrorinstead. - Removed the deprecated
FallThroughErrorerror. The kind of fall-through previously throwing this error was made a compile-time error in Dart 2.0. - Removed the deprecated
NullThrownErrorerror. This error is never thrown from null safe code. - Removed the deprecated
AbstractClassInstantiationErrorerror. It was made a compile-time error to call the constructor of an abstract class in Dart 2.0. - Removed the deprecated
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. - Removed the deprecated
NoSuchMethodErrordefault constructor. Use theNoSuchMethodError.withInvocationnamed constructor instead. - Removed the deprecated
BidirectionalIteratorclass. Existing bidirectional iterators can still work, they just don't have a shared supertype locking them to a specific name for moving backwards.
- Removed the deprecated
-
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
Functiontype can no longer be implemented, extended or mixed in. Since Dart 2.0 writingimplements Functionhas been allowed for backwards compatibility, but it has not had any effect. In Dart 3.0, theFunctiontype isfinaland cannot be subtyped, preventing code from mistakenly assuming it works. -
The following declarations can only be implemented, not extended:
ComparableExceptionIteratorPatternMatchRegExpRegExpMatchStackTraceStringSink
None of these declarations contained any implementation to inherit, and are marked as
interfaceto signify that they are only intended as interfaces. -
The following declarations can no longer be implemented or extended:
MapEntryOutOfMemoryErrorStackOverflowErrorExpandoWeakReferenceFinalizer
The
MapEntryvalue 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
waiton iterables and 2-9 tuples of futures. -
Breaking change #49529:
- Removed the deprecated
DeferredLibraryclass. Use thedeferred asimport syntax instead.
- Removed the deprecated
dart:collection-
Added extension members
nonNulls,firstOrNull,lastOrNull,singleOrNull,elementAtOrNullandindexedonIterables. Also exported fromdart:core. -
Deprecated the
HasNextIteratorclass (#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.
- The following interface can no longer be extended, only implemented:
Queue
- The following implementation classes can no longer be implemented:
LinkedListLinkedListEntry
- The following implementation classes can no longer be implemented
or extended:
HasNextIterator(Also deprecated.)HashMapLinkedHashMapHashSetLinkedHashSetDoubleLinkedQueueListQueueSplayTreeMapSplayTreeSet
- The following interface can no longer be extended, only implemented:
dart:developer-
Breaking change #49529:
- Removed the deprecated
MAX_USER_TAGSconstant. UsemaxUserTagsinstead.
- Removed the deprecated
-
Callbacks passed to
registerExtensionwill be run in the zone from which they are registered. -
Breaking change #50231:
dart:ffi- The experimental
@FfiNativeannotation is now deprecated. Usages should be replaced with the new@Nativeannotation.
dart:html- Breaking change: As previously announced, the deprecated
registerElementandregisterElement2methods inDocumentandHtmlDocumenthave been removed. See #49536 for details.
dart:math- 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.
- The
Randominterface can only be implemented, not extended.
- The
dart:io- Added
nameandsignalNumberto theProcessSignalclass. - Deprecate
NetworkInterface.listSupported. Has always returned true since Dart 2.3. - Finalize
httpEnableTimelineLoggingparameter name transition fromenabletoenabled. See #43638. - Favor IPv4 connections over IPv6 when connecting sockets. See #50868.
- Breaking change #51035:
- Update
NetworkProfilingto accommodate newStringids that are introduced in vm_service:11.0.0
- Update
dart:js_util- Added several helper functions to access more JavaScript operators, like
deleteand thetypeoffunctionality. jsifyis now permissive and has inverse semantics todartify.jsifyanddartifyboth handle types they understand natively more efficiently.- Signature of
callMethodhas been aligned with the other methods and now takesObjectinstead ofString.
Tools
Observatory
- Observatory is no longer served by default and users should instead use Dart
DevTools. Users requiring specific functionality in Observatory should set
the
--serve-observatoryflag.
Web Dev Compiler (DDC)
- Removed deprecated command line flags
-k,--kernel, and--dart-sdk. - The compile time flag
--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.
dart2js
- The compile time flag
--native-null-assertions, which ensures web library APIs are sound in their nullability, is by default set to true in sound mode, unless-O3or higher is passed, in which case they are not checked. For more information on the flag, see NATIVE_NULL_ASSERTIONS.md.
Dart2js
- Cleanup related to #46100:
the internal dart2js snapshot fails unless it is called from a supported
interface, such as
dart compile js,flutter build, orbuild_web_compilers. This is not expected to be a visible change.
Formatter
- Format
sync*andasync*functions with=>bodies. - Don't split after
<in collection literals. - Better indentation of multiline function types inside type argument lists.
- Fix bug where parameter metadata wouldn't always split when it should.
Analyzer
- Most static analysis "hints" are converted to be "warnings," and any
remaining hints are intended to be converted soon after the Dart 3.0 release.
This means that any (previously) hints reported by
dart analyzeare 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-warningsflag. This behavior can also be altered, on a code-by-code basis, by changing the severity of rules in an analysis options file. - Add static enforcement of the SDK-only
@Sinceannotation. 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. - Protects the Dart Analysis Server against extreme memory usage by limiting the number of plugins per analysis context to 1. (issue [#50981][]).
Linter
Updates the Linter to
1.35.0, which includes changes that- add new lints:
implicit_reopenunnecessary_breakstype_literal_in_constant_patterninvalid_case_patterns
- update existing lints to support patterns and class modifiers
- remove support for:
enable_null_safetyinvariant_booleansprefer_bool_in_assertsprefer_equal_for_default_valuessuper_goes_last
- fix
unnecessary_parenthesisfalse-positives with null-aware expressions. - fix
void_checksto allow assignments ofFuture<dynamic>?to parameters typedFutureOr<void>?. - fix
use_build_context_synchronouslyin if conditions. - fix a false positive for
avoid_private_typedef_functionswith generalized type aliases. - update
unnecessary_parenthesisto detect some doubled parens. - update
void_checksto allow returningNeveras void. - update
no_adjacent_strings_in_listto support set literals and for- and if-elements. - update
avoid_types_as_parameter_namesto handle type variables. - update
avoid_positional_boolean_parametersto handle typedefs. - update
avoid_redundant_argument_valuesto check parameters of redirecting constructors. - improve performance for
prefer_const_literals_to_create_immutables. - update
use_build_context_synchronouslyto check context properties. - improve
unnecessary_parenthesissupport for property accesses and method invocations. - update
unnecessary_parenthesisto allow parentheses in more null-aware cascade contexts. - update
unreachable_from_mainto track static elements. - update
unnecessary_null_checksto not report on arguments passed toFuture.valueorCompleter.complete. - mark
always_use_package_importsandprefer_relative_importsas incompatible rules. - update
only_throw_errorsto not report onNever-typed expressions. - update
unnecessary_lambdasto not report withlate finalvariables. - update
avoid_function_literals_in_foreach_callsto not report with nullable- typed targets. - add new lint:
deprecated_member_use_from_same_packagewhich replaces the soft-deprecated analyzer hint of the same name. - update
public_member_api_docsto not require docs on enum constructors. - update
prefer_void_to_nullto not report on as-expressions.
Migration tool removal
The null safety migration tool (
dart migrate) has been removed. If you still have code which needs to be migrated to null safety, please rundart migrateusing Dart version 2.19, before upgrading to Dart version 3.0.Pub
-
To preserve compatibility with null-safe code pre Dart 3, Pub will interpret a language constraint indicating a language version of
2.12or higher and an upper bound of<3.0.0as<4.0.0.For example
>=2.19.2 <3.0.0will be interpreted as>=2.19.2 <4.0.0. -
dart pub publishwill no longer warn aboutdependency_overrides. Dependency overrides only take effect in the root package of a resolution. -
dart pub token addnow 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 getand related commands will now by default also update the dependencies in theexamplefolder (if it exists). Use--no-exampleto avoid this. -
On Windows the
PUB_CACHEhas moved to%LOCALAPPDATA%, since Dart 2.8 thePUB_CACHEhas been created in%LOCALAPPDATA%when one wasn't present. Hence, this only affects users with aPUB_CACHEcreated by Dart 2.7 or earlier. If you havepath/to/.pub-cache/bininPATHyou may need to update yourPATH.
Release notes
Open source →- Added
ConnectedAppServiceto store the connections to Dart and Flutter applications that DTD is aware of. - Log exceptions from invalid
streamNotifyevents. - Added
getRegisteredServicesAPI. - Added new response types
RegisteredServicesResponseandVmServicesResponse. - Breaking Change: Changed the
serviceNameparameter for theDartToolingDaemon.callmethod to have typeString?instead ofString. - Breaking Change: When the
paramsparameter for theDartToolingDaemon.callmethod is null, pass the null value along to the client peer request instead of sending an empty Map value.
-
-
2.5.116 Apr 2025Release notes
Open source →This is a patch release that prevents type inference failures in the analyzer (Issue 38365).
-
2.5.024 Mar 2025Release notes
Open source →Language
The set of operations allowed in constant expressions has been expanded as described in the constant update proposal. The control flow and spread collection features shipped in Dart 2.3 are now also supported in constants as described in the specification here.
Specifically, it is now valid to use the following operations in constant expressions under the appropriate conditions:
- Casts (
e as T) and type tests (e is T). - Comparisons to
null, even for types which override the==operator. - The
&,|, and^binary operators on booleans. - The spread operators (
...and...?). - An
ifelement in a collection literal.
// Example: these are now valid constants. const Object i = 3; const list = [i as int]; const set = {if (list is List<int>) ...list}; const map = {if (i is int) i : "int"};In addition, the semantics of constant evaluation has been changed as follows:
- The
&&operator only evaluates its second operand if the first evaluates to true. - The
||operator only evaluates its second operand if the first evaluates to false. - The
??operator only evaluates its second operand if the first evaluates to null. - The conditional operator (
e ? e1 : e2) only evaluates one of the two branches, depending on the value of the first operand.
// Example: x is now a valid constant definition. const String s = null; const int x = (s == null) ? 0 : s.length;Core libraries
-
Breaking change #36900: The following methods and properties across various core libraries, which used to declare a return type of
List<int>, were updated to declare a return type ofUint8List:BytesBuilder.takeBytes()BytesBuilder.toBytes()Datagram.dataFile.readAsBytes()(Future<Uint8List>)File.readAsBytesSync()InternetAddress.rawAddressRandomAccessFile.read()(Future<Uint8List>)RandomAccessFile.readSync()RawSocket.read()Utf8Codec.encode()(andUtf8Encoder.convert())
In addition, the following classes were updated to implement
Stream<Uint8List>rather thanStream<List<int>>:HttpRequestSocket
Possible errors and how to fix them
-
The argument type 'Utf8Decoder' can't be assigned to the parameter type 'StreamTransformer<Uint8List, dynamic>'
type 'Utf8Decoder' is not a subtype of type 'StreamTransformer' of 'streamTransformer'"
You can fix these call sites by updating your code to use
StreamTransformer.bind()instead ofStream.transform(), like so:Before:
stream.transform(utf8.decoder)After:utf8.decoder.bind(stream) -
The argument type 'IOSink' can't be assigned to the parameter type 'StreamConsumer<Uint8List>'
type '_IOSinkImpl' is not a subtype of type 'StreamConsumer<Uint8List>' 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()→Int8ListInt16List.sublist()→Int16ListInt32List.sublist()→Int32ListInt64List.sublist()→Int64ListInt32x4List.sublist()→Int32x4ListFloat32List.sublist()→Float32ListFloat64List.sublist()→Float64ListFloat32x4List.sublist()→Float32x4ListFloat64x2List.sublist()→Float64x2ListUint8List.sublist()→Uint8ListUint8ClampedList.sublist()→Uint8ClampedListUint16List.sublist()→Uint16ListUint32List.sublist()→Uint32ListUint64List.sublist()→Uint64List
dart:async- Add
valueanderrorconstructors onStreamto allow easily creating single-value or single-error streams.
dart:core-
Update
Uriclass to support RFC6874: "%25" or "%" can be appended to the end of a valid IPv6 representing a Zone Identifier. A valid zone ID consists of unreversed character or Percent encoded octet, which was defined in RFC3986. IPv6addrz = IPv6address "%25" ZoneID
dart:io-
Breaking change #37192: The
Cookieclass's constructor'snameandvalueoptional positional parameters are now mandatory. The signature changes from:Cookie([String name, String value])to
Cookie(String name, String value)However, it has not been possible to set
nameandvalueto null since Dart 1.3.0 (2014) where a bug made it impossible. Any code not using both parameters or setting any to null would necessarily get a noSuchMethod exception at runtime. This change catches such erroneous uses at compile time. Since code could not previously correctly omit the parameters, this is not really a breaking change. -
Breaking change #37192: The
Cookieclass'snameandvaluesetters now validates that the strings are made from the allowed character set and are not null. The constructor already made these checks and this fixes the loophole where the setters didn't also validate.
Dart VM
Tools
Pub
- Clean-up invalid git repositories in cache when fetching from git.
- Breaking change #36765: Packages published to pub.dev can no longer contain git dependencies. These packages will be rejected by the server.
Linter
The Linter was updated to
0.1.96, which includes:- fixed false positives in
unnecessary_parens - various changes to migrate to preferred analyzer APIs
- rule test fixes
Dartdoc
Dartdoc was updated to
0.28.4; this version includes several fixes and is based on a newer version of the analyzer package.Release notes
Open source →- Update SDK constraints to
^3.5.0. - Add
isClosedgetter toDartToolingDaemon.
- Casts (
-
2.4.011 Nov 2024Release notes
Open source →Core libraries
dart:isolate-
TransferableTypedDataclass was added to facilitate faster cross-isolate communication ofUint8Listdata. -
Breaking change:
Isolate.resolvePackageUriwill always throw anUnsupportedErrorwhen compiled with dart2js or DDC. This was the only remaining API indart:isolatethat didn't automatically throw since we dropped support for this library in Dart 2.0.0. Note that the API already throws in dart2js if the API is used directly without manually setting up adefaultPackagesBasehook.
dart:developer- Exposed
result,errorCodeanderrorDetailgetters inServiceExtensionResponseto allow for better debugging of VM service extension RPC results.
dart:io-
Fixed
Cookieclass interoperability with certain websites by allowing the cookie values to be the empty string (Issue 35804) and not stripping double quotes from the value (Issue 33327) in accordance with RFC 6265. -
#36971: The
HttpClientResponseinterface has been extended with the addition of a newcompressionStategetter, which specifies whether the body of a response was compressed when it was received and whether it has been automatically uncompressed viaHttpClient.autoUncompress.As part of this change, a corresponding new enum was added to
dart:io:HttpClientResponseCompressionState.This is a breaking change for those implementing the
HttpClientResponseinterface as subclasses will need to implement the new getter.
dart:async- Breaking change #36382:
The
await forallowednullas a stream due to a bug inStreamIteratorclass. This bug has now been fixed.
dart:core-
#36171: The
RegExpinterface has been extended with two new constructor named parameters:unicode:(bool, default:false), for Unicode patternsdotAll:(bool, default:false), to change the matching behavior of '.' to also match line terminating characters.
Appropriate properties for these named parameters have also been added so their use can be detected after construction.
In addition,
RegExpmethods that originally returnedMatchobjects now return a more specific subtype,RegExpMatch, which adds two features:Iterable<String> groupNames, a property that contains the names of all named capture groupsString namedGroup(String name), a method that retrieves the match for the given named capture group
This is a breaking change for implementers of the
RegExpinterface. Subclasses will need to add the new properties and may have to update the return types on overridden methods.
Language
- Breaking change #35097: Covariance of type variables used in super-interfaces is now enforced. For example, the following code was previously accepted and will now be rejected:
class A<X> {}; class B<X> extends A<void Function(X)> {};- The identifier
asynccan now be used in asynchronous and generator functions.
Dart for the Web
Dart Dev Compiler (DDC)
- Improve
NoSuchMethoderrors for failing dynamic calls. Now they include specific information about the nature of the error such as:- Attempting to call a null value.
- Calling an object instance with a null
call()method. - Passing too few or too many arguments.
- Passing incorrect named arguments.
- Passing too few or too many type arguments.
- Passing type arguments to a non-generic method.
Tools
Linter
The Linter was updated to
0.1.91, which includes the following changes:- Fixed missed cases in
prefer_const_constructors - Fixed
prefer_initializing_formalsto no longer suggest API breaking changes - Updated
omit_local_variable_typesto allow explicitdynamics - Fixed null-reference in
unrelated_type_equality_checks - New lint:
unsafe_html - Broadened
prefer_null_aware_operatorsto work beyond local variables. - Added
prefer_if_null_operators. - Fixed
prefer_containsfalse positives. - Fixed
unnecessary_parenthesisfalse positives. - Fixed
prefer_asserts_in_initializer_listsfalse positives - Fixed
curly_braces_in_flow_control_structuresto handle more cases - New lint:
prefer_double_quotes - New lint:
sort_child_properties_last - Fixed
type_annotate_public_apisfalse positive forstatic constinitializers
Pub
pub publishwill no longer warn about missing dependencies for import statements inexample/.- OAuth2 authentication will explicitly ask for the
openidscope.
-
-
2.3.017 Jul 2024Release notes
Open source →The focus in this release is on the new "UI-as-code" language features which make collections more expressive and declarative.
Language
Flutter is growing rapidly, which means many Dart users are building UI in code out of big deeply-nested expressions. Our goal with 2.3.0 was to make that kind of code easier to write and maintain. Collection literals are a large component, so we focused on three features to make collections more powerful. We'll use list literals in the examples below, but these features also work in map and set literals.
Spread
Placing
...before an expression inside a collection literal unpacks the result of the expression and inserts its elements directly inside the new collection. Where before you had to write something like this:CupertinoPageScaffold( child: ListView(children: [ Tab2Header() ]..addAll(buildTab2Conversation()) ..add(buildFooter())), );Now you can write this:
CupertinoPageScaffold( child: ListView(children: [ Tab2Header(), ...buildTab2Conversation(), buildFooter() ]), );If you know the expression might evaluate to null and you want to treat that as equivalent to zero elements, you can use the null-aware spread
...?.Collection if
Sometimes you might want to include one or more elements in a collection only under certain conditions. If you're lucky, you can use a
?:operator to selectively swap out a single element, but if you want to exchange more than one or omit elements, you are forced to write imperative code like this:Widget build(BuildContext context) { var children = [ IconButton(icon: Icon(Icons.menu)), Expanded(child: title) ]; if (isAndroid) { children.add(IconButton(icon: Icon(Icons.search))); } return Row(children: children); }We now allow
ifinside collection literals to conditionally omit or (withelse) 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 collectionifcan be composed with spreads to conditionally include or omit multiple items:Widget build(BuildContext context) { return Row( children: [ IconButton(icon: Icon(Icons.menu)), if (isAndroid) ...[ Expanded(child: title), IconButton(icon: Icon(Icons.search)), ] ], ); }Collection for
In many cases, the higher-order methods on Iterable give you a declarative way to modify a collection in the context of a single expression. But some operations, especially involving both transforming and filtering, can be cumbersome to express in a functional style.
To solve this problem, you can use
forinside 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
ifinside const collections.Core library changes
dart:isolate- Added
debugNameproperty toIsolate. - Added
debugNameoptional parameter toIsolate.spawnandIsolate.spawnUri.
dart:core- RegExp patterns can now use lookbehind assertions.
- RegExp patterns can now use named capture groups and named backreferences. Currently, named group matches can only be retrieved in Dart either by the implicit index of the named group or by downcasting the returned Match object to the type RegExpMatch. The RegExpMatch interface contains methods for retrieving the available group names and retrieving a match by group name.
Dart VM
-
The VM service now requires an authentication code by default. This behavior can be disabled by providing the
--disable-service-auth-codesflag. -
Support for deprecated flags '-c' and '--checked' has been removed.
Dart for the Web
dart2js
A binary format was added to dump-info. The old JSON format is still available and provided by default, but we are starting to deprecate it. The new binary format is more compact and cheaper to generate. On some large apps we tested, it was 4x faster to serialize and used 6x less memory.
To use the binary format today, use
--dump-info=binary, instead of--dump-info.What to expect next?
-
The visualizer tool will not be updated to support the new binary format, but you can find several command-line tools at
package:dart2js_infothat provide similar features to those in the visualizer. -
The command-line tools in
package:dart2js_infoalso work with the old JSON format, so you can start using them even before you enable the new format. -
In a future release
--dump-infowill default to--dump-info=binary. At that point, there will be an option to fallback to the JSON format, but the visualizer tool will be deprecated. -
A release after that, the JSON format will no longer be available from dart2js, but may be available from a command-line tool in
package:dart2js_info.
Tools
dartfmt
- Tweak set literal formatting to follow other collection literals.
- Add support for "UI as code" features.
- Properly format trailing commas in assertions.
- Improve indentation of adjacent strings in argument lists.
Linter
The Linter was updated to
0.1.86, which includes the following changes:- Added the following lints:
prefer_inlined_adds,prefer_for_elements_to_map_fromIterable,prefer_if_elements_to_conditional_expressions,diagnostic_describe_all_properties. - Updated
file_namesto skip prefixed-extension Dart files (.css.dart,.g.dart, etc.). - Fixed false positives in
unnecessary_parenthesis.
Pub
- Added a CHANGELOG validator that complains if you
pub publishwithout mentioning the current version. - Removed validation of library names when doing
pub publish. - Added support for
pub global activateing package from a custom pub URL. - Added subcommand:
pub logout. Logs you out of the current session.
Dart native
Initial support for compiling Dart apps to native machine code has been added. Two new tools have been added to the
binfolder 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.
Release notes
Open source →- Indicate compatibility with
package:web_socket_channel2.x and 3.x. - Bump minimum version for
package:unified_analyticsto 6.1.0. DartToolingDaemon.connectwill now wait for the web socket to be connected.- The
DartToolingDaemonconstructor is now public and can be directly called with aStreamChannel<String>. - The
paramsparameter inDartToolingDaemon.call()has been changed fromMap<String, Object>?toMap<String, Object?>?. registerServicenow allows passing aMap<String, Object?>? capabilitiesthat can be supplied to clients via newServiceRegisteredandServiceUregisteredevents on theServicestream (when connected to a version of DTD that supports these streams).- Calling
DartToolingDaemon.onEvent()now returns a broadcast stream. This means multiple listeners can be added, but also means you must add a listener prior to callingstreamListento avoid the possibility of missing events.
- Added
-
2.2.004 Apr 2024Release notes
Open source →Language
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-literalsexperiment flag has been disabled.Tools
Analyzer
-
The
DEPRECATED_MEMBER_USEhint was split into two hints:DEPRECATED_MEMBER_USEreports on usage of@deprecatedmembers declared in a different package.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGEreports on usage of@deprecatedmembers declared in the same package.
Linter
Upgraded the linter to
0.1.82which adds the following improvements:- Added
provide_deprecation_message, anduse_full_hex_values_for_flutter_colors,prefer_null_aware_operators. - Fixed
prefer_const_declarationsset literal false-positives. - Updated
prefer_collection_literalsto support set literals. - Updated
unnecessary_parenthesisplay nicer with cascades. - Removed deprecated lints from the "all options" sample.
- Stopped registering "default lints".
- Fixed
hash_and_equalsto respecthashCodefields.
Other libraries
package:kernel-
Breaking change: The
klassgetter on theInstanceConstantclass in the Kernel AST API has been renamed toclassNodefor consistency. -
Breaking change: Updated
Linkimplementation to utilize true symbolic links instead of junctions on Windows. Existing junctions will continue to work with the newLinkimplementation, but all new links will create symbolic links.To create a symbolic link, Dart must be run with administrative privileges or Developer Mode must be enabled, otherwise a
FileSystemExceptionwill be raised with errno set toERROR_PRIVILEGE_NOT_HELD(Issue 33966).
Release notes
Open source →- Added new response types
Success,StringResponse,BoolResponse, andStringListResponse. - Added contributing guide (
CONTRIBUTING.md).
-
-
2.1.025 Mar 2024Release notes
Open source →This is a minor version release. The team's focus was mostly on improving performance and stability after the large changes in Dart 2.0.0. Notable changes:
-
We've introduced a dedicated syntax for declaring a mixin. Instead of the
classkeyword, it usesmixin:mixin SetMixin<E> implements Set<E> { ... }The new syntax also enables
supercalls inside mixins. -
Integer literals now work in double contexts. When passing a literal number to a function that expects a
double, you no longer need an explicit.0at the end of the number. In releases before 2.1, you need code like this when setting a double likefontSize:TextStyle(fontSize: 18.0)Now you can remove the
.0:TextStyle(fontSize: 18)In releases before 2.1,
fontSize : 18causes a static error. This was a common mistake and source of friction. -
Breaking change: A number of static errors that should have been detected and reported were not supported in 2.0.0. These are reported now, which means existing incorrect code may show new errors.
-
dart:corenow exportsFutureandStream. You no longer need to importdart:asyncto use those very common types.
Language
-
Introduced a new syntax for mixin declarations.
mixin SetMixin<E> implements Set<E> { ... }Most classes that are intended to be used as mixins are intended to only be used as mixins. The library author doesn't want users to be able to construct or subclass the class. The new syntax makes that intent clear and enforces it in the type system. It is an error to extend or construct a type declared using
mixin. (You can implement it since mixins expose an implicit interface.)Over time, we expect most mixin declarations to use the new syntax. However, if you have a "mixin" class where users are extending or constructing it, note that moving it to the new syntax is a breaking API change since it prevents users from doing that. If you have a type like this that is a mixin as well as being a concrete class and/or superclass, then the existing syntax is what you want.
If you need to use a
superinside a mixin, the new syntax is required. This was previously only allowed with the experimental--supermixinsflag because it has some complex interactions with the type system. The new syntax addresses those issues and lets you usesupercalls by declaring the superclass constraint your mixin requires:class Superclass { superclassMethod() { print("in superclass"); } } mixin SomeMixin on Superclass { mixinMethod() { // This is OK: super.superclassMethod(); } } class GoodSub extends Superclass with SomeMixin {} class BadSub extends Object with SomeMixin {} // Error: Since the super() call in mixinMethod() can't find a // superclassMethod() to call, this is prohibited.Even if you don't need to use
supercalls, the new mixin syntax is good because it clearly expresses that you intend the type to be mixed in. -
Allow integer literals to be used in double contexts. An integer literal used in a place where a double is required is now interpreted as a double value. The numerical value of the literal needs to be precisely representable as a double value.
-
Integer literals compiled to JavaScript are now allowed to have any value that can be exactly represented as a JavaScript
Number. They were previously limited to such numbers that were also representable as signed 64-bit integers.
(Breaking) A number of static errors that should have been detected and reported were not supported in 2.0.0. These are reported now, which means existing incorrect code may show new errors:
-
Setters with the same name as the enclosing class aren't allowed. (Issue 34225.) It is not allowed to have a class member with the same name as the enclosing class:
class A { set A(int x) {} }Dart 2.0.0 incorrectly allows this for setters (only). Dart 2.1.0 rejects it.
To fix: This is unlikely to break anything, since it violates all style guides anyway.
-
Constant constructors cannot redirect to non-constant constructors. (Issue 34161.) It is not allowed to have a constant constructor that redirects to a non-constant constructor:
class A { const A.foo() : this(); // Redirecting to A() A() {} }Dart 2.0.0 incorrectly allows this. Dart 2.1.0 rejects it.
To fix: Make the target of the redirection a properly const constructor.
-
Abstract methods may not unsoundly override a concrete method. (Issue 32014.) Concrete methods must be valid implementations of their interfaces:
class A { num get thing => 2.0; } abstract class B implements A { int get thing; } class C extends A with B {} // 'thing' from 'A' is not a valid override of 'thing' from 'B'. main() { print(new C().thing.isEven); // Expects an int but gets a double. }Dart 2.0.0 allows unsound overrides like the above in some cases. Dart 2.1.0 rejects them.
To fix: Relax the type of the invalid override, or tighten the type of the overridden method.
-
Classes can't implement FutureOr. (Issue 33744.) Dart doesn't allow classes to implement the FutureOr type:
class A implements FutureOr<Object> {}Dart 2.0.0 allows classes to implement FutureOr. Dart 2.1.0 does not.
To fix: Don't do this.
-
Type arguments to generic typedefs must satisfy their bounds. (Issue 33308.) If a parameterized typedef specifies a bound, actual arguments must be checked against it:
class A<X extends int> {} typedef F<Y extends int> = A<Y> Function(); F<num> f = null;Dart 2.0.0 allows bounds violations like
F<num>above. Dart 2.1.0 rejects them.To fix: Either remove the bound on the typedef parameter, or pass a valid argument to the typedef.
-
Constructor invocations must use valid syntax, even with optional
new. (Issue 34403.) Type arguments to generic named constructors go after the class name, not the constructor name, even when used without an explicitnew:class A<T> { A.foo() {} } main() { A.foo<String>(); // Incorrect syntax, was accepted in 2.0.0. A<String>.foo(); // Correct syntax. }Dart 2.0.0 accepts the incorrect syntax when the
newkeyword is left out. Dart 2.1.0 correctly rejects this code.To fix: Move the type argument to the correct position after the class name.
-
Instance members should shadow prefixes. (Issue 34498.) If the same name is used as an import prefix and as a class member name, then the class member name takes precedence in the class scope.
import 'dart:core'; import 'dart:core' as core; class A { core.List get core => null; // "core" refers to field, not prefix. }Dart 2.0.0 incorrectly resolves the use of
coreincore.Listto the prefix name. Dart 2.1.0 correctly resolves this to the field name.To fix: Change the prefix name to something which does not clash with the instance member.
-
Implicit type arguments in extends clauses must satisfy the class bounds. (Issue 34532.) Implicit type arguments for generic classes are computed if not passed explicitly, but when used in an
extendsclause they must be checked for validity:class Foo<T> {} class Bar<T extends Foo<T>> {} class Baz extends Bar {} // Should error because Bar completes to Bar<Foo>Dart 2.0.0 accepts the broken code above. Dart 2.1.0 rejects it.
To fix: Provide explicit type arguments to the superclass that satisfy the bound for the superclass.
-
Mixins must correctly override their superclasses. (Issue 34235.) In some rare cases, combinations of uses of mixins could result in invalid overrides not being caught:
class A { num get thing => 2.0; } class M1 { int get thing => 2; } class B = A with M1; class M2 { num get thing => 2.0; } class C extends B with M2 {} // 'thing' from 'M2' not a valid override. main() { M1 a = new C(); print(a.thing.isEven); // Expects an int but gets a double. }Dart 2.0.0 accepts the above example. Dart 2.1.0 rejects it.
To fix: Ensure that overriding methods are correct overrides of their superclasses, either by relaxing the superclass type, or tightening the subclass/mixin type.
Core libraries
dart:async- Fixed a bug where calling
stream.take(0).drain(value)would not correctly forward thevaluethrough the returnedFuture. - Added a
StreamTransformer.fromBindconstructor. - Updated
Stream.fromIterableto send a done event after the error when the iterator'smoveNextthrows, and handle if thecurrentgetter throws (issue 33431).
dart:core- Added
HashMap.fromEntriesandLinkedHashmap.fromEntriesconstructors. - Added
ArgumentError.checkNotNullutility method. - Made
Uriparsing more permissive about[and]occurring in the path, query or fragment, and#occurring in fragment. - Exported
FutureandStreamfromdart:core. - Added operators
&,|and^tobool. - Added missing methods to
UnmodifiableMapMixin. Some maps intended to be unmodifiable incorrectly allowed new methods added in Dart 2 to succeed. - Deprecated the
provisionalannotation and theProvisionalannotation class. These should have been removed before releasing Dart 2.0, and they have no effect.
dart:htmlFixed Service Workers and any Promise/Future API with a Dictionary parameter.
APIs in dart:html (that take a Dictionary) will receive a Dart Map parameter. The Map parameter must be converted to a Dictionary before passing to the browser's API. Before this change, any Promise/Future API with a Map/Dictionary parameter never called the Promise and didn't return a Dart Future - now it does.
This caused a number of breaks especially in Service Workers (register, etc.). Here is a complete list of the fixed APIs:
-
BackgroundFetchManager
Future<BackgroundFetchRegistration> fetch(String id, Object requests, [Map options])
-
CacheStorage
Future match(/*RequestInfo*/ request, [Map options])
-
CanMakePayment
Future<List<Client>> matchAll([Map options])
-
CookieStore
Future getAll([Map options])Future set(String name, String value, [Map options])
-
CredentialsContainer
Future get([Map options])Future create([Map options])
-
ImageCapture
Future setOptions(Map photoSettings)
-
MediaCapabilities
Future<MediaCapabilitiesInfo> decodingInfo(Map configuration)Future<MediaCapabilitiesInfo> encodingInfo(Map configuration)
-
MediaStreamTrack
Future applyConstraints([Map constraints])
-
Navigator
Future requestKeyboardLock([List<String> keyCodes])Future requestMidiAccess([Map options])Future share([Map data])
-
OffscreenCanvas
Future<Blob> convertToBlob([Map options])
-
PaymentInstruments
Future set(String instrumentKey, Map details)
-
Permissions
Future<PermissionStatus> query(Map permission)Future<PermissionStatus> request(Map permissions)Future<PermissionStatus> revoke(Map permission)
-
PushManager
Future permissionState([Map options])Future<PushSubscription> subscribe([Map options])
-
RtcPeerConnection
-
Changed:
Future createAnswer([options_OR_successCallback, RtcPeerConnectionErrorCallback failureCallback, Map mediaConstraints])to:
Future<RtcSessionDescription> createAnswer([Map options]) -
Changed:
Future createOffer([options_OR_successCallback, RtcPeerConnectionErrorCallback failureCallback, Map rtcOfferOptions])to:
Future<RtcSessionDescription> createOffer([Map options]) -
Changed:
Future setLocalDescription(Map description, VoidCallback successCallback, [RtcPeerConnectionErrorCallback failureCallback])to:
Future setLocalDescription(Map description) -
Changed:
Future setLocalDescription(Map description, VoidCallback successCallback, [RtcPeerConnectionErrorCallback failureCallback])to:
Future setRemoteDescription(Map description)
-
-
ServiceWorkerContainer
Future<ServiceWorkerRegistration> register(String url, [Map options])
-
ServiceWorkerRegistration
Future<List<Notification>> getNotifications([Map filter])Future showNotification(String title, [Map options])
-
VRDevice
Future requestSession([Map options])Future supportsSession([Map options])
-
VRSession
Future requestFrameOfReference(String type, [Map options])
-
Window
Future fetch(/*RequestInfo*/ input, [Map init])
-
WorkerGlobalScope
Future fetch(/*RequestInfo*/ input, [Map init])
In addition, exposed Service Worker "self" as a static getter named "instance". The instance is exposed on four different Service Worker classes and can throw a InstanceTypeError if the instance isn't of the class expected (WorkerGlobalScope.instance will always work and not throw):
SharedWorkerGlobalScope.instanceDedicatedWorkerGlobalScope.instanceServiceWorkerGlobalScope.instanceWorkerGlobalScope.instance
dart:io- Added new HTTP status codes.
Dart for the Web
dart2js
-
(Breaking) Duplicate keys in a const map are not allowed and produce a compile-time error. Dart2js used to report this as a warning before. This was already an error in dartanalyzer and DDC and will be an error in other tools in the future as well.
-
Added
-Oflag to tune optimization levels. For more details rundart2js -h -v.We recommend to enable optimizations using the
-Oflag instead of individual flags for each optimization. This is because the-Oflag is intended to be stable and continue to work in future versions of dart2js, while individual flags may come and go.At this time we recommend to test and debug with
-O1and to deploy with-O3.
Tool Changes
dartfmt
- Addressed several dartfmt issues when used with the new CFE parser.
Linter
Bumped the linter to
0.1.70which includes the following new lints:avoid_returning_null_for_voidsort_pub_dependenciesprefer_mixinavoid_implementing_value_typesflutter_style_todosavoid_void_asyncprefer_void_to_null
and improvements:
- Fixed NPE in
prefer_iterable_whereType. - Improved message display for
await_only_futures - Performance improvements for
null_closures - Mixin support
- Updated
sort_constructors_firstto apply to all members. - Updated
unnecessary_thisto work on field initializers. - Updated
unawaited_futuresto ignore assignments within cascades. - Improved handling of constant expressions with generic type params.
- NPE fix for
invariant_booleans. - Improved docs for
unawaited_futures. - Updated
unawaited_futuresto check cascades. - Relaxed
void_checks(allowingT Function()to be assigned tovoid Function()). - Fixed false positives in
lines_longer_than_80_chars.
Pub
- Renamed the
--checkedflag topub runto--enable-asserts. - Pub will no longer delete directories named "packages".
- The
--packages-dirflag is now ignored.
-
-
2.0.020 Mar 2024Release notes
Open source →This is the first major version release of Dart since 1.0.0, so it contains many significant changes across all areas of the platform. Large changes include:
-
(Breaking) The unsound optional static type system has been replaced with a sound static type system using type inference and runtime checks. This was formerly called "strong mode" and only used by the Dart for web products. Now it is the one official static type system for the entire platform and replaces the previous "checked" and "production" modes.
-
(Breaking) Functions marked
asyncnow run synchronously until the firstawaitstatement. Previously, they would return to the event loop once at the top of the function body before any code runs (issue 30345). -
(Breaking) Constants in the core libraries have been renamed from
SCREAMING_CAPStolowerCamelCase. -
(Breaking) Many new methods have been added to core library classes. If you implement the interfaces of these classes, you will need to implement the new methods.
-
(Breaking) "dart:isolate" and "dart:mirrors" are no longer supported when using Dart for the web. They are still supported in the command-line VM.
-
(Breaking) Pub's transformer-based build system has been replaced by a new build system.
-
The
newkeyword is optional and can be omitted. Likewise,constcan be omitted inside a const context (issue 30921). -
Dartium is no longer maintained or supported.
Language
-
"Strong mode" is now the official type system of the language.
-
The
newkeyword is optional and can be omitted. Likewise,constcan be omitted inside a const context. -
A string in a
part ofdeclaration may now be used to refer to the library this file is part of. A library part can now declare its library as either: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
asyncnow run synchronously until the firstawaitstatement. Previously, they would return to the event loop once at the top of the function body before any code runs (issue 30345). -
The type
voidis now a Top type likedynamic, andObject. It also now has new errors for being used where not allowed (such as being assigned to any non-void-typed parameter). Some libraries (importantly, mockito) may need to be updated to accept void values to keep their APIs working. -
Future flattening is now done only as specified in the Dart 2.0 spec, rather than more broadly. This means that the following code has an error on the assignment to
y.test() { Future<int> f; var x = f.then<Future<List<int>>>((x) => []); Future<List<int>> y = x; } -
Invocations of
noSuchMethod()receive default values for optional args. The following program used to print "No arguments passed", and now prints "First argument is 3".abstract class B { void m([int x = 3]); } class A implements B { noSuchMethod(Invocation i) { if (i.positionalArguments.length == 0) { print("No arguments passed"); } else { print("First argument is ${i.positionalArguments[0]}"); } } } void main() { A().m(); } -
Bounds on generic functions are invariant. The following program now issues an invalid override error (issue 29014):
class A { void f<T extends int>() {} } class B extends A { @override void f<T extends num>() {} } -
Numerous corner case bugs around return statements in synchronous and asynchronous functions fixed. Specifically:
-
An empty
return;in an async function with return typeFuture<Object>does not report an error. -
return exp;whereexphas typevoidin an async function is now an error unless the return type of the function isvoidordynamic. -
Mixed return statements of the form
return;andreturn exp;are now allowed whenexphas typevoid. -
A compile time error is emitted for any literal which cannot be exactly represented on the target platform. As a result, dart2js and DDC report errors if an integer literal cannot be represented exactly in JavaScript (issue 33282).
-
New member conflict rules have been implemented. Most cases of conflicting members with the same name are now static errors (issue 33235).
Core libraries
-
Replaced
UPPER_CASEconstant names withlowerCamelCase. For example,HTML_ESCAPEis nowhtmlEscape. -
The Web libraries were re-generated using Chrome 63 WebIDLs (details).
dart:asyncStream:- Added
castandcastFrom. - Changed
firstWhere,lastWhere, andsingleWhereto returnFuture<T>and added an optionalT orElse()callback.
- Added
StreamTransformer: addedcastandcastFrom.StreamTransformerBase: new class.Timer: addedtickproperty.Zone- changed to be strong-mode clean. This required some breaking API changes. See https://goo.gl/y9mW2x for more information.
- Added
bindBinaryCallbackGuarded,bindCallbackGuarded, andbindUnaryCallbackGuarded. - Renamed
Zone.ROOTtoZone.root.
- Removed the deprecated
defaultValueparameter onStream.firstWhereandStream.lastWhere. - Changed an internal lazily-allocated reusable "null future" to always belong to the root zone. This avoids race conditions where the first access to the future determined which zone it would belong to. The zone is only used for scheduling the callback of listeners, the listeners themselves will run in the correct zone in any case. Issue #32556.
dart:cli- New "provisional" library for CLI-specific features.
waitFor: function that suspends a stack to wait for aFutureto complete.
dart:collectionMapBase: addedmapToString.LinkedHashMapno longer implementsHashMapLinkedHashSetno longer implementsHashSet.- Added
ofconstructor toQueue,ListQueue,DoubleLinkedQueue,HashSet,LinkedHashSet,SplayTreeSet,Map,HashMap,LinkedHashMap,SplayTreeMap. - Removed
Mapsclass. ExtendMapBaseor mix inMapMixininstead to provide map method implementations for a class. - Removed experimental
DocumentmethodgetCSSCanvasContextand propertysupportsCssCanvasContext. - Removed obsolete
Elementpropertyxtagno longer supported in browsers. - Exposed
ServiceWorkerclass. - Added constructor to
MessageChannelandMessagePortaddEventListenerautomatically callsstartmethod to receive queued messages.
dart:convertBase64Codec.decodereturn type is nowUint8List.JsonUnsupportedObjectError: addedpartialResultpropertyLineSplitternow implementsStreamTransformer<String, String>instead ofConverter. It retainsConvertermethodsconvertandstartChunkedConversion.Utf8Decoderwhen compiled with dart2js uses the browser'sTextDecoderin some common cases for faster decoding.- Renamed
ASCII,BASE64,BASE64URI,JSON,LATIN1andUTF8toascii,base64,base64Uri,json,latin1andutf8. - Renamed the
HtmlEscapeModeconstantsUNKNOWN,ATTRIBUTE,SQ_ATTRIBUTEandELEMENTtounknown,attribute,sqAttributeandelements. - Added
jsonEncode,jsonDecode,base64Encode,base64UrlEncodeandbase64Decodetop-level functions. - Changed return type of
encodeonAsciiCodecandLatin1Codec, andconvertonAsciiEncoder,Latin1Encoder, toUint8List. - Allow
utf8.decoder.fuse(json.decoder)to ignore leading Unicode BOM.
dart:coreBigIntclass added to support integers greater than 64-bits.- Deprecated the
proxyannotation. - Added
Provisionalclass andprovisionalfield. - Added
pragmaannotation. RegExpadded staticescapefunction.- The
Uriclass now correctly handles paths while running on Node.js on Windows. - Core collection changes:
Iterableadded memberscast,castFrom,followedByandwhereType.Iterable.singleWhereaddedorElseparameter.Listadded+operator,firstandlastsetters, andindexWhereandlastIndexWheremethods, and staticcopyRangeandwriteIterablemethods.MapaddedfromEntriesconstructor.MapaddedaddEntries,cast,entries,map,removeWhere,updateandupdateAllmembers.MapEntry: new class used byMap.entries.- Note: if a class extends
IterableBase,ListBase,SetBaseorMapBase(or uses the corresponding mixins) fromdart:collection, the new members are implemented automatically. - Added
ofconstructor toList,Set,Map.
- Renamed
double.INFINITY,double.NEGATIVE_INFINITY,double.NAN,double.MAX_FINITEanddouble.MIN_POSITIVEtodouble.infinity,double.negativeInfinity,double.nan,double.maxFiniteanddouble.minPositive. - Renamed the following constants in
DateTimeto lower case:MONDAYthroughSUNDAY,DAYS_PER_WEEK(asdaysPerWeek),JANUARYthroughDECEMBERandMONTHS_PER_YEAR(asmonthsPerYear). - Renamed the following constants in
Durationto lower case:MICROSECONDS_PER_MILLISECONDtomicrosecondsPerMillisecond,MILLISECONDS_PER_SECONDtomillisecondsPerSecond,SECONDS_PER_MINUTEtosecondsPerMinute,MINUTES_PER_HOURtominutesPerHour,HOURS_PER_DAYtohoursPerDay,MICROSECONDS_PER_SECONDtomicrosecondsPerSecond,MICROSECONDS_PER_MINUTEtomicrosecondsPerMinute,MICROSECONDS_PER_HOURtomicrosecondsPerHour,MICROSECONDS_PER_DAYtomicrosecondsPerDay,MILLISECONDS_PER_MINUTEtomillisecondsPerMinute,MILLISECONDS_PER_HOURtomillisecondsPerHour,MILLISECONDS_PER_DAYtomillisecondsPerDay,SECONDS_PER_HOURtosecondsPerHour,SECONDS_PER_DAYtosecondsPerDay,MINUTES_PER_DAYtominutesPerDay, andZEROtozero. - Added
typeArgumentstoInvocationclass. - Added constructors to invocation class that allows creation of
Invocationobjects directly, without going throughnoSuchMethod. - Added
unaryMinusandemptyconstant symbols on theSymbolclass. - Changed return type of
UriData.dataAsBytestoUint8List. - Added
tryParsestatic method toint,double,num,BigInt,UriandDateTime. - Deprecated
onErrorparameter onint.parse,double.parseandnum.parse. - Deprecated the
NoSuchMethodErrorconstructor. int.parseon the VM no longer accepts unsigned hexadecimal numbers greater than or equal to2**63when not prefixed by0x. (SDK issue 32858)
dart:developerFlowclass added.Timeline.startSyncandTimeline.timeSyncnow accepts an optional parameterflowof typeFlow. Theflowparameter is used to generate flow timeline events that are enclosed by the slice described byTimeline.{start,finish}SyncandTimeline.timeSync.
<!-- Still need entries for all changes to dart:html since 1.x -->
dart:html- Removed deprecated
queryandqueryAll. UsequerySelectorandquerySelectorAll.
dart:ioHttpStatusaddedUPGRADE_REQUIRED.IOOverridesandHttpOverridesadded to aid in writing tests that wish to mock variosdart:ioobjects.Platform.operatingSystemVersionadded that gives a platform-specific String describing the version of the operating system.ProcessStartMode.INHERIT_STDIOadded, which allows a child process to inherit the parent's stdio handles.RawZLibFilteradded for low-level access to compression and decompression routines.- Unified backends for
SecureSocket,SecurityContext, andX509Certificateto be consistent across all platforms. AllSecureSocket,SecurityContext, andX509Certificateproperties and methods are now supported on iOS and OSX. SecurityContext.alpnSupporteddeprecated as ALPN is now supported on all platforms.SecurityContext: addedwithTrustedRootsnamed optional parameter constructor, which defaults to false.- Added a
timeoutparameter toSocket.connect,RawSocket.connect,SecureSocket.connectandRawSecureSocket.connect. If a connection attempt takes longer than the duration specified intimeout, aSocketExceptionwill be thrown. Note: if the duration specified intimeoutis greater than the OS level timeout, a timeout may occur sooner than specified intimeout. Stdin.hasTerminaladded, which is true if stdin is attached to a terminal.WebSocketadded staticuserAgentproperty.RandomAccessFile.closereturnsFuture<void>- Added
IOOverrides.socketConnect. - Added Dart-styled constants to
ZLibOptions,FileMode,FileLock,FileSystemEntityType,FileSystemEvent,ProcessStartMode,ProcessSignal,InternetAddressType,InternetAddress,SocketDirection,SocketOption,RawSocketEvent, andStdioType, and deprecated the oldSCREAMING_CAPSconstants. - Added the Dart-styled top-level constants
zlib,gzip, andsystemEncoding, and deprecated the oldSCREAMING_CAPStop-level constants. - Removed the top-level
FileModeconstantsREAD,WRITE,APPEND,WRITE_ONLY, andWRITE_ONLY_APPEND. Please use e.g.FileMode.readinstead. - Added
X509Certificate.der,X509Certificate.pem, andX509Certificate.sha1. - Added
FileSystemEntity.fromRawPathconstructor to allow for the creation ofFileSystemEntityusingUint8Listbuffers. - Dart-styled constants have been added for
HttpStatus,HttpHeaders,ContentType,HttpClient,WebSocketStatus,CompressionOptions, andWebSocket. TheSCREAMING_CAPSconstants are marked deprecated. Note thatHttpStatus.CONTINUEis nowHttpStatus.continue_, and that e.g.HttpHeaders.FIELD_NAMEis nowHttpHeaders.fieldNameHeader. - Deprecated
Platform.packageRoot, which is only used forpackages/directory resolution which is no longer supported. It will now always return null, which is a value that was always possible for it to return previously. - Adds
HttpClient.connectionTimeout. - Adds
{Socket,RawSocket,SecureSocket}.startConnect. These return aConnectionTask, which can be used to cancel an in-flight connection attempt.
dart:isolate- Make
Isolate.spawntake a type parameter representing the argument type of the provided function. This allows functions with arguments types other thanObjectin strong mode. - Rename
IMMEDIATEandBEFORE_NEXT_EVENTonIsolatetoimmediateandbeforeNextEvent. - Deprecated
Isolate.packageRoot, which is only used forpackages/directory resolution which is no longer supported. It will now always return null, which is a value that was always possible for it to return previously. - Deprecated
packageRootparameter inIsolate.spawnUri, which is was previously used only forpackages/directory resolution. That style of resolution is no longer supported in Dart 2.
<!-- Still need entries for all changes to dart:js since 1.x -->
dart.math- Renamed
E,LN10,LN,LOG2E,LOG10E,PI,SQRT1_2andSQRT2toe,ln10,ln,log2e,log10e,pi,sqrt1_2andsqrt2.
dart.mirrors- Added
IsolateMirror.loadUri, which allows dynamically loading additional code. - Marked
MirrorsUsedas deprecated. TheMirrorsUsedannotation was only used to inform the dart2js compiler about how mirrors were used, but dart2js no longer supports the mirrors library altogether.
<!-- Still need entries for all changes to dart:svg since 1.x -->
dart:typed_data- Added
Unmodifiableview classes over allListtypes. - Renamed
BYTES_PER_ELEMENTtobytesPerElementon all typed data lists. - Renamed constants
XXXXthroughWWWWonFloat32x4andInt32x4to lower-casexxxxthroughwwww. - Renamed
EndinannesstoEndianand its constants fromBIG_ENDIAN,LITTLE_ENDIANandHOST_ENDIANtolittle,bigandhost.
<!-- Still need entries for all changes to dart:web_audio,web_gl,web_sql since 1.x -->
Dart VM
-
Support for MIPS has been removed.
-
Dart
intis now restricted to 64 bits. On overflow, arithmetic operations wrap around, and integer literals larger than 64 bits are not allowed. See https://github.com/dart-lang/sdk/blob/main/docs/language/informal/int64.md for details. -
The Dart VM no longer attempts to perform
packages/directory resolution (for loading scripts, and inIsolate.resolveUri). Users relying onpackages/directories should switch to.packagesfiles.
Dart for the Web
-
Expose JavaScript Promise APIs using Dart futures. For example,
BackgroundFetchManager.getis defined as:Future<BackgroundFetchRegistration> get(String id)It can be used like:
BackgroundFetchRegistration result = await fetchMgr.get('abc');The underlying JS Promise-to-Future mechanism will be exposed as a public API in the future.
Dart Dev Compiler (DDC)
-
dartdevc will no longer throw an error from
ischecks that return a different result in weak mode (SDK issue 28988). For example:main() { List l = []; // Prints "false", does not throw. print(l is List<String>); } -
Failed
ascasts onIterable<T>,Map<T>,Future<T>, andStream<T>are no longer ignored. These failures were ignored to make it easier to migrate Dart 1 code to strong mode, but ignoring them is a hole in the type system. This closes part of that hole. (We still need to stop ignoring "as" cast failures on function types, and implicit cast failures on the above types and function types.)
dart2js
-
dart2js now compiles programs with Dart 2.0 semantics. Apps are expected to be bigger than before, because Dart 2.0 has many more implicit checks (similar to the
--checkedflag in Dart 1.0).We exposed a
--omit-implicit-checksflag which removes most of the extra implicit checks. Only use this if you have enough test coverage to know that the app will work well without the checks. If a check would have failed and it is omitted, your app may crash or behave in unexpected ways. This flag is similar to--trust-type-annotationsin Dart 1.0. -
dart2js replaced its front-end with the common front-end (CFE). Thanks to the CFE, dart2js errors are more consistent with all other Dart tools.
-
dart2js replaced its source-map implementation. There aren't any big differences, but more data is emitted for synthetic code generated by the compiler.
-
dart:mirrorssupport was removed. Frameworks are encouraged to use code-generation instead. Conditional imports indicate that mirrors are not supported, and any API in the mirrors library will throw at runtime. -
The generated output of dart2js can now be run as a webworker.
-
dart:isolatesupport was removed. To launch background tasks, please use webworkers instead. APIs for webworkers can be accessed fromdart:htmlor JS-interop. -
dart2js no longer supports the
--package-rootflag. This flag was deprecated in favor of--packageslong ago.
Tool Changes
Analyzer
-
The analyzer will no longer issue a warning when a generic type parameter is used as the type in an instance check. For example:
test<T>() { print(3 is T); // No warning } -
New static checking of
@visibleForTestingelements. Accessing a method, function, class, etc. annotated with@visibleForTestingfrom a file not in atest/directory will result in a new hint (issue 28273). -
Static analysis now respects functions annotated with
@alwaysThrows(issue 31384). -
New hints added:
-
NULL_AWARE_BEFORE_OPERATORwhen an operator is used after a null-aware access. For example:x?.a - ''; // HINT -
NULL_AWARE_IN_LOGICAL_OPERATORwhen 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
packagesspecially. Previously they had ignored these directories - and their contents - from the point of view of analysis. Now they'll be treated just as regular directories. This special-casing ofpackagesdirectories was to support using symlinks for package: resolution; that functionality is now handled by.packagesfiles. -
New static checking of duplicate shown or hidden names in an export directive (issue 33182).
-
The analysis server will now only analyze code in Dart 2 mode ('strong mode'). It will emit warnings for analysis options files that have
strong-mode: falseset (and will emit a hint forstrong-mode: true, which is no longer necessary). -
The dartanalyzer
--strongflag is now deprecated and ignored. The command-line analyzer now only analyzes code in strong mode.
dartfmt
-
Support
assert()in const constructor initializer lists. -
Better formatting for multi-line strings in argument lists.
-
Force splitting an empty block as the then body of an if with an else.
-
Support metadata annotations on enum cases.
-
Add
--fixto remove unneedednewandconstkeywords, and change:to=before named parameter default values. -
Change formatting rules around static methods to uniformly format code with and without
newandconst. -
Format expressions inside string interpolation.
Pub
-
Pub has a brand new version solver! It supports all the same features as the old version solver, but it's much less likely to stall out on difficult package graphs, and it's much clearer about why a solution can't be found when version solving fails.
-
Remove support for transformers,
pub build, andpub serve. Use the [new build system][transformers] instead. -
There is now a default SDK constraint of
<2.0.0for any package with no existing upper bound. This allows us to move more safely to 2.0.0. All new packages published on pub will now require an upper bound SDK constraint so future major releases of Dart don't destabilize the package ecosystem.All SDK constraint exclusive upper bounds are now treated as though they allow pre-release versions of that upper bound. For example, the SDK constraint
>=1.8.0 <2.0.0now allows pre-release SDK versions such as2.0.0-beta.3.0. This allows early adopters to try out packages that don't explicitly declare support for the new version yet. You can disable this functionality by setting thePUB_ALLOW_PRERELEASE_SDKenvironment variable tofalse. -
Allow depending on a package in a subdirectory of a Git repository. Git dependencies may now include a
pathparameter, indicating that the package exists in a subdirectory of the Git repository. For example:dependencies: foobar: git: url: git://github.com/dart-lang/multi_package_repo path: pkg/foobar -
Added an
--executablesoption topub depscommand. This will list all available executables that can be run withpub run. -
The Flutter
sdksource will now look for packages influtter/bin/cache/pkg/as well asflutter/packages/. In particular, this means that packages can depend on thesky_enginepackage from thesdksource (issue 1775). -
Pub now caches compiled packages and snapshots in the
.dart_tool/pubdirectory, rather than the.pubdirectory (issue 1795). -
Other bug fixes and improvements.
Release notes
Open source →- Documentation improvements.
- Deprecate use of
DTDConnectionin favor ofDartToolingDaemon.
-
-
1.0.022 Feb 2024Release notes
Open source →- Solidified interface with dart tooling daemon.
- Added FileSystem service interface.
-
0.0.327 Dec 2023 -
0.0.221 Dec 2023 -
0.0.119 Dec 2023