Dart:const变量必须使用常量值初始化 [英] Dart: const variables must be initialized with a constant value

查看:98
本文介绍了Dart:const变量必须使用常量值初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

foo 已经是 const 值时,为什么会出错?

Why there is an error, when the foo is already a const value?

const foo = const [10, 20];
const bar = foo[0] * 2; // error: const variables must be initialized with a constant value. 

推荐答案

这是因为虽然用于创建第二个常量的变量是常量,但您还使用了运算符[] –不是编译时常量.

That's because while the variables used to create your second constant are constants, you also used the operator [] – which is not compile-time constant.

因此,您可以这样做:

const a = 42;
const b = a * 3;

您不能这样做:

const array = [42];
const b = a[0];

这篇关于Dart:const变量必须使用常量值初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆