我想从固定的JSON字符串创建const对象。 这个json字符串来自--dart-define参数。
我正在使用STNAME
California 37253956
Texas 25145561
New York 19378102
Name: CENSUS2010POP, dtype: int64
我已经尝试了下面的代码,但是没有用。编译器抱怨第二个构造函数:
const _APP_CONF = String.fromEnvironment('APP_CONF', defaultValue: '{}');
json参数来自class AuthnProvider {
final String id;
final String clientId;
final List<String> scopes;
const AuthnProvider(
{this.id,
this.clientId,
this.scopes});
const AuthnProvider.fromJson(final Map<String, dynamic> json)
: id = json['id'],
clientId = json['clientId'],
scopes = json['scopes'].cast<String>();
方法。
我还尝试从json映射中创建const和final var,并使用第一个构造函数,但编译器也会出错。
答案 0 :(得分:1)
这是预期的。 const
创建一个编译时常量。 Dart在编译期间不会执行代码,因此无法从const
创建Map
。这就是const
构造函数没有主体的原因,以及为什么没有其他方法可以解决此限制。
您没有在问题中提及这样做的原因,但是如果是出于性能方面的考虑,则差异可以忽略不计。如果是出于不变性,那么我们看到的所有字段都已经final
,因此使对象const
没什么区别。