25

I wanted to know if there is any way to show a real time clock in dart? Date and time (e.g 11/14/2018 19:34) and the time will continue to run.

Time can be taken from the device itself.

Aniket patel
  • 551
  • 1
  • 5
  • 17
OrrGorenn
  • 347
  • 1
  • 5
  • 15
  • 2
    https://medium.com/@NPKompleet/creating-an-analog-clock-in-flutter-iv-3995d914c86e you should check this article and adapt the code to do a digital one – Joaquín Nov 14 '18 at 17:39

3 Answers3

44

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);
  }
}
Albert Lardizabal
  • 6,548
  • 7
  • 34
  • 34
  • 18
    you should also call cancel in dispose() method else you will have memory leak. `timer = Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());` and call `timer.cancel()` in dispose() method. – CIF Dec 26 '19 at 16:26
  • Although, depending on the use case and opinions, this can either matter or not, this implementation has two potential flaws: 1. the clock can be up to one second behind the system clock 2. in a (rare, but possible) case of unlucky inaccuracy of `Timer` events (let's say: event _i_ at time 0 seconds 3 milliseconds and event _i + 1_ at time 0 seconds 999 milliseconds), a specific indication can last around two seconds (clock "hangs" for a second). I won't even mention rare and hardly notable inaccuracies, like a (around 1 second) delay reaction for manual clock adjustment in OS settings. – cubuspl42 Mar 26 '21 at 11:26
  • My point is that, unless it's unacceptable for a specific known reason (performance, I guess), it might be more correct to just "animate" the indication (`TickerProvider` family of solutions). – cubuspl42 Mar 26 '21 at 11:30
  • If you don't want to have the overhead of every-frame calculation, I'd still use <1s (for example 0.5s) periodic timer to mitigate point 2. – cubuspl42 Mar 26 '21 at 14:00
  • That is what I'm looking for. but we should use `dipose()` method. how to kill that timer when we close the app? I mean what kind of variable we should declare as a timer? and then call it in `dipose()`? – Abdullah Bahattab Nov 14 '21 at 21:26
39

Simplest solution:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class ClockWidget extends StatelessWidget {
  const ClockWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Stream.periodic(const Duration(seconds: 1)),
      builder: (context, snapshot) {
        return Text(DateFormat('MM/dd/yyyy hh:mm:ss').format(DateTime.now()));
      },
    );
  }
}

Put it anywhere you like.

Mehmet Esen
  • 6,156
  • 3
  • 25
  • 44
  • I think this is the most portable and scalable solution. I'd pass format and duration_time as constructor parameters. – Nebuchanazer Jan 28 '23 at 14:19
9

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}";
    });
  }
}
Nima Derakhshanjan
  • 1,380
  • 9
  • 24
  • 37
Soham Ghosh
  • 169
  • 2
  • 3