Câu hỏi phỏng vấn Flutter
Câu hỏi

How is whenCompleted() different from then() in Futurs?

Câu trả lời

The whenCompleted() and then() methods in Dart's Future class are used to handle the completion of a Future, but they have some key differences:

  1. Callback function: then() takes a callback function that is executed when the Future completes successfully, while whenCompleted() takes a callback function that is executed regardless of whether the Future completes successfully or with an error[1][2].

  2. Return value: then() returns a new Future that completes with the return value of the callback function, while whenCompleted() returns the original Future that it was called on[1][2].

  3. Error handling: When using then(), you can chain multiple then() calls together to handle the result of the previous Future. If an error occurs in one of the then() callbacks, it will be passed to the next error handler (either another then() with an error handler or a catchError() call). With whenCompleted(), any errors that occur in the callback function are not propagated to the returned Future[1][2].

Here's an example to illustrate the differences:

dart Copy
Future<String> fetchData() {
  return Future.delayed(Duration(seconds: 2), () => 'Data');
}

void main() {
  fetchData()
    .then((data) {
      prin...
middle

middle

Gợi ý câu hỏi phỏng vấn

expert

Explain Stateful Widget Lifecycle in details

middle

Do you know what Ephemeral state means?

middle

When do we use double.INFINITY ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào