Search code examples
flutterdartdatetimeflutter-layout

How to show time on page after pressing elevated button in flutter?


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


Solution

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