Flutter ListView Timer Update Every Second

Flutter ListView Timer Update Every Second:This flutter turorial post ListView refresh data every second. This is use to Quiz app, Dream 11.

1) Flutter ListView Date Update Every second
2) Flutter ListView Dream 11
3) Fltter ListView Update Date

Flutter ListView Timer Update Every Second

Flutter ListView Timer Update Every Second

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

import 'package:intl/intl.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Tutorial'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var dateTimeList = [
    DateTime.now().add(Duration(hours: 50)),
    DateTime.now().add(Duration(hours: 28)),
    DateTime.now().add(Duration(hours: 18)),
    DateTime.now().add(Duration(hours: 2)),
    DateTime.now().subtract(Duration(hours: 5)),
    DateTime.now().subtract(Duration(hours: 20)),
    DateTime.now().subtract(Duration(hours: 32)),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: ListView.builder(
              padding: EdgeInsets.only(bottom: 80),
              physics: BouncingScrollPhysics(),
              itemCount: dateTimeList.length,
              itemBuilder: (context, index) => Container(
                padding: EdgeInsets.only(top: 70, bottom: 70),
                child: Center(
                  child: TimerView(
                    color: Colors.green,
                    fontSize: 20,
                    dateTime: dateTimeList[index],
                  ),
                ),
              ),
            )));
  }
}

class TimerView extends StatefulWidget {
  final DateTime dateTime;
  final double fontSize;
  final Color color;

  const TimerView({
    Key key,
    this.dateTime,
    this.fontSize = 14,
    this.color,
  }) : super(key: key);

  @override
  _TimerViewState createState() => _TimerViewState();
}

class _TimerViewState extends State<TimerView> {
  var timerCountDown = '00:00:00';
  Color colors = Colors.red;
  DateTime dateCheck;
  Timer timer;
  DateTime dateTimeStart;

  @override
  void initState() {
    if (widget.dateTime == null) {
      dateTimeStart = DateTime.now();
    } else {
      dateTimeStart = widget.dateTime;
    }
    if (widget.color != null) {
      colors = widget.color;
    }
    dateCheck = DateFormat('yyyy-MM-dd HH:mm:ss').parse(dateTimeStart.toString());
    setTime();
    super.initState();
  }

  void setTime() {
    if (dateCheck.difference(DateTime.now()).inSeconds < 0) {
      setState(() {
        timerCountDown = getData(dateTimeStart.millisecondsSinceEpoch);
      });
    } else {
      if (dateCheck.difference(DateTime.now()).inHours < 24) {
        timer?.cancel();
        timer = new Timer(new Duration(seconds: 1), () {
          setJustTime();
          setTime();
        });
      } else {
        final date = DateFormat('yyyy-MM-dd').parse(dateTimeStart.toString());
        final today = DateFormat('yyyy-MM-dd').parse(DateTime.now().toString());

        if (date.difference(today).inDays == 1) {
          colors  = Colors.yellow;
          timerCountDown = 'Tomorrow';
        } else {
          if (!mounted) return;
          setState(() {
            colors  = Colors.blueAccent;
            timerCountDown = DateFormat.E().format(date) +
                ', ' +
                DateFormat.d().format(date) +
                ' ' +
                DateFormat.MMM().format(date);
          });
        }
      }
    }
  }

  void setJustTime() {
    final seconds = dateCheck.difference(DateTime.now()).inSeconds;
    if (!mounted) return;
    setState(() {
      timerCountDown = secondsToHoursMinutesSeconds(seconds);
    });
  }

  String getData(int seconds) {
    var messageDate = new DateTime.fromMillisecondsSinceEpoch(seconds);
    var formatter = new DateFormat('yyyy-MM-dd');
    String formatted = formatter.format(messageDate);
    var finalDate = DateTime.parse(formatted);
    var days = DateTime.now().difference(finalDate).inDays;
    if (days == 0) {
      if (DateTime.now().difference(messageDate).inHours > 0) {
        colors  = Colors.black54;
        return '${DateTime.now().difference(messageDate).inHours} hours ago.';
      } else if (DateTime.now().difference(messageDate).inMinutes > 0) {
        return '${DateTime.now().difference(messageDate).inMinutes} minutes ago.';
      } else {
        return 'Few seconds ago.';
      }
    } else if (days == 1) {
      colors  = Colors.red;
      return 'Yesterday ${DateFormat.jm().format(messageDate)}';
    } else if (days >= 2 && days <= 6) {
      return DateFormat.EEEE().format(messageDate) +
          " " +
          DateFormat.jm().format(messageDate);
    } else {
      return DateFormat.yMd().add_jm().format(messageDate);
    }
  }

  String secondsToHoursMinutesSeconds(int seconds) {
    var hour = seconds ~/ 3600;
    var minute = (seconds % 3600) ~/ 60;
    var second = (seconds % 3600) % 60;

    final hourUpdate = hour < 10 ? '0$hour' : '$hour';
    final minuteUpdate = minute < 10 ? '0$minute' : '$minute';
    final secondUpdate = second < 10 ? '0$second' : '$second';
    return hourUpdate + ' : ' + minuteUpdate + ' : ' + secondUpdate;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(children: <Widget>[
          Text(
            timerCountDown,
            style: TextStyle(
              fontSize: widget.fontSize,
              fontWeight: FontWeight.bold,
              color: colors,
            ),
          ),
        ]));
  }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in