skip to Main Content

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)
        ],
      );
}

3

Answers


  1. You can use:

    countdownDuration.inSeconds 
    

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

    Update: You can calculate your duration in hours like this:

    countdownDuration.inMinutes/60
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. If you want to encode a duration of 1h39m to a floating-point value of 1.39, you’re just taking the number of leftover minutes, dividing it by 100, and adding the number of hours:

    double encodeDurationToDouble(Duration duration) {
      var hours = duration.inHours;
      var minutes = duration.inMinutes % 60;
    
      return hours + minutes / 100;
    }
    
    void main() {
      var durations = [
        const Duration(hours: 0, minutes: 59),
        const Duration(hours: 3, minutes: 7),
        const Duration(hours: 25, minutes: 12),
      ];
    
      // Prints:
      // 0.59
      // 3.07
      // 25.12
      for (var d in durations) {
        print(encodeDurationToDouble(d));
      }
    }
    

    Although be aware of fundamental inaccuracies when using floating-point numbers.

    You alternatively could encode 1h39m as an integer 139 by multiplying the number of hours by 100 and then adding the leftover minutes:

    int encodeDurationToInt(Duration duration) {
      var hours = duration.inHours;
      var minutes = duration.inMinutes % 60;
      return hours * 100 + minutes;
    }
    

    Or you could just use duration.inMinutes to obtain the total number of minutes instead of encoding it in uncommon ways. You still haven’t explained why you want duration encoded in such a way, so it’s unclear why you can’t just use that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search