prefer_const_literals_to_create_immutables
Use 'const' literals as arguments to constructors of '@immutable' classes.
Description
#The analyzer produces this diagnostic when a non-const list, map, or set literal is passed as an argument to a constructor declared in a class annotated with @immutable
.
Example
#The following code produces this diagnostic because the list literal ([1]
) is being passed to a constructor in an immutable class but isn't a constant list:
import 'package:meta/meta.dart';
@immutable
class C {
final f;
const C(this.f);
}
C c = C([1]);
Common fixes
#If the context can be made a constant context, then do so:
import 'package:meta/meta.dart';
@immutable
class C {
final f;
const C(this.f);
}
const C c = C([1]);
If the context can't be made a constant context but the constructor can be invoked using const
, then add const
before the constructor invocation:
import 'package:meta/meta.dart';
@immutable
class C {
final f;
const C(this.f);
}
C c = const C([1]);
If the context can't be made a constant context and the constructor can't be invoked using const
, then add the keyword const
before the collection literal:
import 'package:meta/meta.dart';
@immutable
class C {
final f;
const C(this.f);
}
C c = C(const [1]);
Unless stated otherwise, the documentation on this site reflects Dart 3.7.3. Page last updated on 2025-05-08. View source or report an issue.