Code reusability is one of the most important principles of professional Flutter development. As applications grow, developers often encounter situations where multiple classes need similar functionality, such as logging, validation, formatting, or state management.
Traditional inheritance can solve some of these problems, but it is not always the best approach.
Dart provides two powerful features for writing reusable code: mixins and extension methods.
Mixins allow classes to reuse behavior without requiring a traditional parent-child relationship. Extension methods allow developers to add convenient operations to existing types without modifying their original source code.
In this tutorial, we’ll explore both concepts with practical examples and build a complete Flutter task manager application that uses mixins for logging and validation and extensions for text and date formatting.
This is Flutter Article 13 in the Moiks Developer Blog Flutter Tutorials series.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What mixins are in Dart and why they are useful.
- How to use the
withkeyword. - How mixins differ from inheritance and interfaces.
- How to use the
onkeyword to constrain mixins. - How mixin method overriding works.
- How to combine multiple mixins.
- What
mixin classmeans. - How to create extension methods.
- How to add extension getters and properties.
- How to handle nullable values in extensions.
- How generic extensions work.
- What extension types are and how they differ from extension methods.
- How to apply mixins and extensions in Flutter applications.
- How to build and test a Flutter task manager.
1. What Is a Mixin in Dart?
A mixin is a reusable collection of methods and properties that can be added to compatible classes.
Instead of placing shared behavior inside a superclass, you can define it separately and apply it where needed.
Consider an application with several classes:
- UserService
- ProductService
- OrderService
All three classes may need logging functionality.
Without mixins, developers might duplicate logging code or create an unnecessary shared superclass.
A mixin provides another option.
Basic Mixin Example
mixin Logger {
void log(String message) {
print('[LOG] $message');
}
}
class UserService with Logger {
void createUser() {
log('Creating user');
}
}
class ProductService with Logger {
void loadProducts() {
log('Loading products');
}
}
void main() {
UserService().createUser();
ProductService().loadProducts();
}
Output:
[LOG] Creating user
[LOG] Loading products
Both classes reuse the same logging behavior.
Neither class needs to extend a logging superclass.
Why Use Mixins?
Mixins are useful for sharing cross-cutting behavior such as logging, validation, caching helpers, animation-related behavior, and reusable lifecycle operations.
However, mixins should represent coherent capabilities. Avoid turning them into large collections of unrelated utilities.
2. Understanding the with Keyword
Dart uses the with keyword to apply mixins to a class.
Syntax
mixin MyMixin {
void performAction() {
print('Action performed');
}
}
class MyClass with MyMixin {}
The class gains access to the mixin’s behavior.
Example: Reusable Validation
mixin InputValidator {
bool isValidEmail(String email) {
return email.contains('@') &&
email.contains('.');
}
bool isValidPassword(String password) {
return password.length >= 8;
}
}
class RegistrationService with InputValidator {
bool register(String email, String password) {
return isValidEmail(email) &&
isValidPassword(password);
}
}
void main() {
final service = RegistrationService();
print(
service.register(
'user@example.com',
'password123',
),
);
}
Output:
true
This is a simplified validation example for learning purposes. Production applications should use appropriate validation rules, authentication infrastructure, and security controls.
3. Applying Multiple Mixins
A class can use multiple mixins.
Example
mixin Logger {
void log(String message) {
print('[LOG] $message');
}
}
mixin TimestampProvider {
DateTime get currentTime => DateTime.now();
}
class TaskService with Logger, TimestampProvider {
void createTask(String title) {
log('Task created: $title');
print('Created at: $currentTime');
}
}
Usage:
void main() {
final service = TaskService();
service.createTask('Learn Dart Mixins');
}
The class gains behavior from both mixins.
Important Rule
Mixin application order matters when mixins define overlapping methods.
The rightmost applicable mixin has precedence in method lookup.
For example:
mixin FirstMixin {
void show() {
print('First');
}
}
mixin SecondMixin {
void show() {
print('Second');
}
}
class Example with FirstMixin, SecondMixin {}
void main() {
Example().show();
}
Output:
Second
Avoid relying heavily on overlapping mixin implementations because they can make behavior difficult to understand.
4. Mixins vs Inheritance in Dart
Mixins and inheritance both support behavior reuse, but their design goals differ.
| Feature | Inheritance | Mixins |
|---|---|---|
| Keyword | extends | with |
| Main purpose | Specialization and inherited behavior | Reusable capabilities |
| Multiple direct applications | One superclass | Multiple mixins |
| Models an is-a relationship | Usually | Not necessarily |
| Can contain reusable methods | Yes | Yes |
| Typical example | Car extends Vehicle | TaskService with Logger |
Inheritance Example
class Vehicle {
void start() {
print('Vehicle started');
}
}
class Car extends Vehicle {}
A car is a vehicle.
Mixin Example
mixin Logger {
void log(String message) {
print(message);
}
}
class Car with Logger {}
A car is not a logger, but it can use logging behavior.
Best practice: Use inheritance for genuine subtype relationships and mixins for reusable capabilities.
5. Understanding the on Keyword in Mixins
The on keyword constrains which classes can use a mixin.
It also gives the mixin access to members of the specified superclass.
Example
class BaseController {
void notifyListeners() {
print('Listeners notified');
}
}
mixin Refreshable on BaseController {
void refresh() {
print('Refreshing data');
notifyListeners();
}
}
class ProductController extends BaseController
with Refreshable {}
void main() {
ProductController().refresh();
}
Output:
Refreshing data
Listeners notified
Why Use on?
The mixin requires access to notifyListeners().
By declaring:
mixin Refreshable on BaseController
Dart ensures the mixin is applied only in a compatible inheritance hierarchy.
This is particularly useful when mixins depend on functionality supplied by a superclass.
6. Mixins with Abstract Members
Mixins can declare abstract members that applying classes must satisfy.
Example
mixin Describable {
String get name;
void describe() {
print('Object name: $name');
}
}
class Product with Describable {
@override
final String name;
Product(this.name);
}
void main() {
final product = Product('Bluetooth Speaker');
product.describe();
}
Output:
Object name: Bluetooth Speaker
The mixin expects a name property.
The applying class provides it.
This technique helps define reusable behavior with explicit requirements.
7. Method Overriding with Mixins
Classes can override methods supplied by mixins.
Example
mixin Logger {
void log(String message) {
print('[DEFAULT] $message');
}
}
class NetworkService with Logger {
@override
void log(String message) {
print('[NETWORK] $message');
}
}
void main() {
NetworkService().log('Request started');
}
Output:
[NETWORK] Request started
Calling a Mixin Implementation with super
A class can also call the inherited mixin implementation.
mixin Logger {
void log(String message) {
print('[LOG] $message');
}
}
class AnalyticsService with Logger {
@override
void log(String message) {
super.log(message);
print('Analytics event recorded');
}
}
This is useful when extending behavior rather than replacing it completely.
8. What Is mixin class in Dart?
Modern Dart supports the mixin class declaration.
A mixin class can be used both as a class and as a mixin, subject to Dart’s class modifier rules.
Example
mixin class Printable {
void printDetails() {
print('Printing details');
}
}
class Invoice with Printable {}
void main() {
final printable = Printable();
printable.printDetails();
final invoice = Invoice();
invoice.printDetails();
}
Unlike a declaration using only mixin, a mixin class can be instantiated directly when it is concrete.
Important Restrictions
Mixin classes cannot declare generative constructors.
The exact ways a mixin class can be extended or applied also depend on any additional class modifiers and library boundaries.
When Should You Use mixin class?
Use it when a type genuinely needs to support both class-style and mixin-style usage.
For most reusable capabilities, a regular mixin is sufficient.
9. Real Flutter Example: Using SingleTickerProviderStateMixin
Flutter itself uses mixins extensively.
One common example is SingleTickerProviderStateMixin.
It provides a ticker suitable for coordinating an animation controller with the widget’s lifecycle.
import 'package:flutter/material.dart';
class AnimatedExample extends StatefulWidget {
const AnimatedExample({super.key});
@override
State<AnimatedExample> createState() =>
_AnimatedExampleState();
}
class _AnimatedExampleState
extends State<AnimatedExample>
with SingleTickerProviderStateMixin {
late final AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
)..repeat(reverse: true);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: FadeTransition(
opacity: controller,
child: const FlutterLogo(size: 120),
),
);
}
}
How It Works
The state class uses:
with SingleTickerProviderStateMixin
This allows the state object to act as the ticker provider for its animation controller.
The controller uses:
vsync: this
The animation controller is disposed of when the widget state is disposed.
This is a practical example of mixins supporting reusable framework behavior.
10. What Are Extension Methods in Dart?
Extension methods allow developers to define additional methods and getters for an existing type without modifying its source code.
For example, Dart’s String class does not need to contain every formatting helper your application might require.
You can define your own extension.
Basic Extension Example
extension StringExtensions on String {
String capitalizeFirst() {
if (isEmpty) return this;
return this[0].toUpperCase() +
substring(1);
}
}
void main() {
print('flutter'.capitalizeFirst());
}
Output:
Flutter
The method can be called using normal method syntax.
Why Use Extension Methods?
Extensions are useful for adding concise, reusable operations to types such as:
StringintdoubleDateTimeList<T>BuildContext- Application-specific model classes
Extensions are statically resolved. They do not modify the original class or introduce virtual methods into its runtime interface.
11. Creating String Extension Methods
Let’s create several practical text utilities.
extension StringFormatting on String {
String capitalizeFirst() {
if (isEmpty) return this;
return this[0].toUpperCase() +
substring(1);
}
String get reversed =>
split('').reversed.join();
bool get isBlank => trim().isEmpty;
String get withoutExtraSpaces =>
trim().replaceAll(
RegExp(r'\s+'),
' ',
);
}
Usage:
void main() {
print('flutter'.capitalizeFirst());
print('dart'.reversed);
print(' '.isBlank);
print(
'Hello Flutter'.withoutExtraSpaces,
);
}
Output:
Flutter
trad
true
Hello Flutter
These examples demonstrate extension methods and extension getters.
The simple character-reversal example works for basic text but does not correctly handle every Unicode grapheme cluster, such as some emoji sequences. Production text processing may require a grapheme-aware approach.
12. Extension Getters in Dart
Extensions can define getters in addition to methods.
Example
extension NumberExtensions on int {
bool get isPositive => this > 0;
bool get isNegative => this < 0;
bool get isEvenNumber => isEven;
}
void main() {
print(10.isPositive);
print((-5).isNegative);
print(8.isEvenNumber);
}
Output:
true
true
true
Extension getters provide a convenient syntax for derived properties.
Avoid creating extensions that merely rename existing APIs without improving clarity.
13. DateTime Extension Methods
Date formatting is common in task managers, expense trackers, calendars, and diary applications.
For this tutorial, we’ll use a simple dependency-free formatter.
extension DateFormatting on DateTime {
String get formattedDate {
final day = this.day.toString().padLeft(2, '0');
final month =
this.month.toString().padLeft(2, '0');
return '$day/$month/$year';
}
bool get isToday {
final now = DateTime.now();
return year == now.year &&
month == now.month &&
day == now.day;
}
}
Usage:
void main() {
final date = DateTime(2026, 11, 9);
print(date.formattedDate);
}
Output:
09/11/2026
For production applications requiring localized date formatting, consider Flutter’s internationalization support and the intl package.
14. Nullable Extension Methods
Extensions can also target nullable types.
Example
extension NullableStringExtensions on String? {
String get orEmpty => this ?? '';
bool get isNullOrBlank =>
this == null || this!.trim().isEmpty;
}
Usage:
void main() {
String? username;
print(username.orEmpty);
print(username.isNullOrBlank);
}
Output:
true
The first printed line is empty because orEmpty returns an empty string.
When Is This Useful?
Nullable extensions can simplify optional values returned by APIs, forms, or local storage.
However, use them carefully. A default value should not hide missing data that requires explicit handling.
15. Generic Extension Methods
Dart extensions can use generic type parameters.
This allows the same extension to work with many different types.
Example: Safe List Access
extension SafeListAccess<T> on List<T> {
T? elementAtOrNull(int index) {
if (index < 0 || index >= length) {
return null;
}
return this[index];
}
}
Usage:
void main() {
final names = ['Alex', 'Sam'];
print(names.elementAtOrNull(0));
print(names.elementAtOrNull(10));
}
Output:
Alex
null
Modern Dart libraries also provide several convenient nullable-access helpers, so check the standard library before adding an equivalent custom extension.
Generic Extensions for Collections
extension ListUtilities<T> on List<T> {
List<T> get reversedCopy =>
reversed.toList();
}
This extension works with lists containing strings, numbers, or custom objects.
16. Extension Methods vs Utility Functions
Both approaches can provide reusable functionality.
Utility Function
String capitalize(String value) {
if (value.isEmpty) return value;
return value[0].toUpperCase() +
value.substring(1);
}
Usage:
capitalize('flutter');
Extension Method
extension Capitalization on String {
String capitalize() {
if (isEmpty) return this;
return this[0].toUpperCase() +
substring(1);
}
}
Usage:
'flutter'.capitalize();
Comparison
| Feature | Extension Method | Utility Function |
|---|---|---|
| Calling syntax | value.method() | function(value) |
| Adds source-code members to the original type | No | No |
| Supports extension getters | Yes | Not applicable |
| Suitable for reusable helpers | Yes | Yes |
| Resolved through static extension lookup | Yes | Normal function call |
Use extensions when the operation naturally belongs with the receiving type.
Use standalone functions when the operation does not clearly belong to one type or when a function is more straightforward.
17. Extension Method Resolution
Extension methods are resolved statically.
This means Dart uses the receiver’s static type and the extensions available in scope.
Example
extension ObjectDescription on Object {
String describe() => 'Object extension';
}
extension StringDescription on String {
String describe() => 'String extension';
}
void main() {
String text = 'Flutter';
Object value = text;
print(text.describe());
print(value.describe());
}
Output:
String extension
Object extension
Although both variables refer to a string, the selected extension depends on the static type.
Important Rules
- Instance members generally take precedence over extension members.
- Extension lookup depends on static types and imports.
- Conflicting extensions can require explicit extension invocation.
- Extensions do not override existing instance methods.
Understanding these rules helps avoid unexpected behavior in larger Dart projects.
18. What Are Extension Types in Dart?
Extension types are different from extension methods.
An extension type defines a new static abstraction over an existing representation type.
It can help provide a more meaningful API without introducing a traditional wrapper object in the same way as an ordinary class.
Example
extension type UserId(int value) {
bool get isValid => value > 0;
String get formatted => 'USER-$value';
}
void main() {
final id = UserId(101);
print(id.isValid);
print(id.formatted);
}
Output:
true
USER-101
Extension Methods vs Extension Types
| Feature | Extension Methods | Extension Types |
|---|---|---|
| Main purpose | Add convenient operations to existing types | Define a new static abstraction |
Uses extension | Yes | Uses extension type |
| Changes existing type’s interface | No | Introduces a distinct static interface |
| Example | Formatting a string | Representing a validated identifier |
| Runtime behavior | Static member resolution | Uses the representation type at runtime |
Extension types are useful for specialized APIs, domain modeling, and representation-based abstractions.
They do not automatically validate constructor arguments. Validation must be implemented explicitly where required.
19. Mixins vs Extensions: Which Should You Use?
Both features promote code reuse, but they solve different problems.
| Requirement | Recommended Feature |
|---|---|
| Share behavior among classes | Mixin |
Add formatting to String | Extension |
Add convenience methods to DateTime | Extension |
| Reuse logging in several services | Mixin or injected logger |
Add helpers to BuildContext | Extension |
| Share behavior that requires superclass members | Constrained mixin |
| Define a domain-specific representation abstraction | Extension type |
| Replace a dependency for testing | Interface and dependency injection |
Practical Rule
Use a mixin when reusable behavior becomes part of a class’s capabilities.
Use an extension when you want convenient operations on an existing type.
Use composition or dependency injection when the shared behavior has substantial state, dependencies, or an independent lifecycle.
20. Practical Flutter Project: Task Manager with Mixins & Extensions
Now let’s build a complete Flutter task manager demonstrating the concepts covered in this tutorial.
The app will support adding tasks, validating input, marking tasks as complete, deleting tasks, displaying creation dates, filtering tasks, and tracking task statistics.
We’ll use:
- A mixin for logging.
- A mixin for task validation.
- String extensions for formatting.
- DateTime extensions for displaying dates.
- A task model.
- A task service.
- A responsive Flutter interface.
- Unit and widget tests.
The application will store tasks in memory. Persistent storage will be introduced in a later tutorial.
Step 1: Create a Flutter Project
Open Terminal:
flutter create dart_mixins_extensions_demo
cd dart_mixins_extensions_demo
No additional third-party packages are required.
Step 2: Project Structure
Create the following files:
lib/
├── main.dart
├── models/
│ └── task.dart
├── mixins/
│ ├── logger_mixin.dart
│ └── validation_mixin.dart
├── extensions/
│ ├── string_extensions.dart
│ └── date_extensions.dart
└── services/
└── task_service.dart
test/
├── task_service_test.dart
└── task_widget_test.dart
Step 3: Create the Task Model
Create lib/models/task.dart:
class Task {
final int id;
final String title;
final DateTime createdAt;
final bool isCompleted;
const Task({
required this.id,
required this.title,
required this.createdAt,
this.isCompleted = false,
});
Task copyWith({
String? title,
bool? isCompleted,
}) {
return Task(
id: id,
title: title ?? this.title,
createdAt: createdAt,
isCompleted: isCompleted ?? this.isCompleted,
);
}
}
The model is immutable.
The copyWith() method creates updated task objects instead of changing existing objects directly.
Step 4: Create the Logging Mixin
Create lib/mixins/logger_mixin.dart:
import 'package:flutter/foundation.dart';
mixin LoggerMixin {
void logInfo(String message) {
debugPrint('[INFO] $message');
}
void logError(String message) {
debugPrint('[ERROR] $message');
}
}
This mixin provides reusable logging functionality.
For a production application, consider a dedicated logging service with configurable levels and privacy-safe diagnostics.
Step 5: Create the Validation Mixin
Create lib/mixins/validation_mixin.dart:
mixin ValidationMixin {
bool isValidTaskTitle(String title) {
final value = title.trim();
return value.isNotEmpty &&
value.length <= 100;
}
String? validateTaskTitle(String title) {
final value = title.trim();
if (value.isEmpty) {
return 'Task title cannot be empty';
}
if (value.length > 100) {
return 'Task title must be 100 characters or less';
}
return null;
}
}
This mixin centralizes task-title validation.
The same validation can be reused in services or controllers where appropriate.
Step 6: Create the String Extension
Create lib/extensions/string_extensions.dart:
extension TaskStringExtensions on String {
String get normalizedTaskTitle {
return trim().replaceAll(
RegExp(r'\s+'),
' ',
);
}
String get capitalized {
if (isEmpty) return this;
return this[0].toUpperCase() +
substring(1);
}
}
These extensions help normalize task titles.
Example:
final title =
' learn dart mixins '
.normalizedTaskTitle
.capitalized;
print(title);
Output:
Learn dart mixins
Step 7: Create the DateTime Extension
Create lib/extensions/date_extensions.dart:
extension TaskDateExtensions on DateTime {
String get formattedDate {
final day =
this.day.toString().padLeft(2, '0');
final month =
this.month.toString().padLeft(2, '0');
return '$day/$month/$year';
}
bool get isToday {
final now = DateTime.now();
return year == now.year &&
month == now.month &&
day == now.day;
}
}
This keeps simple date formatting separate from the widget code.
Step 8: Create the Task Service
Create lib/services/task_service.dart:
import '../extensions/string_extensions.dart';
import '../mixins/logger_mixin.dart';
import '../mixins/validation_mixin.dart';
import '../models/task.dart';
class TaskService
with LoggerMixin, ValidationMixin {
final List<Task> _tasks = [];
int _nextId = 1;
List<Task> get tasks =>
List.unmodifiable(_tasks);
int get totalCount => _tasks.length;
int get completedCount =>
_tasks.where((task) => task.isCompleted).length;
int get pendingCount =>
totalCount - completedCount;
void addTask(String title) {
final normalized =
title.normalizedTaskTitle;
final error = validateTaskTitle(normalized);
if (error != null) {
logError(error);
throw ArgumentError(error);
}
final task = Task(
id: _nextId++,
title: normalized.capitalized,
createdAt: DateTime.now(),
);
_tasks.add(task);
logInfo('Task created: ${task.title}');
}
void toggleTask(int id) {
final index = _tasks.indexWhere(
(task) => task.id == id,
);
if (index == -1) {
logError('Task not found: $id');
throw StateError('Task not found');
}
final task = _tasks[index];
_tasks[index] = task.copyWith(
isCompleted: !task.isCompleted,
);
logInfo('Task status updated: $id');
}
void deleteTask(int id) {
final previousCount = _tasks.length;
_tasks.removeWhere(
(task) => task.id == id,
);
if (_tasks.length < previousCount) {
logInfo('Task deleted: $id');
}
}
void clearCompleted() {
_tasks.removeWhere(
(task) => task.isCompleted,
);
logInfo('Completed tasks cleared');
}
List<Task> filteredTasks({
String query = '',
bool? completed,
}) {
final normalizedQuery =
query.trim().toLowerCase();
final result = _tasks.where((task) {
final matchesQuery = task.title
.toLowerCase()
.contains(normalizedQuery);
final matchesStatus =
completed == null ||
task.isCompleted == completed;
return matchesQuery && matchesStatus;
}).toList();
result.sort((a, b) {
if (a.isCompleted != b.isCompleted) {
return a.isCompleted ? 1 : -1;
}
return b.createdAt.compareTo(a.createdAt);
});
return result;
}
}
Understanding the Task Service
The service combines several Dart features.
Mixins:
with LoggerMixin, ValidationMixin
These provide reusable logging and validation methods.
String extensions:
title.normalizedTaskTitle
This normalizes user input.
Collections:
_tasks.where(...)
This filters tasks.
Immutable model updates:
task.copyWith(...)
This creates updated task objects.
Encapsulation:
final List<Task> _tasks = [];
This keeps the internal list private to its library and exposes an unmodifiable snapshot.
The service separates business logic from the Flutter interface.
Step 9: Build the Flutter UI
Replace lib/main.dart with:
import 'package:flutter/material.dart';
import 'extensions/date_extensions.dart';
import 'models/task.dart';
import 'services/task_service.dart';
void main() {
runApp(const TaskManagerApp());
}
class TaskManagerApp extends StatelessWidget {
const TaskManagerApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dart Mixins & Extensions',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF004B64),
),
useMaterial3: true,
),
home: const TaskManagerScreen(),
);
}
}
class TaskManagerScreen extends StatefulWidget {
const TaskManagerScreen({super.key});
@override
State<TaskManagerScreen> createState() =>
_TaskManagerScreenState();
}
class _TaskManagerScreenState
extends State<TaskManagerScreen> {
final TaskService service = TaskService();
final TextEditingController taskController =
TextEditingController();
final TextEditingController searchController =
TextEditingController();
String searchQuery = '';
bool? selectedStatus;
@override
void dispose() {
taskController.dispose();
searchController.dispose();
super.dispose();
}
void addTask() {
final title = taskController.text;
try {
setState(() {
service.addTask(title);
});
taskController.clear();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Task added successfully'),
),
);
} on ArgumentError catch (error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
error.message?.toString() ??
'Invalid task title',
),
),
);
}
}
Widget buildSummary() {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Wrap(
alignment: WrapAlignment.spaceAround,
spacing: 20,
runSpacing: 12,
children: [
_summaryItem(
'Total',
service.totalCount,
Icons.list_alt,
),
_summaryItem(
'Pending',
service.pendingCount,
Icons.pending_actions,
),
_summaryItem(
'Completed',
service.completedCount,
Icons.check_circle_outline,
),
],
),
),
);
}
Widget _summaryItem(
String label,
int count,
IconData icon,
) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon),
const SizedBox(height: 4),
Text(
'$count',
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
Text(label),
],
);
}
Widget buildTaskTile(Task task) {
return Card(
margin: const EdgeInsets.symmetric(
vertical: 5,
),
child: ListTile(
leading: Checkbox(
value: task.isCompleted,
onChanged: (_) {
setState(() {
service.toggleTask(task.id);
});
},
),
title: Text(
task.title,
style: TextStyle(
decoration: task.isCompleted
? TextDecoration.lineThrough
: null,
),
),
subtitle: Text(
'Created: ${task.createdAt.formattedDate}',
),
trailing: IconButton(
tooltip: 'Delete task',
icon: const Icon(
Icons.delete_outline,
),
onPressed: () {
setState(() {
service.deleteTask(task.id);
});
},
),
),
);
}
@override
Widget build(BuildContext context) {
final visibleTasks = service.filteredTasks(
query: searchQuery,
completed: selectedStatus,
);
return Scaffold(
appBar: AppBar(
title: const Text('Task Manager'),
centerTitle: true,
actions: [
IconButton(
tooltip: 'Clear completed tasks',
onPressed: service.completedCount == 0
? null
: () {
setState(() {
service.clearCompleted();
});
},
icon: const Icon(
Icons.delete_sweep_outlined,
),
),
],
),
body: SafeArea(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 760,
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
buildSummary(),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: TextField(
controller: taskController,
onSubmitted: (_) => addTask(),
decoration:
const InputDecoration(
labelText: 'New Task',
hintText:
'Enter task title',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 10),
FilledButton.icon(
onPressed: addTask,
icon: const Icon(Icons.add),
label: const Text('Add'),
),
],
),
const SizedBox(height: 16),
TextField(
controller: searchController,
onChanged: (value) {
setState(() {
searchQuery = value;
});
},
decoration: const InputDecoration(
labelText: 'Search Tasks',
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SegmentedButton<int>(
segments: const [
ButtonSegment(
value: 0,
label: Text('All'),
),
ButtonSegment(
value: 1,
label: Text('Pending'),
),
ButtonSegment(
value: 2,
label: Text('Completed'),
),
],
selected: {
selectedStatus == null
? 0
: selectedStatus!
? 2
: 1,
},
onSelectionChanged: (selection) {
setState(() {
final value = selection.first;
selectedStatus = value == 0
? null
: value == 2;
});
},
),
),
const SizedBox(height: 12),
Expanded(
child: visibleTasks.isEmpty
? const Center(
child: Text(
'No tasks found',
),
)
: ListView.builder(
itemCount: visibleTasks.length,
itemBuilder: (context, index) {
return buildTaskTile(
visibleTasks[index],
);
},
),
),
],
),
),
),
),
),
);
}
}
Step 10: Run the Application
Start an Android emulator, iOS Simulator, or connected physical device.
Run:
flutter run
Expected Application Behavior
Initially, the application displays an empty task list.
Enter:
learn dart mixins
Tap Add.
The task appears as:
Learn dart mixins
Created: 09/11/2026
The displayed date will reflect the actual date the task was created.
Add more tasks:
Learn extension methods
Build Flutter task manager
Practice Dart OOP
You can then:
- Search tasks by title.
- Filter pending and completed tasks.
- Mark tasks as completed.
- Delete individual tasks.
- Clear all completed tasks.
- View task statistics.
The interface updates immediately after each operation.
How Mixins and Extensions Work in the App
| Feature | Implementation |
|---|---|
| Reusable logging | LoggerMixin |
| Input validation | ValidationMixin |
| Title normalization | String extension |
| Date formatting | DateTime extension |
| Task storage | List<Task> |
| Filtering | where() |
| Sorting | sort() |
| Immutable task updates | copyWith() |
| UI updates | setState() |
This project demonstrates how mixins and extensions can reduce duplication while keeping responsibilities clear.
21. Unit Testing Mixins and Extensions
Automated tests help verify reusable behavior independently of the Flutter interface.
Create:
test/task_service_test.dart
Add:
import 'package:flutter_test/flutter_test.dart';
import 'package:dart_mixins_extensions_demo/extensions/date_extensions.dart';
import 'package:dart_mixins_extensions_demo/extensions/string_extensions.dart';
import 'package:dart_mixins_extensions_demo/services/task_service.dart';
void main() {
group('String Extensions', () {
test('Normalizes task titles', () {
final result =
' learn flutter '
.normalizedTaskTitle;
expect(result, 'learn flutter');
});
test('Capitalizes first character', () {
expect(
'flutter'.capitalized,
'Flutter',
);
});
test('Handles empty strings', () {
expect(''.capitalized, '');
});
});
group('Date Extensions', () {
test('Formats dates', () {
final date = DateTime(2026, 11, 9);
expect(
date.formattedDate,
'09/11/2026',
);
});
});
group('Task Service', () {
late TaskService service;
setUp(() {
service = TaskService();
});
test('Adds a task', () {
service.addTask('Learn Dart');
expect(service.totalCount, 1);
expect(
service.tasks.first.title,
'Learn Dart',
);
});
test('Rejects empty titles', () {
expect(
() => service.addTask(' '),
throwsArgumentError,
);
});
test('Rejects overly long titles', () {
expect(
() => service.addTask('A' * 101),
throwsArgumentError,
);
});
test('Normalizes task titles', () {
service.addTask(
' learn flutter ',
);
expect(
service.tasks.first.title,
'Learn flutter',
);
});
test('Toggles task completion', () {
service.addTask('Learn Dart');
final id = service.tasks.first.id;
service.toggleTask(id);
expect(service.completedCount, 1);
expect(service.pendingCount, 0);
});
test('Filters tasks by query', () {
service.addTask('Learn Dart');
service.addTask('Build Flutter App');
final results = service.filteredTasks(
query: 'dart',
);
expect(results.length, 1);
expect(
results.first.title,
'Learn Dart',
);
});
test('Deletes a task', () {
service.addTask('Learn Dart');
final id = service.tasks.first.id;
service.deleteTask(id);
expect(service.totalCount, 0);
});
test('Clears completed tasks', () {
service.addTask('Task One');
service.addTask('Task Two');
service.toggleTask(
service.tasks.first.id,
);
service.clearCompleted();
expect(service.totalCount, 1);
expect(service.completedCount, 0);
});
test('Rejects unknown task IDs', () {
expect(
() => service.toggleTask(999),
throwsStateError,
);
});
});
}
Run:
flutter test test/task_service_test.dart
What These Tests Verify
The tests cover string normalization, capitalization, date formatting, input validation, task creation, completion tracking, filtering, deletion, and error handling.
These are useful examples of testing business logic without depending on UI interactions.
22. Flutter Widget Testing
Now let’s verify that the task manager interface behaves correctly.
Create:
test/task_widget_test.dart
Add:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:dart_mixins_extensions_demo/main.dart';
void main() {
testWidgets(
'Displays empty task message',
(tester) async {
await tester.pumpWidget(
const TaskManagerApp(),
);
expect(
find.text('No tasks found'),
findsOneWidget,
);
},
);
testWidgets(
'Adds a new task',
(tester) async {
await tester.pumpWidget(
const TaskManagerApp(),
);
await tester.enterText(
find.widgetWithText(
TextField,
'New Task',
),
'Learn Dart Mixins',
);
await tester.tap(
find.widgetWithText(
FilledButton,
'Add',
),
);
await tester.pump();
expect(
find.text('Learn Dart Mixins'),
findsOneWidget,
);
},
);
testWidgets(
'Updates task statistics',
(tester) async {
await tester.pumpWidget(
const TaskManagerApp(),
);
await tester.enterText(
find.widgetWithText(
TextField,
'New Task',
),
'Practice Flutter',
);
await tester.tap(
find.widgetWithText(
FilledButton,
'Add',
),
);
await tester.pump();
expect(
find.text('Practice Flutter'),
findsOneWidget,
);
expect(
find.byType(Checkbox),
findsOneWidget,
);
await tester.tap(
find.byType(Checkbox),
);
await tester.pump();
expect(
find.text('Practice Flutter'),
findsOneWidget,
);
},
);
}
Run:
flutter test test/task_widget_test.dart
Run all tests:
flutter test
Run static analysis:
flutter analyze
If you use a different project name, update the package import paths accordingly.
Also replace or remove the default counter-app widget test generated by flutter create.
23. Common Mistakes with Dart Mixins and Extensions
Mistake 1: Using Mixins for Unrelated Functionality
A mixin should represent a coherent reusable capability.
Avoid placing logging, networking, validation, and database access into one large mixin.
Mistake 2: Confusing extends and with
extends establishes superclass inheritance.
with applies mixin behavior.
Choose the feature that accurately represents the relationship.
Mistake 3: Ignoring Mixin Application Order
When multiple mixins provide overlapping members, application order affects method resolution.
Avoid unnecessary conflicts.
Mistake 4: Using on Without Understanding Constraints
The on clause restricts compatible applications of a mixin.
It is not simply an alternative spelling of extends.
Mistake 5: Assuming Extensions Modify Existing Classes
Extension methods do not change the source or runtime interface of the extended class.
They are resolved statically.
Mistake 6: Expecting Extensions to Override Instance Methods
Instance members take precedence over extension methods.
Extensions are not a replacement for normal method overriding.
Mistake 7: Creating Too Many Extensions
An excessive number of small extensions can make APIs harder to discover.
Group related extensions into appropriately named libraries.
Mistake 8: Ignoring Nullable Types
An extension on String does not automatically apply to String?.
Use appropriate nullable extensions or handle null before calling the method.
Mistake 9: Using Mixins Instead of Dependency Injection
A mixin is not always the right choice for behavior with complex dependencies or its own lifecycle.
For example, an injected logging service may be preferable when logging needs configurable outputs, persistence, or remote reporting.
Mistake 10: Duplicating Standard Library Functionality
Before writing an extension, check whether Dart or Flutter already provides the operation.
Use established APIs when they are clear and sufficient.
24. Best Practices for Dart Mixins and Extensions
Keep Mixins Focused
A mixin should represent one reusable capability.
Prefer Clear Naming
Use names such as LoggerMixin, ValidationMixin, and TaskDateExtensions to communicate intent.
Use on for Real Requirements
Apply mixin constraints when behavior depends on a specific superclass contract.
Avoid Deep Mixin Dependencies
Complex chains of mixins can become difficult to understand and debug.
Use Extensions for Natural Operations
Formatting a string or extracting a derived date property is a good candidate for an extension.
Consider Static Resolution
Remember that extension methods are selected using static types.
Avoid Hiding Important Business Rules
Critical validation, authorization, or payment logic should remain explicit and testable.
Keep UI and Business Logic Separate
Use models, services, and reusable components to keep widgets focused on presentation.
Write Automated Tests
Test mixin behavior, extension edge cases, and the services that use them.
Prefer Simplicity
Use mixins and extensions when they make code clearer, not merely because the language supports them.
25. Frequently Asked Questions
What is a mixin in Dart?
A mixin is a reusable collection of behavior that can be applied to compatible classes using the with keyword.
What is the with keyword in Dart?
The with keyword applies one or more mixins to a class, allowing it to reuse their behavior.
What is the on keyword in Dart mixins?
The on keyword specifies a superclass constraint for a mixin and allows the mixin to depend on members provided by that superclass.
Can a Dart class use multiple mixins?
Yes. A class can apply multiple compatible mixins.
What is the difference between a mixin and inheritance?
Inheritance establishes a superclass relationship. Mixins provide reusable behavior without requiring the applying class to be a traditional specialization of the mixin.
What is mixin class in Dart?
A mixin class is a declaration that supports both class and mixin usage, subject to Dart’s language restrictions.
What are extension methods in Dart?
Extension methods add convenient operations to existing types without modifying their original declarations.
Can extension methods override existing methods?
No. Extension methods do not override instance members.
Can Dart extensions contain getters?
Yes. Extensions can declare methods, getters, setters, and operators, subject to language rules.
Can extension methods work with nullable types?
Yes. You can declare an extension on a nullable type such as String?.
What are generic extensions?
Generic extensions use type parameters so the same extension can work with multiple types.
What is the difference between extension methods and extension types?
Extension methods add statically resolved operations to existing types. Extension types define new static abstractions over representation types.
Does Flutter use mixins?
Yes. Flutter uses mixins in several framework APIs, including animation-related state mixins.
Should Flutter developers use mixins or extensions?
Use mixins for reusable class behavior and extensions for convenient operations on existing types.
Are mixins better than composition?
Not always. Composition is often preferable when shared behavior has substantial dependencies or independent state.
Are extension methods useful for Flutter UI?
Yes. They can simplify formatting, theme access, date handling, and other frequently repeated operations.
26. Conclusion
Dart mixins and extension methods are valuable tools for writing clean, reusable, and maintainable Flutter applications.
In this tutorial, we explored how mixins share behavior across classes, how with applies mixins, and how on constrains their use.
We also learned about multiple mixins, method overriding, abstract mixin members, and the mixin class declaration.
Next, we explored extension methods, extension getters, nullable extensions, generic extensions, and extension types.
Finally, we built a practical Flutter task manager application that uses mixins for logging and validation and extensions for text and date formatting.
The most important lesson is to choose the right reuse mechanism for the problem.
Use inheritance for genuine subtype relationships, mixins for reusable capabilities, extensions for natural operations on existing types, and composition when dependencies deserve their own objects.
These concepts will help you design better Flutter applications as your projects grow in size and complexity.
What’s Next in the Flutter Tutorials Series?
Flutter Article 14: Dart Generics Explained — Type Parameters, Generic Classes, Methods & Practical Flutter Examples
In the next tutorial, we’ll explore generic classes, generic functions, bounded type parameters, type-safe repositories, and reusable Flutter components.
Continue learning Flutter and Dart:
Moiks Developer Blog: https://moiks.com/blog/
Official Documentation and References
- Dart Mixins — https://dart.dev/language/mixins
- Dart Extension Methods — https://dart.dev/language/extension-methods
- Dart Extension Types — https://dart.dev/language/extension-types
- Dart Class Modifiers — https://dart.dev/language/class-modifiers
- Dart Classes — https://dart.dev/language/classes
- Dart Generics — https://dart.dev/language/generics
- Flutter Animation Tutorial — https://docs.flutter.dev/ui/animations/tutorial
- Flutter Architectural Overview — https://docs.flutter.dev/resources/architectural-overview
- Flutter App Architecture — https://docs.flutter.dev/app-architecture
- Flutter Testing Overview — https://docs.flutter.dev/testing/overview
- DartPad — https://dartpad.dev/
Moiks Developer Blog — Practical Flutter, Dart, Android, and iOS development tutorials.