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?

1 Like

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.

1 Like

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

1 Like
{"ft_lang_label":"__label__en","ft_lang_prob":0.7371421,"math_prob":0.91614884,"size":1496,"snap":"2023-14-2023-23","text_gpt3_token_len":346,"char_repetition_ratio":0.17024128,"word_repetition_ratio":0.07339449,"special_character_ratio":0.26671124,"punctuation_ratio":0.17948718,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9723823,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-29T04:15:18Z\",\"WARC-Record-ID\":\"<urn:uuid:c0faa93a-bf70-4d70-a396-4de34c993144>\",\"Content-Length\":\"28153\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:fb30bf5a-9a10-4f1a-8e4a-b5cb505b0a29>\",\"WARC-Concurrent-To\":\"<urn:uuid:56a1c976-782d-4c84-834b-3482c2d1efbe>\",\"WARC-IP-Address\":\"52.44.64.215\",\"WARC-Target-URI\":\"https://forums.kodeco.com/t/about-future-generic-type/184765\",\"WARC-Payload-Digest\":\"sha1:4OCTYD3XQ3XWWHAPO25O5ACD2OE4OLP3\",\"WARC-Block-Digest\":\"sha1:JITHQFLXILIAEVY7ISVOCQXL4TPK7ZSN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296948932.75_warc_CC-MAIN-20230329023546-20230329053546-00376.warc.gz\"}"}