1

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.

2 Answers 2

1

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

you're welcome. if it worked please choose the answer as the accepted answer
0

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

  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.