Home > Software engineering >  Flutter: run code like a timer when app is running in background
Flutter: run code like a timer when app is running in background

Time:05-20

I have a simple timer which works fine when the app is running in foreground. I can listen to the stream and update the UI. However when the app is in the background it will not continue counting. How can I continue counting when the app is running in the background?

This is my code for the timer:

class SetTimer {
  int _seconds = 0;
  final _streamController = StreamController<int>.broadcast();
  Timer? _timer;

  // Getters
  Stream<int> get stream => _streamController.stream;

  // Setters
  void start() {
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      _seconds  ;
      _updateSeconds();
    });
  }

  void _updateSeconds() {
    // stop counting after one hour
    if (_seconds < 3600) {
      _streamController.sink.add(_seconds);
    }
  }
}

CodePudding user response:

As far as I know, there is no way to run the app in the background, like you want to. I had a similar problem with an app, I developed and didn't found the perfect solution. As a workaround, I'm using the wakelock package to prevent the mobile device / app from going into standby. Maybe this could also be a solution for you.

CodePudding user response:

Try the below code -
I tested it & found it will count the number in the background & there is no problem.
I added a screen record video here, it will help you to understand.

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

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyTest(),
    );
  }
}

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

  @override
  State<MyTest> createState() => _MyTestState();
}

class _MyTestState extends State<MyTest> {
  final SetTimer _setTimer = SetTimer();

  @override
  void initState() {
    _setTimer.start();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<int>(
        stream: _setTimer.stream,
        builder: (
            BuildContext context,
            AsyncSnapshot<int> snapshot,
            ) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator();
          } else if (snapshot.connectionState == ConnectionState.active
              || snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return const Text('Error');
            } else if (snapshot.hasData) {
              return Center(
                child: Text(
                    snapshot.data.toString(),
                    style: const TextStyle(color: Colors.red, fontSize: 40)
                ),
              );
            } else {
              return const Text('Empty data');
            }
          } else {
            return Text('State: ${snapshot.connectionState}');
          }
        },
      ),
    );
  }
}

class SetTimer {
  int _seconds = 0;
  final _streamController = StreamController<int>.broadcast();
  Timer? _timer;

  // Getters
  Stream<int> get stream => _streamController.stream;

  // Setters
  void start() {
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      _seconds  ;
      _updateSeconds();
    });
  }

  void _updateSeconds() {
    // stop counting after one hour
    if (_seconds < 3600) {
      _streamController.sink.add(_seconds);
    }
  }
}
  • Related