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...'); }
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Fantastisk!
Completion rate forbedret til 9.09
Understanding Futures
Stryg for at vise menuen
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...'); }
Tak for dine kommentarer!