Show running clock on flutter
This is the same code which Albert had given, but in case you don't want to use the intl package, you can make these changes to this code:
import 'package:flutter/material.dart';
import 'dart:async';
void main () => runApp(MyApp());
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.red),
home: FlutterTimeDemo(),
);
}
}
class FlutterTimeDemo extends StatefulWidget{
@override
_FlutterTimeDemoState createState()=> _FlutterTimeDemoState();
}
class _FlutterTimeDemoState extends State<FlutterTimeDemo>
{
String _timeString;
@override
void initState(){
_timeString = "${DateTime.now().hour} : ${DateTime.now().minute} :${DateTime.now().second}";
Timer.periodic(Duration(seconds:1), (Timer t)=>_getCurrentTime());
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Fluter Test'),),
body:Center(
child: Text(_timeString, style: TextStyle(fontSize: 30),),
),
);
}
void _getCurrentTime() {
setState(() {
_timeString = "${DateTime.now().hour} : ${DateTime.now().minute} :${DateTime.now().second}";
});
}
}
The below uses the intl
plugin to format the time into MM/dd/yyyy hh:mm:ss
. Make sure to update your pubspec.yaml
.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Time Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Time Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _timeString;
@override
void initState() {
_timeString = _formatDateTime(DateTime.now());
Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text(_timeString),
),
);
}
void _getTime() {
final DateTime now = DateTime.now();
final String formattedDateTime = _formatDateTime(now);
setState(() {
_timeString = formattedDateTime;
});
}
String _formatDateTime(DateTime dateTime) {
return DateFormat('MM/dd/yyyy hh:mm:ss').format(dateTime);
}
}
Simplest solution:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class Clock extends StatelessWidget {
const Clock({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: Stream.periodic(const Duration(seconds: 1)),
builder: (context, snapshot) {
return Center(
child: Text(
DateFormat('MM/dd/yyyy hh:mm:ss').format(DateTime.now()),
),
);
},
),
);
}
}