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.