Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Uso de Timer en Flutter para llamar cada 30 segundos a una función

Tiempo de lectura: 2 minutos

La función Timer en Flutter nos permitirá ejecutar una función cada X segundos que indiquemos.

Reloj de arena rojo -  Pexels

Pasos para implementarlo:

Configura el Timer en tu StatefulWidget

Define y administra el Timer en el estado del widget para que puedas iniciar, detener y reiniciar el temporizador según el estado del widget.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'dart:async';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
Timer? _timer;
bool _isScreenActive = true;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_startTimer();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.resumed) {
if (!_isScreenActive) {
_isScreenActive = true;
_startTimer();
}
} else if (state == AppLifecycleState.paused) {
_stopTimer();
_isScreenActive = false;
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final ModalRoute? modalRoute = ModalRoute.of(context);
if (modalRoute?.isCurrent == true) {
_isScreenActive = true;
_startTimer();
} else {
_isScreenActive = false;
_stopTimer();
}
}
@override
void dispose() {
_stopTimer();
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
void _startTimer() {
if (_timer != null && _timer!.isActive) return;
_timer = Timer.periodic(Duration(seconds: 30), (Timer timer) {
_myPeriodicFunction();
});
}
void _stopTimer() {
_timer?.cancel();
}
void _myPeriodicFunction() {
print("Función periódica ejecutada.");
// Aquí colocas la lógica que deseas ejecutar cada 30 segundos
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home Screen')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AnotherScreen()),
);
},
child: Text('Ir a otra pantalla'),
),
),
);
}
}
class AnotherScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Otra Pantalla')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Regresar'),
),
),
);
}
}
import 'dart:async'; import 'package:flutter/material.dart'; class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver { Timer? _timer; bool _isScreenActive = true; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _startTimer(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { super.didChangeAppLifecycleState(state); if (state == AppLifecycleState.resumed) { if (!_isScreenActive) { _isScreenActive = true; _startTimer(); } } else if (state == AppLifecycleState.paused) { _stopTimer(); _isScreenActive = false; } } @override void didChangeDependencies() { super.didChangeDependencies(); final ModalRoute? modalRoute = ModalRoute.of(context); if (modalRoute?.isCurrent == true) { _isScreenActive = true; _startTimer(); } else { _isScreenActive = false; _stopTimer(); } } @override void dispose() { _stopTimer(); WidgetsBinding.instance.removeObserver(this); super.dispose(); } void _startTimer() { if (_timer != null && _timer!.isActive) return; _timer = Timer.periodic(Duration(seconds: 30), (Timer timer) { _myPeriodicFunction(); }); } void _stopTimer() { _timer?.cancel(); } void _myPeriodicFunction() { print("Función periódica ejecutada."); // Aquí colocas la lógica que deseas ejecutar cada 30 segundos } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Home Screen')), body: Center( child: ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => AnotherScreen()), ); }, child: Text('Ir a otra pantalla'), ), ), ); } } class AnotherScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Otra Pantalla')), body: Center( child: ElevatedButton( onPressed: () { Navigator.pop(context); }, child: Text('Regresar'), ), ), ); } }
import 'dart:async';
import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
  Timer? _timer;
  bool _isScreenActive = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _startTimer();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.resumed) {
      if (!_isScreenActive) {
        _isScreenActive = true;
        _startTimer();
      }
    } else if (state == AppLifecycleState.paused) {
      _stopTimer();
      _isScreenActive = false;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final ModalRoute? modalRoute = ModalRoute.of(context);
    if (modalRoute?.isCurrent == true) {
      _isScreenActive = true;
      _startTimer();
    } else {
      _isScreenActive = false;
      _stopTimer();
    }
  }

  @override
  void dispose() {
    _stopTimer();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void _startTimer() {
    if (_timer != null && _timer!.isActive) return;
    _timer = Timer.periodic(Duration(seconds: 30), (Timer timer) {
      _myPeriodicFunction();
    });
  }

  void _stopTimer() {
    _timer?.cancel();
  }

  void _myPeriodicFunction() {
    print("Función periódica ejecutada.");
    // Aquí colocas la lógica que deseas ejecutar cada 30 segundos
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AnotherScreen()),
            );
          },
          child: Text('Ir a otra pantalla'),
        ),
      ),
    );
  }
}

class AnotherScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Otra Pantalla')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Regresar'),
        ),
      ),
    );
  }
}

Explicación del Código

  • Timer: Un Timer se utiliza para ejecutar una función periódicamente cada 30 segundos.
  • _startTimer: Inicia el temporizador si no está ya activo.
  • _stopTimer: Cancela el temporizador si está activo.
  • didChangeAppLifecycleState: Maneja el estado del ciclo de vida de la aplicación. Cuando la aplicación se reanuda (AppLifecycleState.resumed), el temporizador se reinicia. Cuando se pausa (AppLifecycleState.paused), el temporizador se detiene.
  • didChangeDependencies: Verifica si la pantalla actual está activa. Si es así, el temporizador se reinicia; si no, el temporizador se detiene.
  • dispose: Asegura que el temporizador se detenga cuando el widget se elimine.
0

Deja un comentario