Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart typedef and Function Types

Dart typedef and Function Types

typedef is Dart's type alias mechanism; it lets you define short, readable names for complex types.

This chapter introduces two uses of typedef: traditional function type aliases, and the generic type aliases introduced in Dart 3.0.


typedef function type aliases

When a function type is used frequently, typedef can give it a clear name.

This is especially useful for scenarios such as callback functions and event handlers.

Example

// Define a function type alias

// Means: a function that takes two int parameters and returns an int

typedef

IntOperation

=

int

Function

(

int

a

,

int

b

)

;

// Define a callback type

// Means: a function that takes a String message and returns nothing

typedef

MessageCallback

=

void

Function

(

String message

)

;

// Use typedef as a parameter type

int

performOperation

(

int

x

,

int

y

,

IntOperation operation

)

{

 

return

operation

(

x

,

y

)

;

}

void

logMessage

(

String msg

,

MessageCallback callback

)

{

  print

(

'Preparing to output message...'

)

;

  callback

(

'[RUNOOB] $msg'

)

;

}

void

main

(

)

{

 

// Pass a function matching the IntOperation signature

 

int

add

(

int

a

,

int

b

)

=>

a

b

;

 

int

multiply

(

int

a

,

int

b

)

=>

a

b

;

  print

(

'10 + 5 = ${performOperation(10, 5, add)}'

)

;

  print

(

'10 × 5 = ${performOperation(10, 5, multiply)}'

)

;

 

// You can also pass an anonymous function directly

 

int

result

=

performOperation

(

20

,

4

,

(

a

,

b

)

=>

a

~/

b

)

;

  print

(

'20 ÷ 4 = $result'

)

;

 

// Use MessageCallback

  logMessage

(

'Operation complete'

,

(

msg

)

{

    print

(

'Message received: $msg'

)

;

 

}

)

;

}



10 + 5 = 15

10 × 5 = 50

20 ÷ 4 = 5

准备输出消息...

收到消息: [RUNOOB] 操作完成

Without typedef, you need to repeat the lengthy function type signature at every parameter position.

With typedef, type declarations become clear and uniform, and changes only need to be made in one place.

typedef merely gives a type an alias; it does not create a new type. IntOperation and int Function(int, int) are completely equivalent in the type system.


Function types as parameters

In Dart, functions are first-class citizens (First-class Citizen) and can be passed around like ordinary values.

Example

// Declare parameters directly with a function type (without using typedef)

void

processNumbers

(

  List

<

int

numbers

,

bool

Function

(

int

)

filter

,

  String Function

(

int

)

formatter

,

)

{

 

var

filtered

=

numbers.

where

(

filter

)

;

 

for

(

var

n

in

filtered

)

{

    print

(

formatter

(

n

)

)

;

 

}

}

// A higher-order function that returns a function

int

Function

(

int

)

makeMultiplier

(

int

factor

)

{

 

// The returned closure captures factor

 

return

(

int

n

)

=>

n

factor

;

}

void

main

(

)

{

 

var

scores

=

[

55

,

78

,

92

,

60

,

45

,

88

]

;

  print

(

'--- Passing scores ---'

)

;

  processNumbers

(

    scores

,

   

(

n

)

=>

n

=

60

,

                   

// Filter condition

   

(

n

)

=>

'RUNOOB score: $n points'

,

     

// Get current date and time

 

)

;

  print

(

'--- High scores (> 80) ---'

)

;

  processNumbers

(

    scores

,

   

(

n

)

=>

n

80

,

   

(

n

)

=>

'High score: $n points'

,

 

)

;

 

// Function as a return value

 

var

doubler

=

makeMultiplier

(

2

)

;

 

var

tripler

=

makeMultiplier

(

3

)

;

  print

(

'5 × 2 = ${doubler(5)}'

)

;

  print

(

'5 × 3 = ${tripler(5)}'

)

;

}



--- Passing Score ---

RUNOOB 分数: 78 分

RUNOOB 分数: 92 分

RUNOOB 分数: 60 分

RUNOOB 分数: 88 分

--- High score (> 80) ---

高分: 92 分

高分: 88 分

5 × 2 = 10

5 × 3 = 15


Callback pattern

The callback pattern is the most common application scenario for function types.

It gives the caller control over "what to do", making code more flexible and reusable.

Example

// define the callback type

typedef

ResultCallback

<

T

=

void

Function

(

T result

)

;

typedef

ErrorCallback

=

void

Function

(

String error

)

;

// simulate an async operation

void

fetchUserData

(

  String userId

,

{

  required ResultCallback

<

Map

<

String

,

dynamic

onSuccess

,

  required ErrorCallback onError

,

}

)

{

 

// simulate a network request

  print

(

'Fetching user data...'

)

;

 

// simulate success/failure

 

if

(

userId

==

'runoob'

)

{

   

var

data

=

{

     

'id'

:

'runoob'

,

     

'name'

:

'RUNOOB user'

,

     

'level'

:

'VIP'

,

   

}

;

    onSuccess

(

data

)

;

 

}

else

{

    onError

(

'User $userId does not exist'

)

;

 

}

}

void

main

(

)

{

 

// use the callback to handle the result

  fetchUserData

(

   

'runoob'

,

    onSuccess

:

(

data

)

{

      print

(

'Fetch successful!'

)

;

      print

(

'Username: ${data['

name

']}'

)

;

      print

(

'Level: ${data['

level

']}'

)

;

   

}

,

    onError

:

(

error

)

{

      print

(

'Fetch failed: $error'

)

;

   

}

,

 

)

;

  print

(

'---'

)

;

 

// test the failure case

  fetchUserData

(

   

'unknown'

,

    onSuccess

:

(

data

)

{

      print

(

'Fetch successful'

)

;

   

}

,

    onError

:

(

error

)

{

      print

(

'Fetch failed: $error'

)

;

   

}

,

 

)

;

}



正在获取用户数据...

获取成功!

用户名: RUNOOB 用户

等级: VIP

---

正在获取用户数据...

获取失败: 用户 unknown 不存在

Common application scenarios of the callback pattern:

Scenario Callback Type Examples
Network requests onSuccess(data) / onError(error)
UI Events onTap() / onLongPress()
Data Transformation Callbacks in map(), where(), reduce()
Timer Timer(callback, duration)
Animation completion onComplete()

Although the callback pattern is flexible, it leads to "callback hell" when handling multiple layers of asynchronous operations. Dart provides async/await to handle asynchronous flows more elegantly, which we will cover in detail in Chapter 17.


Dart 3.0 Generic Type Aliases

Dart 3.0 extends the capabilities of typedef; now you can create aliases for any type, not just function types.

Example

// Dart 3.0: typedef can create aliases for any type

// aliases for complex collection types

typedef

JsonMap

=

Map

<

String

,

dynamic

;

typedef

UserList

=

List

<

Map

<

String

,

dynamic

;

// generic aliases

typedef

Result

<

T

=

(

{

T data

,

String

?

error

}

)

;

// function type aliases (traditional usage)

typedef

Validator

<

T

=

String

?

Function

(

T value

)

;

// use type aliases

void

processJson

(

JsonMap json

)

{

  print

(

'Processing JSON: $json'

)

;

  print

(

'Number of keys: ${json.length}'

)

;

}

void

validateAndPrint

<

T

(

T value

,

Validator

<

T

validator

)

{

var

error

=

validator

(

value

)

;

 

if

(

error

!=

null

)

{

    print

(

'Validation failed: $error'

)

;

 

}

else

{

    print

(

'Validation passed: $value'

)

;

 

}

}

void

main

(

)

{

 

// use the JsonMap alias

  JsonMap userData

=

{

   

'name'

:

'runoob'

,

   

'age'

:

10

,

   

'isVip'

:

true

,

 

}

;

  processJson

(

userData

)

;

 

// use the Result alias

  Result

<

String

successResult

=

(

data

:

'Operation successful'

,

error

:

null

)

;

  Result

<

String

errorResult

=

(

data

:

''

,

error

:

'Network connection timed out'

)

;

  print

(

'Success: ${successResult.data}'

)

;

  print

(

'Failure: ${errorResult.error}'

)

;

 

// use the generic Validator

  Validator

<

String

nameValidator

=

(

value

)

{

if

(

value.

isEmpty

)

return

'Name cannot be empty'

;

   

if

(

value.

length

<

3

)

return

'Name must be at least 3 characters'

;

   

return

null

;

 

// null means validation passed

 

}

;

  validateAndPrint

(

'RUNOOB'

,

nameValidator

)

;

  validateAndPrint

(

'AB'

,

nameValidator

)

;

}



处理 JSON: {name: runoob, age: 10, isVip: true}

键的数量: 3

成功: 操作成功

失败: 网络连接超时

验证通过: RUNOOB

验证失败: 名称至少 3 个字符

Type aliases in Dart 3.0 greatly reduce verbose type declarations, making code more concise and readable.

A type alias (typedef) and the type itself are completely equivalent at runtime; they are just compile-time "nicknames". This means you cannot use typedef to distinguish two types with the same structure but different semantics--they will be treated as the same type.