Result Command is a lightweight package that brings the Command Pattern to Flutter, allowing you to encapsulate actions, track their execution state, and manage results with clarity. Perfect for simplifying complex workflows, ensuring robust error handling, and keeping your UI reactive.
-
Add the package to your
pubspec.yaml
:dependencies: result_command: x.x.x result_dart: 2.x.x
-
Wrap your actions in commands:
- Use pre-defined
Command
types to encapsulate your logic. - Attach listeners to update your UI dynamically.
- Use pre-defined
-
Execute commands from your UI and enjoy the benefits of encapsulated logic and state tracking.
- Encapsulation: Wrap your business logic into reusable commands.
- State Tracking: Automatically manage states like
Idle
,Running
,Success
,Failure
, andCancelled
. - Error Handling: Centralize how you handle successes and failures using the intuitive
Result
API. - State History: Track state transitions with optional metadata.
- Timeout Support: Specify execution time limits for commands.
- Cancellation Support: Cancel long-running tasks when needed.
- UI Integration: React to command state changes directly in your Flutter widgets.
At its core, Result Command lets you define reusable actions (commands) that manage their lifecycle. Each command:
- Executes an action (e.g., API call, user input validation).
- Tracks its state (
Idle
,Running
, etc.). - Notifies listeners when the state changes.
- Maintains a history of states and transitions.
- Returns a result (
Success
orFailure
) using theResult
API.
Each Command
exposes its current state through a CommandState
. The state represents one of the following:
IdleCommand
: The command is ready to execute.RunningCommand
: The command is currently executing an action.SuccessCommand
: The action completed successfully.FailureCommand
: The action failed with an error.CancelledCommand
: The action was explicitly stopped.
You can access the current state using the value
property of the command:
final command = Command0<String>(() async {
return Success('Hello, World!');
});
// The current state of the command.
print(command.value); // Outputs: SuccessCommand<String>
The state updates automatically as the command executes:
- Use
addListener
for manual handling. - Use
ValueListenableBuilder
to bind the state to your UI.
Each command tracks a configurable history of its states, useful for debugging, auditing, and behavioral analysis.
Set the maximum length of the history when creating a command:
final command = Command0<String>(
() async => const Success('Done'),
maxHistoryLength: 5,
);
Access the history with stateHistory
:
final history = command.stateHistory;
history.forEach(print);
To simplify state management and improve code readability, the following getters are available:
-
isIdle
: Checks if the command is in the idle state.bool get isIdle => value is IdleCommand<T>;
-
isRunning
: Checks if the command is currently running.bool get isRunning => value is RunningCommand<T>;
-
isCancelled
: Checks if the command has been cancelled.bool get isCancelled => value is CancelledCommand<T>;
-
isSuccess
: Checks if the command execution was successful.bool get isSuccess => value is SuccessCommand<T>;
-
isFailure
: Checks if the command execution failed.bool get isFailure => value is FailureCommand<T>;
These getters allow you to write cleaner and more intuitive code when interacting with commands in your views or controllers.
Encapsulate a simple action into a reusable Command
:
final fetchGreetingCommand = Command0<String>(
() async {
await Future.delayed(Duration(seconds: 2));
return Success('Hello, World!');
},
);
fetchGreetingCommand.addListener(() {
final snapshot = fetchGreetingCommand.value;
if (snapshot is Success<String>) {
final result = snapshot.value;
print('Success: $result');
} else if (snapshot is FailureCommand<String>) {
final error = snapshot.error;
print('Failure: $error');
}
});
// Execute the command
fetchGreetingCommand.execute();
Commands now support a timeout for execution:
final fetchGreetingCommand = Command0<String>(
() async {
await Future.delayed(Duration(seconds: 5)); // Simulating a delay.
return Success('Hello, World!');
},
);
fetchGreetingCommand //
.execute(timeout: Duration(seconds: 2))
.catchError((error) {
print('Error: $error'); // "Error: Command timed out"
},
);
Pass input to your command's action:
final calculateSquareCommand = Command1<int, int>(
(number) async {
if (number < 0) {
return Failure(Exception('Negative numbers are not allowed.'));
}
return Success(number * number);
},
);
calculateSquareCommand.addListener(() {
final snapshot = calculateSquareCommand.value;
if (snapshot is SuccessCommand<int>) {
final result = snapshot.value;
print('Square: $result');
} else if (snapshot is FailureCommand<int>) {
final error = snapshot.error;
print('Error: $error');
}
});
// Execute the command with input
calculateSquareCommand.execute(4);
Use ValueListenableBuilder
to update the UI automatically:
final loginCommand = Command2<bool, String, String>(
(username, password) async {
if (username == 'admin' && password == 'password') {
return Success(true);
}
return Failure(Exception('Invalid credentials.'));
},
);
Widget build(BuildContext context) {
return Column(
children: [
ValueListenableBuilder<CommandState<bool>>(
valueListenable: loginCommand,
builder: (context, state, child) {
if (state is RunningCommand<bool>) {
return CircularProgressIndicator();
} else if (state is SuccessCommand<bool>) {
return Text('Login Successful!');
} else if (state is FailureCommand<bool>) {
return Text('Login Failed: ${(state as FailureCommand).error}');
}
return ElevatedButton(
onPressed: () => loginCommand.execute('admin', 'password'),
child: Text('Login'),
);
},
),
],
);
}
Cancel long-running commands gracefully:
Isolate? _uploadIsolate;
void _uploadAction() {
// uploading code...
}
final uploadCommand = Command0<void>(
() async {
_uploadIsolate = await Isolate.spawn(_uploadAction, []);
},
onCancel: () {
_uploadIsolate.kill();
},
);
// Start the upload
uploadCommand.execute();
// Cancel after 3 seconds
Future.delayed(Duration(seconds: 3), () {
uploadCommand.cancel();
});
Cancel long-running commands gracefully:
final calculateSquareCommand = Command1<int, int>(
(number) async {
if (number < 0) {
return Failure(Exception('Negative numbers are not allowed.'));
}
return Success(number * number);
},
);
calculateSquareCommand.addListener(() {
final message = calculateSquareCommand.value.when<String>(
data: (value) => 'Square: $value',
failure: (exception) => 'Error: ${exception?.message}',
running: () => 'Calculating...',
orElse: () => 'default value',
);
// Display the message in a snackbar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
});
// Execute the command with input
calculateSquareCommand.execute(4);
Widget build(BuildContext context) {
return Column(
children: [
ValueListenableBuilder<CommandState<bool>>(
valueListenable: loginCommand,
builder: (context, state, child) {
return state.when(
data: (_) => const Text('Login Successful!'),
running: () => const CircularProgressIndicator(),
failure: (error) => Text('Login Failed: $error'),
orElse: () => ElevatedButton(
onPressed: () => loginCommand.execute('admin', 'password'),
child: Text('Login'),
),
);
},
),
],
);
}
final calculateSquareCommand = Command1<int, int>(
(number) async {
if (number < 0) {
return Failure(Exception('Negative numbers are not allowed.'));
}
return Success(number * number);
},
);
calculateSquareCommand.addListener(() {
final message = calculateSquareCommand.value.when<String>(
data: (value) => 'Square: $value',
orElse: () => 'default value',
);
// Display the message in a snackbar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
});
// Execute the command with input
calculateSquareCommand.execute(4);
Notes
- The function ensures type safety by requiring
data to handle the
success` state explicitly. - The
orElse
callback is useful for dealing with unexpected states or adding default behavior.
- Simplified Collaboration: Encapsulation makes it easier for teams to work independently on UI and business logic.
- Reusability: Commands can be reused across different widgets or flows.
- Maintainability: Cleaner separation of concerns reduces technical debt.
We’d love your help in improving Result Command! Feel free to report issues, suggest features, or submit pull requests.