Dart Future.error()
Syntax & Examples
Future.error constructor
The `Future.error` constructor in Dart creates a future that completes with an error.
Syntax of Future.error
The syntax of Future.Future.error constructor is:
Future.error(Object error, [ StackTrace stackTrace ])This Future.error constructor of Future creates a future that completes with an error.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
error | required | An object representing the error that the future will complete with. |
stackTrace | optional | A stack trace associated with the error, used for debugging purposes. |
✐ Examples
1 Creating a future with a simple error
In this example,
- We create a future using the `Future.error` constructor and pass a string as the error object.
- We handle the error using the `catchError` method and print the error message.
Dart Program
void main() {
Future<void>.error('Something went wrong!')
.catchError((error) {
print('Error: $error');
});
}Output
Error: Something went wrong!
2 Creating a future with a custom exception and stack trace
In this example,
- We create a future using the `Future.error` constructor and pass an exception and current stack trace as arguments.
- We handle the error using the `catchError` method and print both the error and the stack trace.
Dart Program
void main() {
Future<int>.error(Exception('Custom Exception'), StackTrace.current)
.catchError((error, stackTrace) {
print('Error: $error\nStackTrace: $stackTrace');
});
}Output
Error: Exception: Custom Exception
StackTrace: Error
at get current (https://storage.googleapis.com/nnbd_artifacts/3.3.4
dart_sdk.js:140009:30)
at Object.main$0 [as main] (blob:null
5dcf70dd-e929-4d4e-b70c-38dd1346c258:55:83)
at Object.main$ [as main] (blob:null
5dcf70dd-e929-4d4e-b70c-38dd1346c258:52:10)
at blob:null/5dcf70dd-e929-4d4e-b70c-38dd1346c258:95:26
at Object.execCb (https://dartpad.dev/require.js:5:16727)
at e.check (https://dartpad.dev/require.js:5:10499)
at e.<anonymous> (https://dartpad.dev/require.js:5:12915)
at https://dartpad.dev/require.js:5:1542
at https://dartpad.dev/require.js:5:13376
at each (https://dartpad.dev/require.js:5:1020)
at e.emit (https://dartpad.dev/require.js:5:13344)
at e.check (https://dartpad.dev/require.js:5:11058)
at e.enable (https://dartpad.dev/require.js:5:13242)
at e.init (https://dartpad.dev/require.js:5:9605)
at a (https://dartpad.dev/require.js:5:8305)
at Object.completeLoad (https://dartpad.dev/require.js:5:15962)
at HTMLScriptElement.onScriptLoad (https://dartpad.dev
require.js:5:16882)Summary
In this Dart tutorial, we learned about Future.error constructor of Future: the syntax and few working examples with output and detailed explanation for each example.