NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
pub.dev · #1 most downloaded on pub.dev
This package provides a library that performs static analysis of Dart code.
Last release 24 days ago
11 Sep 2026
Ships fairly regularly
a new release about every 2 weeks
Nearly every release is documented
notes for 57 of the last 60 stable releases
3 versions withdrawn
withdrawn after publishing
13 years old
389 releases · first in 2013
Updated the current language version to 3.3.
3.3.ConstantEvaluator.Improvements for extension types.
Added InstanceElement, a super-interface for InterfaceElement and ExtensionElement.
One column per quarter.
InstanceElement, a super-interface for InterfaceElement
and ExtensionElement.TypeSystem.greatestLowerBound.Remove deprecated declaredElement2 from AST.
declaredElement2 from AST.element2 from AST.name2 from AST.FunctionBody.isPotentiallyMutatedInClosure.extensionName, staticElement from ExtensionOverride.name from NamedType.InvalidType is now used when types or property cannot be resolved. Previously DynamicType was used.
InvalidType is now used when types or property cannot be resolved.
Previously DynamicType was used.Deprecated DartType.isDynamic, use is DynamicType instead.
DartType.isDynamic, use is DynamicType instead.NamedType to use importPrefix and name2 token.
The deprecated name node is still visited in this version, but will stop
in the next major version.ExtensionOverride to use importPrefix and name token.
The deprecated extensionName node is still visited in this version, but
will stop in the next major version.AnalysisError constructor, use tmp constructor,
with names formal parameters. Theoretically no clients should use either,
but practically there are two uses currently.InvalidType, used when a named type cannot be resolved, or a
property cannot be resolved, etc. Previously DynamicType was used.
In the future DynamicType will be used only when specified explicitly,
or a property is resolved against a dynamic target. The clients should
prepare by checking also for InvalidType in addition to DynamicType.Restore previously published finalKeyword, interfaceKeyword and sealedKeyword of MixinElement. We added them preliminary while working on the class mo
finalKeyword, interfaceKeyword and
sealedKeyword of MixinElement. We added them preliminary while
working on the class modifiers feature, but eventually decided to remove.
See https://github.com/dart-lang/sdk/issues/52159 for details.Deprecated IfStatement.condition, use expression instead.
@experimental from AST nodes and elements for records and patterns.IfStatement.condition, use expression instead.NamedType.importPrefix, NamedType.name2, and NamedType.element.
Deprecated NamedType.name. Currently Identifier is an expression, and
an expression as a name of a type does not make sense. So, instead we model
it as a name token, the Element that it references, and an optional import
library prefix reference.* Added DartType.isDartCoreType.
DartType.isDartCoreType.Deprecated FunctionBody.isPotentiallyMutatedInClosure, not used by clients.
FunctionBody.isPotentiallyMutatedInClosure, not used by clients.FunctionBody.isPotentiallyMutatedInScope and pattern assignment.Deprecated DartType.isVoid, use is VoidType instead.
DartType.isVoid, use is VoidType instead.records, patterns, and class-modifiers features enabled by default.Require SDK >=2.19.0 <3.0.0 to use PathNotFoundException from dart:io.
>=2.19.0 <3.0.0 to use PathNotFoundException from dart:io.Work on class-modifiers feature.
class-modifiers feature.patterns feature.Implemented DartPattern.precedence.
DartPattern.precedence.Rename RecordPatternField to PatternField.
RecordPatternField to PatternField.RecordPatternFieldName to PatternFieldName.* Bug fixes: 50660
Require collection: ^1.17.0 because we use elementAtOrNull.
collection: ^1.17.0 because we use elementAtOrNull.Use 3.0.0 as the current language version.
3.0.0 as the current language version.Deprecated Element.enclosingElement3, use enclosingElement instead.
Element.enclosingElement3, use enclosingElement instead.Directive.element2, use element instead.CatchClause.exceptionParameter2, use exceptionParameter instead.CatchClause.stackTraceParameter2, use stackTraceParameter instead.DartType.element2, use element instead.Element.isAccessibleIn2(), use isAccessibleIn() instead.CompilationUnitElement.enums2, use enums instead.CompilationUnitElement.getEnum2(), use getEnum() instead.CompilationUnitElement.mixins2, use mixins instead.LibraryElement.parts2, use parts instead.ImportElement.imports2, use imports instead.AnalysisDriverForPackageBuild.sdkLibraryUris.buildSdkSummary2(), use buildSdkSummary() instead.Deprecated AstNode.name2, use name instead.
AstNode.name2, use name instead.AstNode.declaredElement2, use declaredElement instead.Removed deprecated methods from AST.
DiagnosticMessage.message.LibraryElement.getImportsWithPrefix().ParameterElement.isNotOptional.DartType.displayName.AnalysisDriver.ClassOrMixinDeclaration.Declaration.declaredElement.Element.enclosingElement and enclosingElement2.ExportElement, ImportElement.NamedCompilationUnitMember.name.Declaration.declaredElement.DartType.element.Add missing addXyz to NodeLintRegistry.
addXyz to NodeLintRegistry.lookUpInheritedConcreteX() to InterfaceElement.Added DartType.element2, so that InterfaceType.element2 overrides it.
DartType.element2, so that InterfaceType.element2 overrides it.Update deprecation message for FormalParameter.identifier.
FormalParameter.identifier.ClassOrMixinDeclaration, use ClassDeclaration and MixinDeclaration directly.Declaration.declaredElement, use declaredElement2 instead.
This is necessary to separate ClassElement, EnumElement, and MixinElement.
And, in the future, augmentations like ClassAugmentationElement, etc.TypeSystem.instantiateToBounds2(), use instantiateInterfaceToBounds() or
instantiateTypeAliasToBounds() instead.Deprecated ClassDeclaration.isAbstract, use abstractKeyword instead.
ClassDeclaration.isAbstract, use abstractKeyword instead.ClassTypeAlias.isAbstract, use abstractKeyword instead.ClassOrMixinDeclaration.getField, filter members instead.ClassOrMixinDeclaration.getMethod, filter members instead.ClassDeclaration.getConstructor, filter members instead.Directive.element, use element2 instead.ClassElement.hasStaticMember, it is not useful for clients.NamespaceDirective.uriElement, use element2.uri with DirectiveUriWithLibrary instead.UriBasedDirective.uriContent, UriBasedDirective.uriElement, UriBasedDirective.uriSource.
Use Directive.element2.uri instead.NamespaceDirective.selectedSource, use element2.uri with DirectiveUriWithSource instead.Configuration.uriSource, use resolvedUri instead.CatchClause.exceptionParameter and CatchClause.stackTraceParameter.
Use exceptionParameter2 and stackTraceParameter2 instead.FileResult.isAugmentation and isLibrary to complement isPart.name2 and declaredElement instead.Element.enclosingElement2, use enclosingElement3 instead. The meaningful change is that
ConstructorElement.enclosingElement3 returns now InterfaceElement, not ClassElement.get enums/mixin, use get enums2/mixins2 instead.DartType.element, check for InterfaceType, TypeParameterType, and then ask the element.ClassElement.isEnum and isMixin. Check for is EnumElement and is MixinElement instead.LibraryElement.getType() use getClass() instead.Fix identifier for LibraryExportElement and LibraryImportElement.
identifier for LibraryExportElement and LibraryImportElement.Deprecated Directive.keyword, use corresponding xyzToken in specific directives.
Directive.keyword, use corresponding xyzToken in specific directives.LibraryElement.parts, use parts2 instead.LibraryElement.exports, use libraryExports instead.LibraryElement.imports, use libraryImports instead.Element.enclosingElement, use enclosingElement2 instead.Member is not equal to ElementImpl, use Element.declaration.Deprecated ImportDirective.COMPARATOR, use appropriate custom logic, if necessary.
>=2.17.0 <3.0.0.ImportDirective.COMPARATOR, use appropriate custom logic, if necessary.Element.isAccessibleIn(), use isAccessibleIn2() instead.Deprecated ParameterElement.isNotOptional, use isRequired instead.
ParameterElement.isNotOptional, use isRequired instead.ResourceProviderMixin.newFile2, use newFile instead.ResourceProviderMixin.newAnalysisOptionsYamlFile2, use newAnalysisOptionsYamlFile instead.DartType.resolveToBound, use TypeSystem.resolveToBound instead.LibraryElement.getImportsWithPrefix, use PrefixElement.imports instead.AnalysisSession.getFile() to return updated content after applyPendingFileChanges.Removed deprecated UriKind and Source.uriKind.
UriKind and Source.uriKind.LibraryElement.hasExtUri.LibraryElement.hasLoadLibraryFunction.ImportElement.prefixOffset.CompilationUnitElement.types.Source.encoding.Source.isInSystemLibrary.Source.modificationStamp.stamp in MemoryResourceProvider.SourceFactory.restoreUri, use pathToUri instead.AnalysisContext.workspace.isNonNullableByDefault parameter in ErrorReporter is now required.Element.SORT_BY_OFFSET, it is not used.AnalysisSession.getFile and getParsedUnit to fail
if there are pending file changes, instead of reading. As for any other
AnalysisSession method, await AnalysisContext.applyPendingFileChanges().Token.copy() and copyComments().CommentToken.remove().astFactory and AstFactory.AnalysisOptions.signature and signaturesEqual.buildSdkSummary().Fixes a bug in the CFE which could manifest as compilation errors of Flutter web apps when compiled with dart2wasm (issue [#55714]).
Breaking Change [#54640][]: The pattern context type schema for cast patterns has been changed from Object? to _ (the unknown type), to align with the…
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:asyncParallelWaitError 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:cliwaitFor is removed in 3.4.dart:ffiStruct.create and Union.create to create struct and union views
of the sequence of bytes stored in a subtype of TypedData.dart:ioBreaking 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_interopFixes 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_dataBREAKING 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.
Resource.parent2, use parent instead.astFactory, clients should not create AST nodes manually.CompilationUnit.lineInfo to be non-nullable.CompilationUnitElement.lineInfo to be non-nullable.ResourceProviderMixin.newFile, use newFile2 instead.ResourceProviderMixin.newAnalysisOptionsYamlFile.AnalysisContext.changeFile and AnalysisContext.applyPendingFileChanges.buildSdkSummary, use asynchronous buildSdkSummary2 instead.Fixes an issue in dart2js where object literal constructors in interop extension types would fail to compile without an @JS annotation on the library
This is a patch release that:
@JS annotation on the
library (issue #55057).await expression, unless the extension type itself implements
Future (issue #55095).Breaking Change [#54056][]: The rules for private field promotion have been changed so that an abstract getter is considered promotable if there are n…
Dart 3.3 adds extension types to the language. To use them, set your
package's [SDK constraint][language version] 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_assertionunnecessary_castinvalid_null_aware_operatorThese 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:coreString.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_interopJSAny 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_unsafehas helper to make hasProperty calls more concise.dart:typed_dataBREAKING 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:nativewrappersbase 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_parametersavoid_returning_null,avoid_returning_null_for_futuregetField to ExtensionElement.isGenerative to ConstructorElement.isDartCoreEnum to ClassElement and DartType.superclass2, mixinTypes2, etc. Use superclass, mixinTypes, etc.enhanced-enums language feature.Breaking Change [#53167][]: Use a more precise split point for refutable patterns. Previously, in an if-case statement, if flow analysis could prove t…
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:asyncbroadcast parameter to Stream.empty constructor.dart:cliwaitFor 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:convertutf8.encode() and Utf8Codec.encode() from
List<int> to Uint8List.dart:developerService.getIsolateID method.getIsolateId method to Service.getObjectId method to Service.dart:ffiNativeCallable.isolateLocal constructor. This creates
NativeCallables 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
NativeCallables 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 closed. Calls
to close after the first are now ignored.dart:ioBreaking 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:isolateIsolate.packageConfigSync and Isolate.resolvePackageUriSync APIs.dart:js_interopJSNumber.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.Symbols and BigInts 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 Objects. See #53106 for more details. Use
dart:js_interop's JSSymbol and JSBigInt with extension types to interop
with these types.Symbols and BigInts 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 Objects. 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.Breaking change [#52027][]: FileSystemEvent is `sealed`. This means that FileSystemEvent cannot be extended or implemented.
dart:asyncinterface 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:coreUri.base on native platforms now respects IOOverrides overriding
current directory (#39796).dart:ffiNativeCallable 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:iosameSite 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_interopObjectLiteral 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:
package:dart_style.MockSdk class.AnalysisDriver constructor.2.17.Breaking change: Dart 3.0 interprets [switch cases] as patterns instead of constant expressions. Most constant expressions found in switch cases are v…
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:
IterableIterableMixin (now alias for Iterable)IterableBase (now alias for Iterable)ListMixinSetMixinMapMixinLinkedListEntryStringConversionSinkdart:coreAdded 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:
ComparableExceptionIteratorPatternMatchRegExpRegExpMatchStackTraceStringSinkNone 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:
MapEntryOutOfMemoryErrorStackOverflowErrorExpandoWeakReferenceFinalizerThe 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:asyncAdded extension member wait on iterables and 2-9 tuples of futures.
Breaking change #49529:
DeferredLibrary class.
Use the deferred as import syntax instead.dart:collectionAdded extension members nonNulls, firstOrNull, lastOrNull,
singleOrNull, elementAtOrNull and indexed on Iterables.
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.
QueueLinkedListLinkedListEntryHasNextIterator (Also deprecated.)HashMapLinkedHashMapHashSetLinkedHashSetDoubleLinkedQueueListQueueSplayTreeMapSplayTreeSetdart:developerBreaking 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:htmlregisterElement
and registerElement2 methods in Document and HtmlDocument have been
removed. See #49536 for
details.dart:mathRandom interface can only be implemented, not extended.dart:ioname 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_utildelete 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_reopenunnecessary_breakstype_literal_in_constant_patterninvalid_case_patternsenable_null_safetyinvariant_booleansprefer_bool_in_assertsprefer_equal_for_default_valuessuper_goes_lastunnecessary_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.
DartType.aliasElement/aliasArguments.FeatureSet.UnitElementResult.signature - unused by clients.AnalysisError.withNamedArguments.ErrorReporter.reportErrorMessage.ResourceProvider.getModificationTimes().MemoryResourceProvider.newDummyLink().MemoryResourceProvider.updateFile().Resource.parent.ResultState and AnalysisResult.state.summary_file_builder library.message and correction from ErrorCode.lookUp methods from InterfaceType.InterfaceType.getSmartLeastUpperBound.path and uri from AnalysisResult.AnalysisSession.TypeName and corresponding methods.TypeProvider.Deprecations and renames for getXyz methods in AnalysisDriver.
getXyz methods in AnalysisDriver.double in mock SDK.path and uri from AnalysisResult.UriResolver.restoreAbsolute, use pathToUri instead.SourceFactory.restoreAbsolute, use pathToUri instead.UriKind and Source.uriKind.Source.modificationStamp.Source.isInSystemLibrary, use uri.isScheme('dart') instead.Breaking change: [Static extension members][] are accessible when imported with a prefix (issue [671][]). In the extension method preview launch, impo…
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:ioIOOverrides.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_finalpub 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.
ConstructorElement.displayName to either Class or Class.constructor.InterfaceType.getSmartLeastUpperBound, use TypeSystem.leastUpperBound instead.MockSdk, use createMockSdk and FolderBasedDartSdk instead.Breaking change #37985: Inference is changed when using Null values in a FutureOr context. Namely, constraints of the forms similar to Null <: FutureO…
[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:developerparent parameter to TimelineTask constructor to allow for
linking of asynchronous timeline events in the DevTools timeline view.dart:ffidart: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:ioenableTimelineLogging 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
Diagnosticables 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 changesAnalysisResult.state, check for specific valid or invalid subtypes.ResultState.LibraryElement.hasExtUri, FFI should be used instead.Breaking change #36900: The following methods and properties across various core libraries, which used to declare a return type of List , were updated…
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.dataFile.readAsBytes() (Future<Uint8List>)File.readAsBytesSync()InternetAddress.rawAddressRandomAccessFile.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>>:
HttpRequestSocketPossible 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<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() → Uint64Listdart:asyncvalue and error constructors on Stream to allow easily creating
single-value or single-error streams.dart:coreUpdate 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:ioBreaking 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_parensDartdoc was updated to 0.28.4; this version includes several fixes and is
based on a newer version of the analyzer package.
Breaking change: Isolate.resolvePackageUri will always throw an UnsupportedError when compiled with dart2js or DDC. This was the only remaining API in…
dart:isolateTransferableTypedData 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:developerresult, errorCode and errorDetail getters in
ServiceExtensionResponse to allow for better debugging of VM service
extension RPC results.dart:ioFixed 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:asyncawait 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_constructorsprefer_initializing_formals to no longer suggest API breaking changesomit_local_variable_types to allow explicit dynamicsunrelated_type_equality_checksunsafe_htmlprefer_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_quotessort_child_properties_lasttype_annotate_public_apis false positive for static const
initializerspub publish will no longer warn about missing dependencies for import
statements in example/.openid scope.ResourceProvider.getModificationTimes().MemoryResourceProvider.newDummyLink().MemoryResourceProvider.updateFile().TypeName, use NamedType instead.AstVisitor.visitNamedType() instead of visitTypeName().ClassTypeAlias.superclass, use superclass2 instead.ConstructorName.type, use type2 instead.ExtendsClause.superclass, use superclass2 instead.ImplementsClause.interfaces, use interfaces2 instead.OnClause.superclassConstraints, use superclassConstraints2 instead.TypeLiteral.typeName, use type instead.WithClause.mixinTypes, use mixinTypes2 instead.AstFactory.typeName(), use namedType() instead.Support for deprecated flags '-c' and '--checked' has been removed.
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:isolatedebugName property to Isolate.debugName optional parameter to Isolate.spawn and
Isolate.spawnUri.dart:coreThe 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 activateing 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.
constructor-tearoffs feature by default in 2.15.Breaking change: The klass getter on the InstanceConstant class in the Kernel AST API has been renamed to classNode for consistency.
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:kernelBreaking 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).
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 mean…
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:asyncstream.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:coreHashMap.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: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.instancedart: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_voidsort_pub_dependenciesprefer_mixinavoid_implementing_value_typesflutter_style_todosavoid_void_asyncprefer_void_to_nulland improvements:
prefer_iterable_whereType.await_only_futuresnull_closuressort_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.AnalysisResult.path to be non-nullable.ParsedLibraryResult.units to be non-nullable.ResolvedLibraryResult.element to be non-nullable.ResolvedLibraryResult.units to be non-nullable.ResolvedUnitResult.content to be non-nullable.ResolvedUnitResult.unit to be non-nullable.AnalysisSession.getXyz2() into getXyz().AnalysisDriver.results to Stream<Object>.
It used to always produce ResolvedUnitResults, but sometimes its
content and unit were null, when the result actually had only errors.
Now it produces either ResolvedUnitResult, or ErrorsResult, or
some other results that might be added in the future.DartType.alias with information about instantiated type alias.
The type alias element and arguments are present or absent together.DartType.aliasElement and DartType.aliasArguments.2.15.The Dart 1.0 syntax is supported but deprecated.
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:asyncStream:
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:cliwaitFor: function that suspends a stack to wait for a Future to complete.dart:collectionMapBase: added mapToString.LinkedHashMap no longer implements HashMapLinkedHashSet 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:convertBase64Codec.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:coreBigInt 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:developerFlow 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.<!-- Still need entries for all changes to dart:html since 1.x -->
dart:htmlquery and queryAll. Use querySelector and
querySelectorAll.dart:ioHttpStatus 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:isolateIsolate.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.<!-- Still need entries for all changes to dart:js since 1.x -->
dart.mathE, LN10, LN, LOG2E, LOG10E, PI, SQRT1_2 and SQRT2 to
e, ln10, ln, log2e, log10e, pi, sqrt1_2 and sqrt2.dart.mirrorsIsolateMirror.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.<!-- Still need entries for all changes to dart:svg since 1.x -->
dart:typed_dataUnmodifiable 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.<!-- Still need entries for all changes to dart:web_audio,web_gl,web_sql since 1.x -->
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.
Scope.lookup2().FunctionTypeAliasElement.LineInfo.getLocation() to return CharacterLocation.LineInfo_Location.AnalysisSession.DartObject.type from ParameterizedType? to DartType?.FunctionType to implement DartType, not ParameterizedType.FunctionType.element and FunctionType.typeArguments.DartObject.type from ParameterizedType? to DartType?.FunctionType to implement DartType, not ParameterizedType.FunctionType.element and FunctionType.typeArguments.StringInterpolation.firstString and lastString, to express
explicitly that there are always (possibly empty) strings as the first
and the last elements of an interpolation.ImportElement.prefixOffset, use prefix.nameOffset instead.CompilationUnitElement.types, use classes instead.Element.nonSynthetic, use it to get the element that caused creation
of this element, e.g. the field for a synthetic getter.FieldElement.isFinal is true only when the field is not synthetic.-1 as nameOffset.defaultValueCode is null for field formal parameters.LibraryElement.name so that it is non-nullable.Nothing published for this version
Nothing published for this version
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…
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.
Deprecated AnalysisDriver default constructor. Added tmp1. The goal is to allow deprecating and removing unused parameters.
AnalysisDriver default constructor. Added tmp1. The goal
is to allow deprecating and removing unused parameters.ConstructorReference, FunctionReference, and
TypeLiteral.Deprecated AnalysisSession.getUnitElement(). Use AnalysisSession.getUnitElement2() instead.
2.14.AnalysisSession.getUnitElement().
Use AnalysisSession.getUnitElement2() instead.AnalysisSession.getResolvedUnit().
Use AnalysisSession.getResolvedUnit2() instead.AnalysisSession.getResolvedLibrary().
Use AnalysisSession.getResolvedLibrary2() instead.AnalysisSession.getResolvedLibraryByElement().
Use AnalysisSession.getResolvedLibraryByElement2() instead.AnalysisSession.getLibraryByUri().
Use AnalysisSession.getLibraryByUri2() instead.AnalysisSession.getErrors().
Use AnalysisSession.getErrors2() instead.AnalysisSession.getParsedLibrary().
Use AnalysisSession.getParsedLibrary2() instead.AnalysisSession.getParsedLibraryByElement().
Use AnalysisSession.getParsedLibraryByElement2() instead.AnalysisSession.getParsedUnit().
Use AnalysisSession.getParsedUnit2() instead.AnalysisSession.getFile() and getSourceKind().
Use AnalysisSession.getFile2() instead.AnalysisSession.getUnitElementSignature().
This method is not used by any known client, and will be removed.Deprecated TypeProvider.nonSubtypableClasses. Use TypeProvider.isNonSubtypableClass instead.
TypeProvider.nonSubtypableClasses.
Use TypeProvider.isNonSubtypableClass instead.sdkPath to AnalysisContextCollection constructor.nonfunction-type-aliases is enabled by default in the
language version 2.13.Added Expression.inConstantContext to API.
Expression.inConstantContext to API.null.CompilationUnitElement.mixins before types.Deprecated all setters in API of AST. Use parseString() instead.
parseString() instead.AnalysisSession.getErrors() does not return null, check its state.aliasElement and aliasArguments for aliases of
InterfaceTypes and TypeParameterTypes.Deprecated TypeProvider.futureType2(), iterableType2(), etc. Use corresponding TypeProvider.futureType(), iterableType(), etc.
TypeProvider.futureType2(), iterableType2(), etc.
Use corresponding TypeProvider.futureType(), iterableType(), etc.Resource.parent2 and deprecated Resource.parent.Folder.isRoot.FolderExtension with withAncestors.ContextRoot.workspace, deprecated AnalysisContext.workspace.ElementVisitor.visitFunctionTypeAliasElement().
Override ElementVisitor.visitTypeAliasElement() instead.FunctionTypeAliasElement. Use TypeAliasElement instead.Updated dependencies to null safe releases.
Deprecated FunctionTypeAliasElement.function. Use TypeAliasElement.aliasedElement instead.
2.12.0.FunctionTypeAliasElement.function.
Use TypeAliasElement.aliasedElement instead.CompilationUnitElement.functionTypeAliases.
Use CompilationUnitElement.typeAliases instead.AnalysisContext.sdkRoot.NullSafetyUnderstandingFlag.functionTypeAliasElement from TypeSystem.instantiateToBounds2.Annotation.typeArguments in preparation for supporting #44838.actualUri from UriResolver.resolveAbsolute.FunctionType.element and FunctionType.typeArguments.Nothing published for this version
Added a new constructor for non-API ErrorCode class. It will be used to migrate existing ErrorCode subclasses, and then deprecated and removed.
PackageBuildWorkspace that supports package:build to stop
at the first directory with pubspec.yaml, and don't try to go up
and find another one with both pubspec.yaml and .dart_tool/build.ErrorCode class. It will be used to
migrate existing ErrorCode subclasses, and then deprecated and removed.Deprecated Scope.lookup2(id), use lookup() instead.
Scope.lookup({id, setter}) with lookup(id).Scope.lookup2(id), use lookup() instead.Member.baseElement.package:analyzer/analyzer.dart library.ElementAnnotation.constantValue.VariableElement.constantValue.VariableElement.initializer.auxiliaryElements.FunctionType.element for types created from a typedef
is now FunctionTypeAliasElement, not its function element.GenericTypeAliasElement.PhysicalResourceProvider.NORMALIZE_EOL_ALWAYS.PhysicalResourceProvider constructor to no longer take a
required positional parameter (removed the existing fileReadMode positional
parameter).Your coding agent can read these notes before it upgrades. Set up the MCP server →