Home > database >  How to convert time value into double/int value?
How to convert time value into double/int value?

Time:06-30

Is there a way to convert time value into double or int? Here's is the code to my timer which I wanted to change into double value because I wanted it to hold the time value as a double so later on I want to calculate the total price based on the data from the timer.I've tried the convert method but its seems to failed and I try to search other solution but mostly it was python language solution.

import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:latestfyp/QR/qrexit.dart';
import 'package:path/path.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';

import '../QR/qrenter.dart';

class CountdownPage extends StatefulWidget {
  const CountdownPage({Key? key}) : super(key: key);

  @override
  State<CountdownPage> createState() => _CountdownPageState();
}

class _CountdownPageState extends State<CountdownPage> {
  Barcode? result;
  QRViewController? controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  dynamic data;
  dynamic data1;
  double test = 0.000083333;
  var total;
  static const countdownDuration = Duration(seconds: 0);
  Duration duration = Duration();
  Timer? timer;
  bool isCountdown = true;
  void initState(){
    super.initState();
    startTimer();
    reset();
  }
  // @override
  // void reassemble() {
  //   super.reassemble();
  //   if (Platform.isAndroid) {
  //     controller!.pauseCamera();
  //   }
  //   controller!.resumeCamera();
  // }
  void reset(){
    if (isCountdown){
    setState(() => duration = countdownDuration);
  }
    else{
      setState(() => duration = Duration());
    }
    }
  void addTime(){
    final addSeconds = isCountdown? 1  : 1;
    setState(() {
      final seconds = duration.inSeconds   addSeconds;
      if(seconds <0) {
        timer?.cancel();
      }
      else{
        duration = Duration(seconds: seconds);
      }
    });

  }
  void startTimer(){
    timer = Timer.periodic(Duration(seconds: 1),(_) => addTime());

  }
  void stopParking(BuildContext context)   {
    Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => QR()));
  }

  Future<void> _navigateAndDisplaySelection(BuildContext context) async {
    // Navigator.push returns a Future that completes after calling
    // Navigator.pop on the Selection Screen.
    final result = await Navigator.push(
      context,
      // Create the SelectionScreen in the next step.
      MaterialPageRoute(builder: (context) => const QR()),
    );
  }

  void stopTimer({bool resets = true}){
    // data = duration *60;
    if (resets){
      reset();
    }

    setState(() => timer?.cancel());

  }


  @override
  Widget build(BuildContext context) => Scaffold(
    body: Center(child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        buildTime(),
        // const SizedBox(height: 70),
        buildButtons(),
        // TextButton(
        //   child: Text('Scan to End Parking Time'),
        //   onPressed: (){
        //     Navigator.push(context,MaterialPageRoute(builder: (context) => QR()));
        //   },
        // ),

      ],
    )),
  );

  Widget buildButtons(){

    final isRunning = timer == null? false : timer!.isActive;
    // final isCompleted = duration.inSeconds == 0;

    return isRunning
        ?Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextButton(
          child: Text('Start timer'),
          onPressed:(){startTimer();},
        ),
        TextButton(
          child: Text('Stop'),
          onPressed:(){
            if(isRunning){
              stopTimer(resets: false,);
            }

          },
        ),
        TextButton(
          child: Text('Cancel'),
          onPressed: stopTimer,
        ),
        TextButton(
          child: Text('Scan to end parking'),
          // onPressed: () => QR(),
          onPressed: (){
            data = timer;
            data1 = duration * 60 * 60;
            total = data1.toString() ;
            Navigator.push(this.context,MaterialPageRoute(builder: (context) => QRExit(price: total.toString(), duration:data.toString())));
          },
        ),
      ],
    )
        :TextButton(
        child: Text('Start Timer'),
        onPressed:(){
          startTimer();
        }
    );

  }



  Widget buildTime() {
    String twoDigits(int n) => n.toString().padLeft(2,'0');
    // final hours = twoDigits(duration.inHours);
    // final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // buildTimeCard(time: hours , header: 'Hours'),
        // const SizedBox(width: 8),
        // buildTimeCard(time: minutes , header: 'Minutes'),
        const SizedBox(width: 8),
        buildTimeCard(time: seconds , header: 'Seconds'),
      ],
    );
  }
  Widget qr(){
    return Scaffold(
      body: Column(
        children: <Widget>[
          Expanded(flex: 4, child: _buildQrView(this.context)),
          Expanded(
            flex: 1,
            child: FittedBox(
              fit: BoxFit.contain,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.all(25),
                        child: SizedBox(
                          height: 15,
                          width: 55,
                          child: ElevatedButton(
                            onPressed: ()  async{
                              await controller?.resumeCamera();

                            },
                            child: Text('Scan', style: TextStyle(fontSize: 10)),
                          ),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildQrView(BuildContext ctx) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    var scanArea = (MediaQuery.of(ctx).size.width < 400 ||
        MediaQuery.of(ctx).size.height < 400)
        ? 150.0
        : 300.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor: Colors.red,
          borderRadius: 10,
          borderLength: 30,
          borderWidth: 10,
          cutOutSize: scanArea),
      onPermissionSet: (ctrl, p) => _onPermissionSet(ctx, ctrl, p),

    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
        // data = result;
        if(result != null){
          // MaterialPageRoute(builder: (context) => Test());
          Navigator.push(
              this.context,
              MaterialPageRoute(builder: (context) => const CountdownPage()));

        }
      });
    });
  }

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    log('${DateTime.now().toIso8601String()}_onPermissionSet $p');
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('no Permission')),
      );
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }


  Widget buildTimeCard({required String time, required String header}) =>
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Colors.black,
            ),
            child:
            Text(
              time,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.white,
                fontSize: 60,
              ),
            ),
          ),
          const SizedBox(height: 20),
          Text(header)
        ],
      );
}

CodePudding user response:

You can use:

countdownDuration.inSeconds 

which will return the whole Duration in seconds, also there are other units available like minutes, microseconds, and hours.

CodePudding user response:

Here is what I understand:

    // convert hours & min into double
  String getTime(int hours, int minutes) {
    String hour = hours.toString();
    String minute = minutes.toString();
    if (hours < 10) {
      hour = '0$hours';
    }
    if (minutes < 10) {
      minute = '0$minutes';
    }
    return '$hour.$minute';
  }

You can change this according to your need and convert a string into double/int.

  • Related