Untitled

mail@pastecode.io avatar
unknown
dart
2 years ago
2.0 kB
0
Indexable
Never
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:taxi_driver/main.dart';
import 'package:taxi_driver/utils/Constants.dart';
import 'package:taxi_driver/utils/Extensions/app_common.dart';

class TimerScreen extends StatefulWidget {
  @override
  TimerScreenState createState() => TimerScreenState();
}

class TimerScreenState extends State<TimerScreen> {
  Timer? timer;
  int start = 30;
  late Duration durdef;

  DateTime dt1 = DateTime.now();
  //DateTime dt2 = DateFormat("dd/MM/yyyy HH:mm:ss").parse(IS_TIME2);

  @override
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    log('current:${DateTime.now()}');
    log('old:${DateTime.parse(sharedPref.getString(IS_TIME2)!)}');
    log('difference:${DateTime.now().difference(DateTime.parse(sharedPref.getString(IS_TIME2)!))}');
  }

  void startTimer() {
    const oneSec = const Duration(seconds: 1);
    timer = new Timer.periodic(
      oneSec,
      (Timer timer) {
        if (start == 0) {
          setState(() {
            timer.cancel();
          });
        } else {
          setState(() {
            start--;
          });
        }
      },
    );
  }

  @override
  void setState(fn) {
    if (mounted) super.setState(fn);
  }

  @override
  void dispose() {
    if(timer != null){
      timer!.cancel();
      sharedPref.setInt(IS_TIME, start);
      sharedPref.setString(IS_TIME2, DateTime.now().toString());
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Timer test")),
      body: Column(
        children: <Widget>[
          TextButton(
            onPressed: () {
              startTimer();
            },
            child: Text("start"),
          ),
          Text("$start")
        ],
      ),
    );
  }
}