本文实例为大家分享了flutter实现倒计时加载页面的具体代码,供大家参考,具体内容如下
效果图
实现步骤
1、pubspec.yaml中添加依赖 flustars,该包的TimelineUtil和TimerUtil类可以实现计时功能
dependencies:
flustars: ^0.3.3
!注意空格哦
2、代码实现
初始化TimerUtil
late TimerUtil util;
double current_time = 0;
void initState() {
super.initState();
util = new TimerUtil(mInterval: 18, mTotalTime: 5000);
util.setOnTimerTickCallback((millisUntilFinished) {
setState(() {
//每次时间间隔回调,把每次当前总时间ms除以1000就是秒
current_time = millisUntilFinished / 1000;
//倒计时结束时 跳转到首页 当然也可以等待资源加载完成再跳转
if (current_time == 0) {
//跳转到首页
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage()));
}
});
});
构造页面
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Image.asset('images/2.0/beijing.jpg'),
Container(
alignment: Alignment.centerRight,
child: SizedBox(
height: 50,
width: 50,
child: Stack(
children: [
Center(child: CircularProgressIndicator(
value: current_time == 5.0 ? 0 : (5 - current_time) / 5,
),),
Center(child: Text('${current_time.toInt()}'),)
],)
),
),
],
));
}
完整代码
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LoadingPage(),
);
}
}
class LoadingPage extends StatefulWidget {
const LoadingPage({Key? key}) : super(key: key);
@override
_LoadingPageState createState() => _LoadingPageState();
}
class _LoadingPageState extends State<LoadingPage> {
late TimerUtil util; //计时对象
double current_time = 0; //当前时间
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Image.asset('images/2.0/beijing.jpg'),
Container(
alignment: Alignment.centerRight,
child: SizedBox(
height: 50,
width: 50,
child: Stack(
children: [
Center(child: CircularProgressIndicator(
value: current_time == 5.0 ? 0 : (5 - current_time) / 5,
),),
Center(child: Text('${current_time.toInt()}'),)
],)
),
),
],
));
}
@override
void initState() {
super.initState();
util = new TimerUtil(mInterval: 18, mTotalTime: 5000);
util.setOnTimerTickCallback((millisUntilFinished) {
setState(() {
//每次时间间隔回调,把每次当前总时间ms除以1000就是秒
current_time = millisUntilFinished / 1000;
//倒计时结束时 跳转到首页 当然也可以等待资源加载完成再跳转
if (current_time == 0) {
//跳转到首页
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage()));
}
});
});
//开始倒计时
util.startCountDown();
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HomePage'),
),
);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。