Use static variable in function()

后端 未结 4 2060
谎友^
谎友^ 2021-01-12 14:11

I would know if we can declare a static var in a function, as we can do in JavaScript.

When I callback my function, my variable keep her last affectation.

Or

4条回答
  •  猫巷女王i
    2021-01-12 14:48

    You can use only global variables.

    Also you may solve this via private variables with "mangling" names.

    void main() {
      myFunction();
      myFunction();
      myFunction();
    }
    
    int _myFunction$count = 0;
    
    void myFunction() {
      print(_myFunction$count++);
    }
    

    This does not helps a lot but you can consider that variable with name "_myFunction$count" is a local static variable "count" in function "myFunction".

    The same as this pseudo code.

    void myFunction() {
      static int count = 0;
      print(count++);
    }
    

提交回复
热议问题