Flutter timer background

Flutter Timer in Background

To run a timer in the background using Flutter, you can utilize the background_fetch plugin. This plugin allows you to execute Dart code in the background on both Android and iOS devices.

Step 1: Add Dependencies

In order to use background_fetch plugin, you need to add it to your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  background_fetch: ^0.8.2
  

Step 2: Initialization

To initialize the plugin, you need to call the BackgroundFetch.configure method within your Flutter app.

void main() {
  runApp(MyApp());
  
  BackgroundFetch.configure(
    BackgroundFetchConfig(
      minimumFetchInterval: 15, // Minimum time interval for executing background fetch (in minutes)
      stopOnTerminate: false, // Set true if you want to stop background fetch when the app is terminated
      enableHeadless: true, // Set true to enable background fetch in headless mode
      startOnBoot: true, // Set true to start background fetch on device boot
    ),
    (String taskId) async {
      // Your background fetch logic goes here
      // This function will be called when a background fetch event is triggered
    },
  );
}
  

Step 3: Handle Background Fetch

The function provided to BackgroundFetch.configure will be called whenever a background fetch event is triggered. You can perform your desired timer logic within this function.

(String taskId) async {
  // Your background fetch logic goes here
  // This function will be called when a background fetch event is triggered
  Timer.periodic(Duration(seconds: 1), (Timer t) {
    // Your timer logic goes here
    print('Timer is running in the background...');
  });
  BackgroundFetch.finish(taskId);
}
  

Step 4: Testing

You can now test the background fetch functionality by running your app on a physical device. Keep in mind that iOS may have additional requirements, such as enabling background fetch capabilities in your app’s Info.plist file.

Example App

Here’s an example of a Flutter Timer app that runs in the background:

// main.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:background_fetch/background_fetch.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
  
  BackgroundFetch.configure(
    BackgroundFetchConfig(
      minimumFetchInterval: 15,
      stopOnTerminate: false,
      enableHeadless: true,
      startOnBoot: true,
    ),
    (String taskId) async {
      Timer.periodic(Duration(seconds: 1), (Timer t) {
        print('Timer is running in the background...');
      });
      BackgroundFetch.finish(taskId);
    },
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Background Timer',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: TimerScreen(),
    );
  }
}

class TimerScreen extends StatefulWidget {
  @override
  _TimerScreenState createState() => _TimerScreenState();
}

class _TimerScreenState extends State {
  int seconds = 0;

  @override
  void initState() {
    super.initState();
    Timer.periodic(Duration(seconds: 1), (Timer t) {
      if (mounted) {
        setState(() {
          seconds++;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Background Timer'),
      ),
      body: Center(
        child: Text(
          'Seconds: $seconds',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}
  

You can use the provided example as a starting point for your own app and modify the timer logic according to your requirements.

Leave a comment