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]);
除非另有说明,文档之所提及适用于 Dart 3.7.3 版本,本页面最后更新时间: 2025-05-08。 查看文档源码 或者 报告页面问题。