Evolving and deprecating APIs

suggest change

Once a package is published, every public class, method and parameter is a promise to its users. This article covers the tools Dart gives you for changing those promises without breaking people by surprise:

The examples were run with Dart 3.13.4. The targeted @Deprecated constructors need sdk: ^3.10.0 in pubspec.yaml. Each example is a library package plus an app that depends on it through a path: dependency. The app is where the warnings show up, because most deprecation diagnostics only fire for code in a different package. A pub workspace works just as well for this setup.

Semantic versioning and breaking changes

Pub packages use semantic versioning. Users depend on a range like geo: ^1.4.0, which pub reads as >=1.4.0 <2.0.0, so dart pub upgrade will pull in any 1.x release automatically. That gives you these rules:

Version bump Example Allowed changes
patch 1.4.0 -> 1.4.1 bug fixes only
minor 1.4.0 -> 1.5.0 new APIs, new deprecations
major 1.4.0 -> 2.0.0 anything, including removals

Before 1.0.0 everything shifts one place to the left: ^0.4.0 means >=0.4.0 <0.5.0, so going from 0.4.x to 0.5.0 is the breaking release.

In Dart, all of these break someone:

That last one surprises people. Here is version 1.1.0 of a cache package that added clear() to two classes:

// cache/lib/cache.dart
class Cache {
  final _data = <String, String>{};
  String? get(String key) => _data[key];
  void put(String key, String value) => _data[key] = value;
  void clear() => _data.clear(); // new in 1.1.0
}

final class LruCache {
  final _data = <String, String>{};
  String? get(String key) => _data[key];
  void put(String key, String value) => _data[key] = value;
  void clear() => _data.clear(); // new in 1.1.0, not breaking
}

An app written against 1.0.0:

// app/bin/main.dart
import 'package:cache/cache.dart';

class MemoryCache implements Cache {
  final _m = <String, String>{};
  @override
  String? get(String key) => _m[key];
  @override
  void put(String key, String value) => _m[key] = value;
}

class MyLru extends LruCache {}
$ dart analyze
  error - bin\main.dart:4:7 - Missing concrete implementation of 'Cache.clear'. Try implementing the missing method, or make the class abstract. - non_abstract_class_inherits_abstract_member
  error - bin\main.dart:12:21 - The class 'LruCache' can't be extended outside of its library because it's a final class. - invalid_use_of_type_outside_library

The minor release broke MemoryCache, because implements copies the interface but none of the code. MyLru was never allowed in the first place: LruCache is final, so nobody outside the library can extend or implement it. That's why adding clear() to it is safe.

Keep room to change with class modifiers

A plain class can be constructed, extended and implemented by anyone. That's the most flexible option for your users and the least flexible for you. Decide up front what you want to support, because adding a modifier later is a breaking change, while removing one is not:

The full table of modifiers is in Inheritance, and Implicit interfaces explains why implementing a class that has private members goes wrong at runtime. A related trick: expose IDs and units as extension types instead of raw int or String. You can add members to them later without changing the run-time representation.

If you already shipped a plain class and want to tighten it, you can't do it in a minor release. Deprecate the use you plan to forbid, then add the modifier in the next major version. That's what the targeted @Deprecated forms are for.

@Deprecated basics

@Deprecated(message) from dart:core marks a declaration as going away. The message should say what to use instead and when the old API will be removed:

// geo/lib/geo.dart
class Circle {
  final double radius;
  Circle(this.radius);

  @Deprecated('Use computeArea() instead. Will be removed in geo 2.0.0.')
  double getArea() => computeArea();

  double computeArea() => 3.14159 * radius * radius;
}

@Deprecated('Use formatNumber() instead. Will be removed in geo 2.0.0.')
String format(double v) => formatNumber(v, precision: 2);

String formatNumber(double v, {required int precision}) =>
    v.toStringAsFixed(precision);

@Deprecated('Use Polygon instead. Will be removed in geo 2.0.0.')
typedef Shape = Polygon;

class Polygon {
  final int sides;
  const Polygon(this.sides);
}

Note the pattern: the old API still exists and forwards to the new one, so existing code keeps working. A deprecated typedef is a cheap way to rename a class: the old name stays valid as an alias. An app still using the old names:

import 'package:geo/geo.dart';

void main() {
  final c = Circle(2);
  print(format(c.getArea()));
  const Shape hex = Shape(6);
  print(hex.sides);
}
$ dart run bin/main.dart
12.57
6
$ dart analyze
   info - bin\main.dart:5:9 - 'format' is deprecated and shouldn't be used. Use formatNumber() instead. Will be removed in geo 2.0.0. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use
   info - bin\main.dart:5:18 - 'getArea' is deprecated and shouldn't be used. Use computeArea() instead. Will be removed in geo 2.0.0. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use
   info - bin\main.dart:6:9 - 'Shape' is deprecated and shouldn't be used. Use Polygon instead. Will be removed in geo 2.0.0. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use
   info - bin\main.dart:6:21 - 'Shape' is deprecated and shouldn't be used. Use Polygon instead. Will be removed in geo 2.0.0. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use

4 issues found.

The code compiles and runs. deprecated_member_use is only an info, so dart analyze still exits with 0 unless you pass --fatal-infos.

The @deprecated constant (lowercase) is Deprecated("next release"), which tells users nothing useful. Enable the provide_deprecation_message lint to catch it:

   info - lib\src\legacy.dart:1:1 - Missing a deprecation message. Try using the constructor to provide a message ('@Deprecated("message")'). - provide_deprecation_message

Annotations and attributes covers @Deprecated next to the other built-in annotations.

Deprecating parameters and libraries

You can deprecate an optional parameter, which is how you rename a named parameter or change its type. Keep both for a while:

// cache/lib/cache.dart (continued)
void connect(String host,
    {@Deprecated('Use timeout instead.') int? timeoutMs, Duration? timeout}) {
  final t = timeout ?? Duration(milliseconds: timeoutMs ?? 5000);
  print('connect $host ($t)');
}

You can also deprecate a whole library, for example an old entry point you're folding into the main one:

// cache/lib/old.dart
@Deprecated('Import package:cache/cache.dart instead.')
library;

export 'cache.dart';
import 'package:cache/cache.dart';
import 'package:cache/old.dart';

void main() {
  connect('db', timeoutMs: 100);
  connect('db', timeout: Duration(seconds: 1));
}
$ dart run bin/main.dart
connect db (0:00:00.100000)
connect db (0:00:01.000000)
$ dart analyze
   info - bin\main.dart:2:1 - 'package:cache/old.dart' is deprecated and shouldn't be used. Import package:cache/cache.dart instead. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use
   info - bin\main.dart:5:17 - 'timeoutMs' is deprecated and shouldn't be used. Use timeout instead. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use

Deprecation isn't inherited. If a superclass deprecates a member, an override in a subclass isn't deprecated, so deprecate it there too if it's going away.

Targeted deprecations (Dart 3.10)

Plain @Deprecated on a class warns about every use of it, which is wrong when you only want to stop people from subclassing it. Dart 3.10 added named constructors that deprecate one capability:

Annotation Warns when other code... Usually followed in the next major by
@Deprecated.extend() extends the class interface class or final class
@Deprecated.implement() implements the class or mixin base class or final class
@Deprecated.subclass() extends or implements it final class
@Deprecated.mixin() mixes in a mixin class dropping mixin from mixin class
@Deprecated.instantiate() calls its constructors abstract class
@Deprecated.optional() omits the argument for an optional parameter making the parameter required

The message is optional for these forms. Here's version 1.4.0 of a shapes package preparing for 2.0.0:

// shapes/lib/shapes.dart
@Deprecated.subclass('Shape will be final in shapes 2.0.0. Use composition.')
class Shape {
  final String name;
  Shape(this.name);
  double area() => 0;
}

@Deprecated.extend('Canvas will become an interface class in 2.0.0.')
class Canvas {
  void draw(Shape s) => print('drawing ${s.name}');
}

@Deprecated.implement('Renderer will become a base class in 2.0.0.')
class Renderer {
  void render() => print('render');
}

@Deprecated.instantiate('Point will become abstract in 2.0.0. Use Point.origin.')
class Point {
  final double x, y;
  Point(this.x, this.y);
  // ignore: deprecated_instantiate
  static final origin = Point(0, 0);
}

@Deprecated.mixin('Logging will stop being a mixin in 2.0.0.')
mixin class Logging {
  void log(String m) => print('[log] $m');
}

String format(double v,
        {@Deprecated.optional('precision will be required in 2.0.0.')
        int precision = 2}) =>
    v.toStringAsFixed(precision);

And an app that uses all of it:

// app/bin/main.dart
import 'package:shapes/shapes.dart';

class Square extends Shape {
  Square() : super('square');
}

class FakeShape implements Shape {
  @override
  String get name => 'fake';
  @override
  double area() => 1;
}

class MyCanvas extends Canvas {}

class MyRenderer implements Renderer {
  @override
  void render() {}
}

class Service with Logging {}

void main() {
  final p = Point(1, 2);
  print(Point.origin.x + p.y);
  print(format(3.14159));
  print(format(3.14159, precision: 3));
  Canvas().draw(Shape('blob')); // plain use: no warnings
}
$ dart analyze
warning - bin\main.dart:4:22 - Subclassing 'Shape' is deprecated. Try removing the 'extends' clause, or removing 'Shape' from the 'implements' clause. - deprecated_subclass
warning - bin\main.dart:8:28 - Subclassing 'Shape' is deprecated. Try removing the 'extends' clause, or removing 'Shape' from the 'implements' clause. - deprecated_subclass
warning - bin\main.dart:15:24 - Extending 'Canvas' is deprecated. Try removing the 'extends' clause. - deprecated_extend
warning - bin\main.dart:17:29 - Implementing 'Renderer' is deprecated. Try removing 'Renderer' from the 'implements' clause. - deprecated_implement
warning - bin\main.dart:22:20 - Mixing in 'Logging' is deprecated. Try removing 'Logging' from the 'with' clause. - deprecated_mixin
warning - bin\main.dart:25:13 - Instantiating 'Point' is deprecated. Try instantiating a non-abstract class. - deprecated_instantiate
warning - bin\main.dart:27:9 - Omitting an argument for the 'precision' parameter is deprecated. Try passing an argument for 'precision'. - deprecated_optional

7 issues found.
$ dart run bin/main.dart
2.0
3.14
3.142
drawing blob

Things to notice:

The analyzer checks that the annotation makes sense. Each of these is flagged:

@Deprecated.extend()
final class Locked {}          // already can't be extended

@Deprecated.implement()
base class B {}                // already can't be implemented

@Deprecated.instantiate()
abstract class Abs {}          // already can't be instantiated

@Deprecated.mixin()
class NotMixin {}              // not a mixin class

@Deprecated.optional()
void f({required int x}) {}    // not optional
warning - bin\c.dart:1:2 - The annotation '@Deprecated.extend' can only be applied to extendable classes. Try removing the '@Deprecated.extend' annotation. - invalid_deprecated_extend_annotation
warning - bin\c.dart:4:2 - The annotation '@Deprecated.implement' can only be applied to implementable classes. Try removing the '@Deprecated.implement' annotation. - invalid_deprecated_implement_annotation
warning - bin\c.dart:7:2 - The annotation '@Deprecated.instantiate' can only be applied to classes. Try removing the '@Deprecated.instantiate' annotation. - invalid_deprecated_instantiate_annotation
warning - bin\c.dart:10:2 - The annotation '@Deprecated.mixin' can only be applied to classes. Try removing the '@Deprecated.mixin' annotation. - invalid_deprecated_mixin_annotation
warning - bin\c.dart:13:2 - The annotation '@Deprecated.optional' can only be applied to optional parameters. Try removing the '@Deprecated.optional' annotation. - invalid_deprecated_optional_annotation

Experimental APIs with @experimental

Sometimes you want to ship an API that isn't stable yet, inside a stable package. @experimental from package:meta marks it as exempt from semver: it may change or disappear in any release.

# kit/pubspec.yaml
dependencies:
  meta: ^1.17.0
// kit/lib/kit.dart
import 'package:meta/meta.dart';

class Client {
  String get(String path) => 'GET $path';

  /// Streaming responses. The API may change in a minor release.
  @experimental
  Stream<String> stream(String path) async* {
    yield 'chunk 1 of $path';
    yield 'chunk 2 of $path';
  }
}

@experimental
enum Protocol { http1, http2, http3 }

String describe() => Protocol.values.join(','); // same package: no warning
import 'package:kit/kit.dart';

Future<void> main() async {
  final c = Client();
  print(c.get('/a'));
  await for (final chunk in c.stream('/b')) {
    print(chunk);
  }
  // ignore: experimental_member_use
  print(Protocol.http3);
}
$ dart analyze
warning - bin\main.dart:6:31 - 'stream' is experimental and could be removed or changed at any time. - experimental_member_use

1 issue found.
$ dart run bin/main.dart
GET /a
chunk 1 of /b
chunk 2 of /b
Protocol.http3

Since Dart 3.10 the analyzer reports experimental_member_use as a warning, so users opt in on purpose with an // ignore: comment or by changing its severity. When the API is stable, remove the annotation in a minor release.

Controlling severity in analysis_options.yaml

App authors can tune how loud deprecations are. This makes deprecated_member_use a warning, so CI fails until the code is migrated:

# app/analysis_options.yaml
analyzer:
  errors:
    deprecated_member_use: warning
$ dart analyze
warning - bin\main.dart:2:1 - 'package:cache/old.dart' is deprecated and shouldn't be used. Import package:cache/cache.dart instead. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use
warning - bin\main.dart:5:17 - 'timeoutMs' is deprecated and shouldn't be used. Use timeout instead. Try replacing the use of the deprecated member with the replacement. - deprecated_member_use

2 issues found.

Going the other way, deprecated_subclass: info or experimental_member_use: ignore keeps a build green while you migrate.

Lints for package authors

Two lints help inside your own package:

# geo/analysis_options.yaml
linter:
  rules:
    - deprecated_member_use_from_same_package
    - remove_deprecations_in_breaking_versions

deprecated_member_use_from_same_package reports uses of your own deprecated APIs, which deprecated_member_use ignores. It's how you find the places in your package, its examples and tests that still call the old API.

remove_deprecations_in_breaking_versions reminds you to delete deprecated declarations when you bump to a breaking version. It reads version: from pubspec.yaml. With this file and version: 2.0.0:

@Deprecated('Use newApi')
void oldApi() {}

class C {
  @deprecated
  int get x => 1;
}
$ dart analyze
   info - lib\t1.dart:1:2 - Remove deprecated elements in breaking versions. Try removing the deprecated element. - remove_deprecations_in_breaking_versions
   info - lib\t1.dart:5:4 - Remove deprecated elements in breaking versions. Try removing the deprecated element. - remove_deprecations_in_breaking_versions

Trying different versions on the same file:

version: Reported?
1.5.0 no
2.0.0-dev.1 yes
2.0.0 yes
2.0.1 no
3.0.0 yes
0.4.0 yes (breaking for 0.x)
0.4.3 no

The lint needs a resolved package: run dart pub get first, or it silently reports nothing.

Automatic migrations with fix_data.yaml

Deprecation tells users what to change. A data-driven fix changes it for them. Put a fix_data.yaml file in your package's lib/ directory, describing each change:

# geo/lib/fix_data.yaml
version: 1
transforms:
  - title: 'Rename to computeArea'
    date: 2026-10-01
    element:
      uris: ['package:geo/geo.dart']
      method: 'getArea'
      inClass: 'Circle'
    changes:
      - kind: 'rename'
        newName: 'computeArea'

  - title: 'Migrate to formatNumber'
    date: 2026-10-01
    element:
      uris: ['package:geo/geo.dart']
      function: 'format'
    changes:
      - kind: 'rename'
        newName: 'formatNumber'
      - kind: 'addParameter'
        index: 1
        name: 'precision'
        style: required_named
        argumentValue:
          expression: '2'

  - title: 'Rename to Polygon'
    date: 2026-10-01
    element:
      uris: ['package:geo/geo.dart']
      typedef: 'Shape'
    changes:
      - kind: 'rename'
        newName: 'Polygon'

Each transform names an element (by kind: class, method, function, getter, constructor, typedef, field and so on, plus the library uris that export it) and a list of changes. Other change kinds include renameParameter, removeParameter, changeParameterType, addTypeParameter and replacedBy.

Users of geo 1.5.0 now get fixes in their IDE (as quick fixes) and from the command line:

$ dart fix --dry-run
Computing fixes in app (dry run)...

4 proposed fixes in 1 file.

bin\main.dart
  deprecated_member_use - 4 fixes

To fix an individual diagnostic, run one of:
  dart fix --apply --code=deprecated_member_use

To fix all diagnostics, run:
  dart fix --apply
$ dart fix --apply
Computing fixes in app...
Applying fixes...

bin\main.dart
  deprecated_member_use - 4 fixes

4 fixes made in 1 file.

The app's main after the fix:

import 'package:geo/geo.dart';

void main() {
  final c = Circle(2);
  print(formatNumber(c.computeArea(), precision: 2));
  const Polygon hex = Polygon(6);
  print(hex.sides);
}

The fixes also work after the old API is gone. If a user jumps straight from 1.4 to 2.0.0, where getArea, format and Shape were deleted but fix_data.yaml was kept, dart analyze shows errors (undefined_method, undefined_class, undefined_function) and dart fix --apply repairs them the same way:

$ dart fix --apply
Computing fixes in app...
Applying fixes...

bin\main.dart
  undefined_class - 1 fix
  undefined_function - 2 fixes
  undefined_method - 1 fix

4 fixes made in 1 file.

So keep transforms in fix_data.yaml after you remove the old API, at least for one major version.

Testing your fixes

dart fix --compare-to-golden applies fixes to every .dart file in a directory and compares the result with a matching .dart.expect file. The convention is a test_fixes/ directory in the package:

geo/
  analysis_options.yaml       # excludes test_fixes/**
  lib/
    geo.dart
    fix_data.yaml
  test_fixes/
    analysis_options.yaml     # enables deprecated_member_use_from_same_package
    geo.dart
    geo.dart.expect
// test_fixes/geo.dart
import 'package:geo/geo.dart';

void main() {
  print(format(Circle(1).getArea()));
  const Shape s = Shape(3);
  print(s);
}
// test_fixes/geo.dart.expect
import 'package:geo/geo.dart';

void main() {
  print(formatNumber(Circle(1).computeArea(), precision: 2));
  const Polygon s = Polygon(3);
  print(s);
}

The test files are in the same package as the deprecated API, so deprecated_member_use doesn't fire, and without a diagnostic there is nothing to fix. That's what test_fixes/analysis_options.yaml is for:

# geo/test_fixes/analysis_options.yaml
linter:
  rules:
    - deprecated_member_use_from_same_package

Without it the test fails with Actual (original code was unchanged). In the package's top-level analysis_options.yaml, exclude the directory so its deliberate deprecated uses don't show up in dart analyze:

# geo/analysis_options.yaml
analyzer:
  exclude:
    - test_fixes/**
$ dart fix --compare-to-golden test_fixes
Computing fixes in test_fixes...
Passed: 1, Failed: 0

The command exits with 1 on a mismatch, so you can run it in CI next to dart test.

A deprecation checklist

For each breaking change you plan:

  1. In a minor release (1.5.0), add the replacement API, make the old one forward to it, and mark the old one @Deprecated(...) or with a targeted form. Say what to use and in which version it goes away.
  2. Add a transform to lib/fix_data.yaml and a case to test_fixes/.
  3. Update the changelog with the migration steps, and mention dart fix --apply.
  4. Fix your own code, examples and tests, with deprecated_member_use_from_same_package enabled.
  5. In the next major release (2.0.0), let remove_deprecations_in_breaking_versions find what to delete. Remove the old APIs, add the class modifiers you announced, and keep the fix_data.yaml transforms.

Users then run dart pub upgrade --major-versions and dart fix --apply.

If your team has project-specific rules that the built-in lints don't cover, such as "never call this internal API from outside lib/src", you can enforce them with an analyzer plugin. That's covered in the article "Writing custom lint rules with analyzer plugins".

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents