Flutter Countdown Timer

0 votes

How can I do to put the value passed in the construction, to make a timer that rounds to the first decimal and shows at the child text of my RaisedButton? I've tried but without luck. I manage to make work the callback function with a simple Timer but no periodic and with no update of value in real time in the text...

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

class TimerButton extends StatefulWidget {
  final Duration timerTastoPremuto;


  TimerButton(this.timerTastoPremuto);

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

class _TimerButtonState extends State<TimerButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(5.0),
      height: 135.0,
      width: 135.0,
      child: new RaisedButton(
        elevation: 100.0,
        color: Colors.white.withOpacity(.8),
        highlightElevation: 0.0,
        onPressed: () {
          int _start = widget.timerTastoPremuto.inMilliseconds;

          const oneDecimal = const Duration(milliseconds: 100);
          Timer _timer = new Timer.periodic(
              oneDecimal,
                  (Timer timer) =>
                  setState(() {
                    if (_start < 100) {
                      _timer.cancel();
                    } else {
                      _start = _start - 100;
                    }
                  }));

        },
        splashColor: Colors.red,
        highlightColor: Colors.red,
        //shape: RoundedRectangleBorder e tutto il resto uguale
        shape: BeveledRectangleBorder(
            side: BorderSide(color: Colors.black, width: 2.5),
            borderRadius: new BorderRadius.circular(15.0)),
        child: new Text(
          "$_start",
          style: new TextStyle(fontFamily: "Minim", fontSize: 50.0),
        ),
      ),
    );
  }
}

Mar 30, 2023 in Flutter by Ashwini
• 5,430 points
727 views

1 answer to this question.

0 votes

In your code, the variable _start is defined inside the onPressed callback function, so it is not accessible outside of it. To display the current value of the timer in the Text widget of your RaisedButton, you need to move the definition of _start to the State object of your TimerButton widget.

Here's an updated version of your code that should work as you described:

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

class TimerButton extends StatefulWidget {
  final Duration timerTastoPremuto;

  TimerButton(this.timerTastoPremuto);

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

class _TimerButtonState extends State<TimerButton> {
  int _start;

  Timer _timer;

  @override
  void initState() {
    super.initState();
    _start = widget.timerTastoPremuto.inMilliseconds;
  }

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

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(5.0),
      height: 135.0,
      width: 135.0,
      child: new RaisedButton(
        elevation: 100.0,
        color: Colors.white.withOpacity(.8),
        highlightElevation: 0.0,
        onPressed: () {
          const oneDecimal = const Duration(milliseconds: 100);
          _timer = new Timer.periodic(
            oneDecimal,
            (Timer timer) => setState(() {
              if (_start < 100) {
                timer.cancel();
              } else {
                _start = _start - 100;
              }
            }),
          );
        },
        splashColor: Colors.red,
        highlightColor: Colors.red,
        shape: BeveledRectangleBorder(
          side: BorderSide(color: Colors.black, width: 2.5),
          borderRadius: new BorderRadius.circular(15.0),
        ),
        child: new Text(
          "${(_start / 1000.0).toStringAsFixed(1)}",
          style: new TextStyle(fontFamily: "Minim", fontSize: 50.0),
        ),
      ),
    );
  }
}

In this version, the _start variable is defined as a member variable of the _TimerButtonState class, and its initial value is set in the initState method using the widget.timerTastoPremuto value passed from the constructor. The _timer variable is also defined as a member variable, so it can be canceled in the dispose method to prevent any memory leaks.

The Text widget inside the RaisedButton now displays the value of _start divided by 1000 and rounded to one decimal place using the toStringAsFixed method.

Finally, in the onPressed callback function, the _timer variable is set to a new Timer.periodic instance, and the setState method is called on each tick to update the value of _start and trigger a rebuild of the RaisedButton.

To know more, join our Flutter Certification Course today.

answered Mar 30, 2023 by pooja

Related Questions In Flutter

0 votes
1 answer

Linking 3 Flutter Projects in One Flutter Project

Yes, it is possible to combine multiple ...READ MORE

answered Mar 20, 2023 in Flutter by vinayak
333 views
0 votes
1 answer

Flutter Projects & Android X Migration Issues

Migrating to AndroidX can be a frustrating ...READ MORE

answered Mar 20, 2023 in Flutter by Tej
261 views
0 votes
1 answer

How to change flutter project name and id?

Yes, it is possible to change the ...READ MORE

answered Mar 20, 2023 in Flutter by pooja
2,813 views
0 votes
1 answer
0 votes
1 answer

Is Flutter/Dart valuable in the professional setting?

Yes, Flutter and Dart are valuable skills ...READ MORE

answered Mar 21, 2023 in Flutter by vani
252 views
0 votes
1 answer

Dart_LoadScriptFromKernel: The binary program does not contain 'main'.

Hi@akhtar, You need to add the main() function ...READ MORE

answered Jul 21, 2020 in Others by MD
• 95,440 points
3,220 views
0 votes
1 answer

How to install Dart in Windows system?

Hi@akhtar, Dart is the programming language used to code Flutter apps. ...READ MORE

answered Jul 21, 2020 in Others by MD
• 95,440 points
787 views
0 votes
1 answer

flutter run: No connected devices

Hi@akhtar, To prepare to run and test your ...READ MORE

answered Jul 21, 2020 in Others by MD
• 95,440 points
3,838 views
0 votes
1 answer

How to create a function in Dart language?

Hi@akhtar, There are many function types available in ...READ MORE

answered Jul 22, 2020 in Others by MD
• 95,440 points
514 views
0 votes
1 answer

Flutter Outline Shows "Nothing to show" in android studio

There are a few possible solutions for ...READ MORE

answered Mar 30, 2023 in Flutter by vishalini
2,165 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP