I have a question about the Future generic type below
The code in the book is:
print('Before the future');
final myFuture = Future<int>.delayed(
Duration(seconds: 1),
() => 42,
)
.then(
(value) => print('Value: $value'),
)
.catchError(
(Object error) => print('Error: $error'),
)
.whenComplete(
() => print('Future is complete'),
);
print('After the future');
myFuture is an instance of Future class. The type is inferred as Future<void>. But the right hand side is written as Future<int>.delayed( … How can this be possible? Or how do I understand the code above?
The Future<int>.delayed constructor returns a Future<int>. The int refers to the value returned by () => 42. Since Dart can infer this type you can use Future.delayed directly without specifying the type. It’s still inferred to be Future<int>.
The confusion perhaps comes from the methods that are called on that returned future. Let me rewrite the code like so:
final myFuture = Future<int>.delayed(
Duration(seconds: 1),
() => 42,
);
final thenFuture = myFuture.then(
(value) => print('Value: $value'),
);
final catchErrorFuture = thenFuture.catchError(
(Object error) => print('Error: $error'),
);
final whenCompleteFuture = catchErrorFuture.whenComplete(
() => print('Future is complete'),
);
The then method returns a Future<void>. So do the catchError and whenComplete methods. That’s why you see the inferred Future<void> for the original myFuture. The myFuture in my refactored code above has the expected Future<int> type.