prefer_ const_ literals_ to_ create_ immutables
Details about the 'prefer_const_literals_to_create_immutables' diagnostic produced by the Dart analyzer.
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 List<int> f;
const C(this.f);
}
C c = C([1]);
Common fixes
#If the context can be made a constant contextConstant contextA region of code where the const keyword is implied and everything within that region must be a constant. Learn more, then do so:
import 'package:meta/meta.dart';
@immutable
class C {
final List<int> f;
const C(this.f);
}
const C c = C([1]);
If the context can't be made a
constant contextConstant contextA region of code where the const keyword is implied and
everything within that region must be a constant.
Learn more
but the constructor can be invoked using const,
then add const before the constructor invocation:
import 'package:meta/meta.dart';
@immutable
class C {
final List<int> f;
const C(this.f);
}
C c = const C([1]);
If the context can't be made a
constant contextConstant contextA region of code where the const keyword is implied and
everything within that region must be a constant.
Learn more
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 List<int> f;
const C(this.f);
}
C c = C(const [1]);
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.