I'm new to flutter. I'm trying to make a simple automatically updating time.

I tried with RefreshIndicator but it didn't work for me. What is the correct way to make it update per second? Is it possible to make it update with the setState in the bottomNavigationBar by making recursion function?

enter image description here

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

int Currentindex = 0 ;

late String time1;
var today = DateTime.now();

String time()
{
  today = DateTime.now();
   time1 = (today.hour.toString()+" : "+today.minute.toString()+" : "+today.second.toString());
  return time1;
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {

  @override

  Widget build(BuildContext context) {

    return MaterialApp( debugShowCheckedModeBanner : false ,
      home: Firstpage()
      ,);
  }
}

class Firstpage extends StatefulWidget {
  const Firstpage({Key? key}) : super(key: key);

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

class _FirstpageState extends State<Firstpage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp( debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Currentindex == 0 ? Column(mainAxisAlignment: MainAxisAlignment.center, children: [ElevatedButton(onPressed: (){
            setState(() {
              Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context)
              {
                return SecondPage();
              }
              )
              );
            });
          }, child: Text("Click me"))],

          ) : Currentindex == 1 ? Column(mainAxisAlignment : MainAxisAlignment.center,children: [Text(time(),style: TextStyle(fontSize: 80),)], ):
          SizedBox()
        ) ,
      bottomNavigationBar: BottomNavigationBar(items: const [
        BottomNavigationBarItem(label: "Icecream",icon: Icon(Icons.icecream , color: Colors.white,)),
        BottomNavigationBarItem(label: "Time",icon: Icon(Icons.access_time , color: Colors.white,))],
      backgroundColor: Colors.blue,
      onTap: (int index){setState(() {

        if(Currentindex == 1){today = DateTime.now();;}

        Currentindex = index;
      });},
      ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  const SecondPage({Key? key}) : super(key: key);

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

class _SecondPageState extends State<SecondPage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp( debugShowCheckedModeBanner: false,
      home: Scaffold( backgroundColor: Colors.grey,
        appBar: AppBar(title: Text("Cool"),backgroundColor: Colors.transparent,),
        body: Center(
          child: Column(crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
            children: [ElevatedButton(onPressed: (){
              setState(() {
                Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){return Firstpage();
                }
                )
                );
              }
              );
            }, child: Text("Go back"), style: ElevatedButton.styleFrom(primary: Colors.yellow , onPrimary: Colors.orange),)],
          ),
        ),
      )
    );
  }
}


Solution 1: Saichi Okuma

See if it helps. Ideally this kind of widget (that updates all the time) should be in leafs and by themselves, to avoid rebuilding parts of your tree unnecessarily.

class MyWidget extends StatefulWidget {
  const MyWidget();

  @override
  State<StatefulWidget> createState() => _MyWidget();
}
class _MyWidget extends State<MyWidget> {
  String lastTime = '';

  @override
  initState() {
    super.initState();
    timeUpdate.listen((time) => setState(() => lastTime = time ));
  }

  String get time => DateTime.now().toString();

  Stream<String> get timeUpdate async* {
    while(true) {
      await Future.delayed(Duration(seconds: 1));
     yield time;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      time,
      style: Theme.of(context).textTheme.headline4,
    );
  }
}


Solution 2: Minjin Gelegdorj

If you're trying to make a digital clock looking thing, try this:

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

class ClockWidget extends StatelessWidget {

  const ClockWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Stream.periodic(const Duration(seconds: 1)),
      builder: (context, snapshot) {
        return Text(
          DateFormat('HH:mm:ss')
                  .format(DateTime.now().toLocal())
                  .toString(),
        );
      },
    );
  }
}