Home > Mobile >  Flutter Q1. setState being called about 100 times in a second, while Timer periodic Duration set to
Flutter Q1. setState being called about 100 times in a second, while Timer periodic Duration set to

Time:11-07

Edit: Q1. is answered. please help me in the Q2. Also, please suggest if i should make a new thread of this question ?

Q1. I am making a digital clock in my app. I have set my Timer, so that setState should run after each second. and in the UI, it seems fine. But in terminal you can see it runs a lot of times in a second. How to stop that?

Q2. I have two pages in flutter app. Even when i move to secondpage (using navigator.push), the timer still runs in background. ( I know it because i am printing it in terminal also). Also, I already tried canceling my Timer in dispose method. it does not work. Also, If I use navigator.pushRemoved, it solves the problem of Timer being run in background, but i wont be able to go back to this page.

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:provider_2_practice/controller/controller_file.dart';

import 'new_screen.dart';

class MyHomePageUI extends StatefulWidget {
  @override
  State<MyHomePageUI> createState() => _MyHomePageUIState();
}

class _MyHomePageUIState extends State<MyHomePageUI> {

  Timer? timer ;
  String abc ='df-1'; //default value: 'df-1'

  String refreshTime(){
    timer?.cancel();

    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(mounted){
        setState( () {
          abc = DateFormat('hh:mm:ss a').format(DateTime.now());
          print(abc);
        } );
      }
    });

    return abc ;
  }

@override
  void dispose() {
    // TODO: implement dispose
  print('test');
  timer?.cancel();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue[900],
      floatingActionButton: FloatingActionButton(
        onPressed: (){

           Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));
 
        },
        child: Icon(Icons.add,  color: Colors.white),
        backgroundColor: Colors.blue,
      ),


      body: Column(
        children: [
          SizedBox(height:100,),
          Text(refreshTime(), style: TextStyle(fontSize: 45, fontWeight: FontWeight.bold,color: Colors.white70),),
          Text('current time', style: TextStyle(  fontWeight: FontWeight.bold,color: Colors.white),),

        ],
      ),
    );
  }
}

first page

second page, Timer still running. see the consol

CodePudding user response:

Every time refreshTime() is called you are creating a new timer on top of any existing timers. To solve this first cancel any existing timers. So like,

  String refreshTime(){
    timer?.cancel();
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState( () {
        abc = DateFormat('hh:mm:ss a').format(DateTime.now());
        print(abc);
      } );
    });

    return abc ;
  }

CodePudding user response:

ye initState ma rakho or jis btn click py next page pay ja rhy hu wha timer cancel kro or Ui py print krwany k lea abc use kro

timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
  if(mounted){
    setState( () {
      abc = DateFormat('hh:mm:ss a').format(DateTime.now());
    } );

  }
  print(abc);
});
  • Related