What is a typedef in Dart?

后端 未结 5 1601
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 15:34

I have read the description, and I understand that it is a function-type alias.

  • A typedef, or function-type alias, gives a function type a name that you can

5条回答
  •  抹茶落季
    2020-12-04 15:59

    A common usage pattern of typedef in Dart is defining a callback interface. For example:

    typedef void LoggerOutputFunction(String msg);
    
    class Logger {
      LoggerOutputFunction out;
      Logger() {
        out = print;
      }
      void log(String msg) {
        out(msg);
      }
    }
    
    void timestampLoggerOutputFunction(String msg) {
      String timeStamp = new Date.now().toString();
      print('${timeStamp}: $msg');
    }
    
    void main() {
      Logger l = new Logger();
      l.log('Hello World');
      l.out = timestampLoggerOutputFunction;
      l.log('Hello World');
    }
    

    Running the above sample yields the following output:

    Hello World
    2012-09-22 10:19:15.139: Hello World

    The typedef line says that LoggerOutputFunction takes a String parameter and returns void.

    timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.

    Let me know if you need another example.

提交回复
热议问题