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

Dart Interfaces and Mixins

Dart Interfaces and Mixins

Although Dart only supports single inheritance, interfaces and Mixins allow flexible multiple code reuse.

This chapter introduces how to implement interfaces with implements, code reuse with mixin, and the with keyword.


Implementing Interfaces with implements

In Dart, every class implicitly defines an interface.

Using the implements keyword lets a class implement another class's interface, and it can implement multiple interfaces.

Example

// Define a "printable" interface

class

Printable

{

 

// Methods in the interface have no default implementation

 

// The implementer must override all members

 

void

printContent

(

)

{

   

// This method body is ignored when using implements

 

}

}

// Define a "savable" interface

class

Savable

{

 

void

save

(

)

{

}

}

// Use implements to implement multiple interfaces

class

Document

implements

Printable

,

Savable

{

  String title

;

  String content

;

  Document

(

this

.

title

,

this

.

content

)

;

 

// Must implement all methods required by the Printable interface

  @override

 

void

printContent

(

)

{

    print

(

'--- Document: $title ---'

)

;

    print

(

content

)

;

    print

(

'--- RUNOOB Print Finished ---'

)

;

 

}

 

// Must implement all methods required by the Savable interface

  @override

 

void

save

(

)

{

    print

(

'Document "$title" has been saved to disk'

)

;

 

}

}

void

main

(

)

{

 

var

doc

=

Document

(

'Dart Tutorial'

,

'This is a Dart beginner's guide'

)

;

 

// Polymorphism: Document is both Printable and Savable

  Printable printable

=

doc

;

  printable.

printContent

(

)

;

  Savable savable

=

doc

;

  savable.

save

(

)

;

}



--- Document: Dart Tutorial ---

这是一份 Dart 入门指南

--- RUNOOB print finished ---

文档 "Dart 教程" 已保存到磁盘

The key difference between implements and extends: extends inherits all implementations (method bodies) from the parent class, whereas implements only inherits the interface signature and you must re-implement all methods. In addition, extends can inherit only one class, while implements can implement multiple interfaces.

extends vs implements Comparison

Feature extends implements
No limit on quantity Can inherit only one Can implement multiple
Method implementation Inherits the parent class's implementation Must implement all methods yourself
constructor Can call super() Does not inherit constructors
Use Cases An "is-a" relationship A "can-do" contract

Implementing Multiple Interfaces

Dart can implement multiple interfaces, which is the main way to break through the single-inheritance limitation.

Example

// Define multiple behavior interfaces

class

Flyable

{

 

void

fly

(

)

{

}

}

class

Swimmable

{

 

void

swim

(

)

{

}

}

class

Walkable

{

 

void

walk

(

)

{

}

}

// A duck can fly, swim, and walk

class

Duck

implements

Flyable

,

Swimmable

,

Walkable

{

  String name

;

  Duck

(

this

.

name

)

;

  @override

 

void

fly

(

)

{

    print

(

'$name is flying in the sky'

)

;

 

}

  @override

 

void

swim

(

)

{

    print

(

'$name is swimming on the water'

)

;

 

}

  @override

 

void

walk

(

)

{

    print

(

'$name is waddling on land'

)

;

 

}

}

// A fish can only swim

class

Fish

implements

Swimmable

{

  @override

 

void

swim

(

)

{

    print

(

'The fish is swimming in the water'

)

;

 

}

}

void

main

(

)

{

 

var

duck

=

Duck

(

'RUNOOB Duck'

)

;

 

// The duck can play multiple roles

 

(

duck

as

Flyable

)

.

fly

(

)

;

 

(

duck

as

Swimmable

)

.

swim

(

)

;

 

(

duck

as

Walkable

)

.

walk

(

)

;

 

// Type checking

  print

(

'Can the duck fly? ${duck is Flyable}'

)

;

  print

(

'Can the duck swim? ${duck is Swimmable}'

)

;

 

var

fish

=

Fish

(

)

;

  print

(

'Can the fish fly? ${fish is Flyable}'

)

;

}



RUNOOB 鸭 在天空中飞翔

RUNOOB 鸭 在水面上游泳

RUNOOB 鸭 在陆地上摇摇晃晃地走

鸭子能飞吗? true

鸭子能游吗? true

鱼能飞吗? false


Code Reuse with Mixins

A Mixin is a mechanism for reusing code across multiple classes; it solves the problem of "multiple classes needing to share the same methods where inheritance is not appropriate".

Use the mixin keyword to define a Mixin, and the with keyword to mix it into a class.

Example

// Define using the mixin keyword

mixin Logger

{

 

// Methods in a Mixin can be reused by multiple classes

 

void

log

(

String message

)

{

    print

(

'[${DateTime.now()}] $message'

)

;

 

}

 

void

logError

(

String message

)

{

    print

(

'[ERROR ${DateTime.now()}] $message'

)

;

 

}

}

mixin TimestampFormatter

{

  String formatTimestamp

(

DateTime dt

)

{

   

return

'${dt.year}-${dt.month.toString().padLeft(2, '

0

')}'

       

'-${dt.day.toString().padLeft(2, '

0

')}'

;

 

}

}

// Mix in the Mixin using the with keyword

class

UserService

with

Logger

,

TimestampFormatter

{

 

void

createUser

(

String name

)

{

    log

(

'Create user: $name'

)

;

   

var

now

=

DateTime.

now

(

)

;

    print

(

'Created at: ${formatTimestamp(now)}'

)

;

 

}

}

class

OrderService

with

Logger

{

 

void

createOrder

(

String orderId

)

{

    log

(

'Create order: $orderId'

)

;

 

}

 

void

cancelOrder

(

String orderId

)

{

    logError

(

'Failed to cancel order: $orderId'

)

;

 

}

}

void

main

(

)

{

 

var

userService

=

UserService

(

)

;

  userService.

createUser

(

'runoob'

)

;

 

var

orderService

=

OrderService

(

)

;

  orderService.

createOrder

(

'ORD-001'

)

;

  orderService.

cancelOrder

(

'ORD-001'

)

;

}



[2026-06-12 10:30:00.000] 创建用户: runoob

创建时间: 2026-06-12

[2026-06-12 10:30:00.001] 创建订单: ORD-001

[ERROR 2026-06-12 10:30:00.001] 取消订单失败: ORD-001

UserService and OrderService come from different business domains, so using inheritance to share Logger is not appropriate.

Through a Mixin, both can gain logging functionality without affecting each other.

A Mixin cannot have a constructor and cannot be instantiated. Its role is very pure: to provide reusable methods without involving state initialization.

Mixin Constraints

A Mixin can use the on keyword to restrict it to being used only by classes of a specific type.

Example

// Base class

class

Animal

{

  String name

;

  Animal

(

this

.

name

)

;

}

// This Mixin can only be mixed into Animal and its subclasses

mixin FlyableMixin on Animal

{

 

void

fly

(

)

{

    print

(

'$name is flying!'

)

;

 

}

}

// Bird is an Animal, so it can use FlyableMixin

class

Bird

extends

Animal

with

FlyableMixin

{

  Bird

(

String name

)

:

super

(

name

)

;

}

// The following line will error: Car is not an Animal, so it cannot use FlyableMixin

// class Car with FlyableMixin {} // Error!

void

main

(

)

{

 

var

bird

=

Bird

(

'RUNOOB Little Bird'

)

;

  bird.

fly

(

)

;

 

// Methods in FlyableMixin can access the Animal property name

  print

(

'The little bird's name: ${bird.name}'

)

;

}



RUNOOB 小鸟 飞起来了!

小鸟的名字: RUNOOB 小鸟

The Full Combination of class, Mixin, extends, and implements

In Dart a class can use extends, with, and implements at the same time:

Example

mixin Jumpable

{

 

void

jump

(

)

=>

print

(

'Jump up!'

)

;

}

mixin Runnable

{

 

void

run

(

)

=>

print

(

'Run forward!'

)

;

}

class

Animal

{

 

void

breathe

(

)

=>

print

(

'Breathing...'

)

;

}

// Inherit Animal, mix in Jumpable and Runnable, implement Comparable

class

Athlete

extends

Animal

   

with

Jumpable

,

Runnable

   

implements

Comparable

<

Athlete

{

  String name

;

 

int

score

;

  Athlete

(

this

.

name

,

this

.

score

)

;

  @override

 

int

compareTo

(

Athlete other

)

=>

score.

compareTo

(

other.

score

)

;

 

void

showSkills

(

)

{

    breathe

(

)

;

    run

(

)

;

    jump

(

)

;

 

}

}

void

main

(

)

{

 

var

a1

=

Athlete

(

'RUNOOB Player A'

,

95

)

;

 

var

a2

=

Athlete

(

'Player B'

,

88

)

;

  a1.

showSkills

(

)

;

  print

(

'${a1.name} vs ${a2.name}: ${a1.compareTo(a2) > 0 ? "A wins" : "B wins"}'

)

;

}



呼吸...

跑步前进!

跳起来!

RUNOOB 选手A vs 选手B: A 胜

Full declaration order: class Subclass extends Parent with Mixin1, Mixin2 implements Interface1, Interface2