Understanding Futures
When you work with Dart, you will often encounter situations where some operations take time to complete. Examples include fetching data from the internet, reading a file, or waiting for user input. In these cases, you do not want your program to stop and wait for the operation to finish before moving on. Instead, you want your program to continue running and handle the result when it becomes available. This is where a Future comes in.
A Future in Dart represents a value that may not be available yet, but will be provided at some point in the future. Futures are the foundation of asynchronous programming in Dart. They allow you to write code that can start an operation and then react to its result later, without blocking the rest of your program. Using Futures is essential for keeping your applications responsive and efficient, especially when dealing with tasks that take an unpredictable amount of time.
main.dart
1234567891011121314import 'dart:async'; Future<int> fetchNumber() { return Future.delayed(Duration(seconds: 2), () { return 42; }); } void main() { fetchNumber().then((value) { print('The number is $value'); }); print('Waiting for the number...'); }
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Genial!
Completion tasa mejorada a 9.09
Understanding Futures
Desliza para mostrar el menú
When you work with Dart, you will often encounter situations where some operations take time to complete. Examples include fetching data from the internet, reading a file, or waiting for user input. In these cases, you do not want your program to stop and wait for the operation to finish before moving on. Instead, you want your program to continue running and handle the result when it becomes available. This is where a Future comes in.
A Future in Dart represents a value that may not be available yet, but will be provided at some point in the future. Futures are the foundation of asynchronous programming in Dart. They allow you to write code that can start an operation and then react to its result later, without blocking the rest of your program. Using Futures is essential for keeping your applications responsive and efficient, especially when dealing with tasks that take an unpredictable amount of time.
main.dart
1234567891011121314import 'dart:async'; Future<int> fetchNumber() { return Future.delayed(Duration(seconds: 2), () { return 42; }); } void main() { fetchNumber().then((value) { print('The number is $value'); }); print('Waiting for the number...'); }
¡Gracias por tus comentarios!