[英]Why does Flutter report error when accessing list element?
I'm receiving a syntax error from Android Studio when creating a list in Flutter (Dart).在 Flutter (Dart) 中创建列表时,我收到来自 Android Studio 的语法错误。
Even in the simplest form copied from the Flutter documentation, I get the same error.即使是从 Flutter 文档中复制的最简单的形式,我也会遇到同样的错误。
the code:编码:
var simonSequence = new List<int>(3);
var c = simonSequence[0]; //error here
final anEmptyListOfDouble = <int>[];
anEmptyListOfDouble[0]=0; //also error here
give an error on the line that accesses the list element.在访问列表元素的行上给出错误。
any suggestions are appreciated.任何建议表示赞赏。
because you are writing the code inside the class scope, while you must be writing it in a function.因为您在类范围内编写代码,而您必须在函数中编写它。
this is what you are doing这就是你在做什么
class _SimonState extends State<Simon>{
//other codes
var simonSequence = new List<int>(3);
var c = simonSequence[0]; //error
final anEmptyListOfDouble = <int>[];
anEmptyListOfDouble[0]=0; //error
}
this is what your code SHOULD be like这就是你的代码应该是什么样子
class _SimonState extends State<Simon>{
//other codes
//some function you want your code to be called from
void anyFunction(){
var simonSequence = new List<int>(3);
var c = simonSequence[0]; //error
final anEmptyListOfDouble = <int>[];
anEmptyListOfDouble[0]=0; //error
}
@override
Widget build(BuildContext context) {
//then you will call your function anywhere you need like here
//for example
return RaisedButton(
onPressed:(){
anyFunction();
}
);
}
}
It simply because you're trying to access the declared variable within the class scope.这仅仅是因为您试图访问类范围内的声明变量。 It's marked as error because it's not a declaration for a variable.它被标记为错误,因为它不是变量的声明。 See the following code and its comment for details:有关详细信息,请参阅以下代码及其注释:
class _SimonState extends State<Simon>{
// Here you can only declare your variables.
// Or declaring a method.
var simonSequence = new List<int>(3);
var c = simonSequence[0]; // Error! This is not a variable declaration.
final anEmptyListOfDouble = <int>[];
anEmptyListOfDouble[0]=0; // Error! This is not a variable declaration.
...
void anotherMethod() {
...
// Correct, your accessing the variable here.
var c = simonSequence[0];
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.