Hrosenthal
Hrosenthal

Reputation: 65

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).

Even in the simplest form copied from the Flutter documentation, I get the same error.

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.

Upvotes: 1

Views: 135

Answers (2)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29783

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];
  }

  ...
}

Upvotes: 0

alireza easazade
alireza easazade

Reputation: 3822

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();
           }
       );
    }

}

Upvotes: 1

Related Questions