使用dart语言实现,在界面中每一秒刷新并显示当前时间
时间: 2024-05-24 10:13:36 浏览: 188
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _currentTime;
@override
void initState() {
super.initState();
_currentTime = _getCurrentTime();
// Refresh every second
Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_currentTime = _getCurrentTime();
});
});
}
String _getCurrentTime() {
var now = new DateTime.now();
var formatter = new DateFormat('HH:mm:ss');
String formattedTime = formatter.format(now);
return formattedTime;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Time App',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Time App'),
),
body: Center(
child: Text(
'Current Time: $_currentTime',
style: TextStyle(fontSize: 30),
),
),
),
);
}
}
阅读全文