乐闻世界logo
搜索文章和话题

How to run code after some delay in Flutter?

1个答案

1

In Flutter, if you need to delay code execution, you can use Dart's Future.delayed method. This method allows you to set a delay and then execute the relevant code.

Here's a simple example demonstrating how to use Future.delayed in a Flutter application:

dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); } } class HomePage extends StatefulWidget { _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { String _message = "Initial message"; void initState() { super.initState(); _delayedFunction(); } void _delayedFunction() { Future.delayed(Duration(seconds: 5), () { setState(() { _message = "Message updated after 5 seconds"; }); }); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Delayed Execution Example"), ), body: Center( child: Text(_message), ), ); } }

In this example, after the app launches, _delayedFunction() is called within the initState() method. This function uses Future.delayed to set a 5-second delay. Once the delay completes, it updates the state variable _message, triggering a widget rebuild and displaying the new message on the screen.

This approach is ideal for scenarios where immediate response is unnecessary, such as initialization loading animations or delayed responses following user interactions.

2024年7月1日 12:19 回复

你的答案