簡體   English   中英

為什么 Flutter 訪問列表元素會報錯?

[英]Why does Flutter report error when accessing list element?

在 Flutter (Dart) 中創建列表時,我收到來自 Android Studio 的語法錯誤。

即使是從 Flutter 文檔中復制的最簡單的形式,我也會遇到同樣的錯誤。

編碼:

  var simonSequence = new List<int>(3);
  var c = simonSequence[0];  //error here 

  final anEmptyListOfDouble = <int>[];
  anEmptyListOfDouble[0]=0; //also error here

在訪問列表元素的行上給出錯誤。

任何建議表示贊賞。

因為您在類范圍內編寫代碼,而您必須在函數中編寫它。

這就是你在做什么

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

}

這就是你的代碼應該是什么樣子

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

}

這僅僅是因為您試圖訪問類范圍內的聲明變量。 它被標記為錯誤,因為它不是變量的聲明。 有關詳細信息,請參閱以下代碼及其注釋:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM