如何在Flutter中创建带3秒计时器的启动页并跳转首页?
实现Flutter 3秒自动跳转启动页
下面是一个简单易懂的实现示例,启动页包含图标、文字,3秒后自动跳转到首页:
import 'package:flutter/material.dart'; import 'dart:async'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: SplashScreen(), ); } } // 启动页组件 class SplashScreen extends StatefulWidget { const SplashScreen({super.key}); @override State<SplashScreen> createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { @override void initState() { super.initState(); // 启动3秒计时器,时间到后跳转首页 Timer(const Duration(seconds: 3), () { Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => const HomePage()), ); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ // 应用图标(可替换为自定义图标) const Icon( Icons.android, size: 120, color: Colors.green, ), const SizedBox(height: 30), // 应用名称 const Text( "我的Flutter应用", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black87, ), ), const SizedBox(height: 15), // 加载提示文字 Text( "正在加载...", style: TextStyle( fontSize: 16, color: Colors.grey[600], ), ), ], ), ), ); } } // 首页组件 class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("首页"), ), body: const Center( child: Text("欢迎来到首页!"), ), ); } }
关键部分说明:
- 计时器逻辑:在
initState生命周期方法中初始化Timer,设置3秒延迟,时间到后用Navigator.pushReplacement跳转首页(该方法会移除启动页路由,避免用户返回时回到启动页) - UI布局:通过
Column垂直排列图标与文字,Center让整体内容居中,SizedBox控制元素间距 - 自定义替换:你可以把示例中的
Icons.android替换成自己的应用图标(比如用Image.asset加载本地图标文件),文字内容也可根据需求修改
内容的提问来源于stack exchange,提问作者user22213824
相关产品推荐
相关产品推荐

