DartAdvanced 2 min read

Dart private named parameters: initialize private fields cleanly

Use a public named argument to initialize a library-private field without manual forwarding.

On this page

A model can accept a readable named input while keeping its stored representation private. Recent Dart syntax lets an initializing formal refer to that private field directly. The public call-site name omits the underscore.

Worked example

Language requirement: Dart 3.12 or later. This complete example uses browser-supported libraries.

main.dart
// @dart = 3.12
class StockItem {
  StockItem({required this._sku});
  final String _sku;
  String get label => 'Stock: $_sku';
}

void main() {
  final item = StockItem(sku: 'CABLE-1');
  print(item.label);
}

Follow the data and control flow

The constructor declaration refers to _sku, while the caller supplies sku. The instance field is still library-private. This removes a manual initializer forwarding step; it does not change how Dart library privacy or authorization works.

Private named parameters require Dart 3.12 or later. A codebase targeting an older language version can express the same behavior with a public constructor parameter and an initializer list. Choose the form that matches your package support policy.

The source directive selects the required language version when an editor uses an older package default. The compiler must still support that version; a directive does not install a newer SDK.

A mistake to avoid

Writing _sku: at the external call site is not the public parameter spelling. Also avoid assuming that a private stored value is encrypted or hidden from the running application. It is a source-level API boundary, not a secret-management feature.

Practice and verification

Add a second private field and a public derived getter. Move the class into a separate library and verify the public named arguments still work. Add normalization through a factory if the SKU contract requires it instead of mixing implicit validation into a display getter.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.