I have tried many times to build an elevated button to show live time and date on flutter screen but unfortunately I couldn’t do this. Can any programmer help me ??
This is my code :
ElevatedButton(
onPressed: () {
setState(() {
final date =
DateFormat('yyyy').format(DateTime.now()).toString();
});
},
child: Text(
'Show Time',
style: TextStyle(fontSize: 20),
),
),
SizedBox(
height: 150,
),
Text('Date is' date),
],
CodePudding user response:
You need to use state variable to show the time. And the DateFormat will be DateFormat('hh:MM:ss')
. You can find the full list of DateFormat
class TimerH extends StatefulWidget {
TimerH({Key? key}) : super(key: key);
@override
State<TimerH> createState() => _TimerHState();
}
class _TimerHState extends State<TimerH> {
String time = "";
DateTime dateTime = DateTime.now();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
ElevatedButton(
onPressed: () {
dateTime = DateTime.now();
setState(() {
time = DateFormat('hh:MM:ss').format(DateTime.now()).toString();
});
},
child: Text(
'Show Time',
style: TextStyle(fontSize: 20),
),
),
SizedBox(
height: 150,
),
Text('Date is' time),
Text("${dateTime.hour} ${dateTime.minute} ${dateTime.second}")
],
),
);
}
}
CodePudding user response:
The problem is that you are declaring the date
variable inside the setState()
! That makes it a local variable that you can't use anywhere else, outside this setState()
. Thus, it can't be put in your Widget tree and displayed on the screen, for example.
And another problem is that it's final! If you want it to display different times and/or dates each time you press the button, the variable must be mutable, i.e. not final or const.