Use static variable in function()

后端 未结 4 2059
谎友^
谎友^ 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条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 14:51

    You can use a function object to maintain state:

    library test;
    
    class Test implements Function {
      var status = 0;
      static var static_status = 10;
    
      call() {
        print('Status: $status');
        print('Static status: $static_status');
        status++;
        static_status++;
      }
    }
    
    void main() {
      var fun = new Test();
    
      fun();
      fun();
      fun();
    
      var fun2 = new Test();
    
      fun2();
      fun2();
      fun2();
    }
    

    Output:

    Status: 0
    Static status: 10
    Status: 1
    Static status: 11
    Status: 2
    Static status: 12
    Status: 0
    Static status: 13
    Status: 1
    Static status: 14
    Status: 2
    Static status: 15
    

提交回复
热议问题