Katika Flutter, ikiwa unataka kufanya kitendo fulani baada ya maalum timeout, unaweza kutumia Future.delayed
chaguo la kukokotoa pamoja na async
na await
maneno muhimu. Hapa kuna mfano:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Timeout Example'),
),
body: Center(
child: ElevatedButton(
onPressed:() {
performActionWithTimeout();
},
child: Text('Perform Action with Timeout'),
),
),
);
}
Future<void> performActionWithTimeout() async {
print('Action started');
// Simulate a delay of 3 seconds
await Future.delayed(Duration(seconds: 3));
print('Action completed after timeout');
}
}
Katika mfano huu, wakati kifungo kinaposisitizwa, performActionWithTimeout
kazi inaitwa. Ndani ya chaguo hili la kukokotoa, tunatumia await Future.delayed(Duration(seconds: 3))
kutambulisha kuchelewa kwa sekunde 3. Baada ya kuchelewa, hatua imekamilika.
Unaweza kuchukua nafasi ya kitendo ndani performActionWithTimeout
ya chaguo la kukokotoa na operesheni unayotaka. Utaratibu huu timeout unaweza kukusaidia unapotaka kuchelewesha kitendo bila kuzuia uzi wa UI.
Kumbuka kwamba ikiwa kumekuwa na masasisho yoyote au vifurushi vipya vinavyohusiana na timeout baada Flutter ya sasisho langu la mwisho, unaweza kutaka kuchunguza chaguo hizo pia.