Delays and Future.delayed
When you need to introduce a pause or simulate a time-consuming operation in Dart asynchronous code, you can use Future.delayed. This constructor creates a Future that completes after a specified duration. It is commonly used to mimic network requests, database calls, or any operation where you want to wait before continuing your code.
The Future.delayed constructor takes two parameters:
- The first parameter is a
Durationobject, which specifies how long the delay should be; - The second parameter is an optional callback function that returns the value with which the
Futurewill complete.
By using await with Future.delayed, you can pause the execution of an async function for a given amount of time, making your code easier to read and control.
main.dart
123456789101112131415import 'dart:async'; Future<String> fetchData() async { // Simulate a 2-second network delay return await Future.delayed( Duration(seconds: 2), () => 'Data loaded', ); } void main() async { print('Requesting data...'); String result = await fetchData(); print(result); }
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Чудово!
Completion показник покращився до 9.09
Delays and Future.delayed
Свайпніть щоб показати меню
When you need to introduce a pause or simulate a time-consuming operation in Dart asynchronous code, you can use Future.delayed. This constructor creates a Future that completes after a specified duration. It is commonly used to mimic network requests, database calls, or any operation where you want to wait before continuing your code.
The Future.delayed constructor takes two parameters:
- The first parameter is a
Durationobject, which specifies how long the delay should be; - The second parameter is an optional callback function that returns the value with which the
Futurewill complete.
By using await with Future.delayed, you can pause the execution of an async function for a given amount of time, making your code easier to read and control.
main.dart
123456789101112131415import 'dart:async'; Future<String> fetchData() async { // Simulate a 2-second network delay return await Future.delayed( Duration(seconds: 2), () => 'Data loaded', ); } void main() async { print('Requesting data...'); String result = await fetchData(); print(result); }
Дякуємо за ваш відгук!