Use static variable in function()

后端 未结 4 2047
谎友^
谎友^ 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:34

    You can't use static in a function.

    Global variables in Dart are no code smell because they are only library global.
    Global variables in JavaScript are ugly because they can conflict with global variables from 3rd-party libraries.
    This doesn't happen in Dart.

    As you can make a library in Dart as small as you want (for example only one variable) and you have something similar to a namespace for a library when you import it like

    import 'my_globals.dart' as gl;
    

    and then use it like

    print(gl.myGlobalValue);
    

    this is no code smell.

    You could also create a class to simulate a namespace like

    class MyGlobals {
      static myVal = 12345;
    }
    

    But library global variables are preferred in Dart instead of classes which contain only static variables or functions.

提交回复
热议问题