About Future generic type

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?

2 Likes

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.

2 Likes

Thanks @suragch , your re-written code clears my thought.

2 Likes

Thank you @ellery for your question! We appreciate your active participation in the community. Keep up the great work, and don’t hesitate to share more of your questions and insights. Your contributions make our community stronger and more vibrant. Happy learning!

Thank you, @suragch , for your prompt and helpful response to the question. Your expertise is greatly appreciated!