<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Simay on Medium]]></title>
        <description><![CDATA[Stories by Simay on Medium]]></description>
        <link>https://medium.com/@simayekici?source=rss-14729db4cccc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dZqzEXEVh4xrf5Q_JN5YkA.jpeg</url>
            <title>Stories by Simay on Medium</title>
            <link>https://medium.com/@simayekici?source=rss-14729db4cccc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:02:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simayekici/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Make Your Flutter App Work in Background With flutter_background_service]]></title>
            <link>https://medium.com/@simayekici/how-to-make-your-flutter-app-work-in-background-with-flutter-background-service-4d1e6ccf1b23?source=rss-14729db4cccc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d1e6ccf1b23</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[background-service]]></category>
            <dc:creator><![CDATA[Simay]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 12:30:23 GMT</pubDate>
            <atom:updated>2025-01-26T12:37:16.601Z</atom:updated>
            <content:encoded><![CDATA[<p>In Flutter, when your app is minimized, locked, or closed, it pauses all its activities. Normally, that’s fine, but there are cases when you need your app to keep running certain tasks in the background. This could be for syncing data, tracking location, or sending notifications. That’s where background services come in — they allow these tasks to run even when the app isn’t actively in use. In this article, I’ll show you how to set this up using the flutter_background_service package, which is a popular choice for managing background tasks.</p><h3>— How does flutter_background_service help?</h3><p>The flutter_background_service package lets you run tasks in the background by tapping into native platform services instead of Dart isolates. This way, the background tasks are managed by the operating system, so they can run even when the app is not actively running in the foreground. The package connects the background service with your Flutter app, allowing them to communicate smoothly.</p><h3>The Tech Behind: Native Background Services</h3><p>The package makes use of native services for running background tasks.</p><ul><li><strong>On Android:</strong> It uses <strong>Foreground Services</strong>, which are designed for tasks that need to keep running even when the app is not in the foreground. Foreground services need to show a persistent notification to let the user know that something is happening in the background.</li><li><strong>On iOS:</strong> The package relies on <strong>Background Fetch</strong>, which wakes up the app periodically to perform small tasks like syncing data. Keep in mind that iOS restricts this time to about 15 minutes at a time, so the service can’t run indefinitely. This is done to preserve battery life and optimize device performance.</li></ul><h3>Creating the Background Task: Where the Real Work Happens</h3><p>The core of every background service is its intended task — what the service is designed to execute when the app is not actively running. In the case of the flutter_background_service package, this functionality is initiated in the onStartfunction. But before diving into implementation specifics, let’s consider the bigger picture:</p><h3>What Makes a Background Service Work?</h3><p>A background service isn’t just code running in the background; it has a specific purpose and needs to work efficiently. It should:</p><ul><li><strong>Wake up when necessary:</strong> The service should run its tasks at the right moment, whether triggered by the app or system events.</li><li><strong>Be independent:</strong> The service operates in its own environment, which means it has to load all necessary data each time it runs.</li><li><strong>Handle interruptions:</strong> Services must be resilient to system interruptions or crashes and should be able to resume or restart as needed.</li></ul><h3>Implementing a Simple Background Service with Local Notifications in Flutter</h3><p>In this section, we’ll implement a simple app that uses a background service to periodically update a step counter and show notifications to the user. This example will show how to set up a background service and integrate local notifications to keep users informed, even when the app is not in the foreground.</p><pre>final localNotificationsPlugin = FlutterLocalNotificationsPlugin();<br><br>Future&lt;void&gt; main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await initializeService();<br>  runApp(const MaterialApp(home: StepCounterScreen()));<br>}<br>Future&lt;void&gt; initializeService() async {<br>  final service = FlutterBackgroundService();<br>  await service.configure(<br>    androidConfiguration: AndroidConfiguration(<br>      onStart: onStart,<br>      isForegroundMode: true,<br>      autoStart: true,<br>    ),<br>    iosConfiguration:<br>        IosConfiguration(onForeground: onStart, onBackground: (_) =&gt; true),<br>  );<br>  service.startService();<br>}<br>void onStart(ServiceInstance service) async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  const channel = AndroidNotificationChannel(<br>      &#39;step_counter_channel&#39;, &#39;Step Notifications&#39;,<br>      importance: Importance.high);<br>  await localNotificationsPlugin<br>      .resolvePlatformSpecificImplementation&lt;<br>          AndroidFlutterLocalNotificationsPlugin&gt;()<br>      ?.createNotificationChannel(channel);<br>  await localNotificationsPlugin.initialize(const InitializationSettings(<br>      android: AndroidInitializationSettings(&#39;@mipmap/ic_launcher&#39;)));<br>  int steps = 0;<br>  Timer.periodic(const Duration(seconds: 10), (_) {<br>    steps += 50;<br>    _showNotification(&quot;Step Counter&quot;, &quot;Steps today: $steps&quot;);<br>  });<br>  service.on(&#39;stopService&#39;).listen((_) =&gt; service.stopSelf());<br>}<br>Future&lt;void&gt; _showNotification(String title, String body) async {<br>  await localNotificationsPlugin.show(<br>    0,<br>    title,<br>    body,<br>    const NotificationDetails(<br>      android: AndroidNotificationDetails(<br>          &#39;step_counter_channel&#39;, &#39;Step Notifications&#39;,<br>          channelDescription: &#39;Step counter updates.&#39;,<br>          importance: Importance.high,<br>          priority: Priority.high),<br>    ),<br>  );<br>}<br>class StepCounterScreen extends StatefulWidget {<br>  const StepCounterScreen({super.key});<br>  @override<br>  StepCounterScreenState createState() =&gt; StepCounterScreenState();<br>}<br>class StepCounterScreenState extends State&lt;StepCounterScreen&gt; {<br>  @override<br>  void initState() {<br>    super.initState();<br>    _requestPermissions();<br>  }<br>  Future&lt;void&gt; _requestPermissions() async {<br>    if (await Permission.notification.isDenied) {<br>      await Permission.notification.request();<br>    }<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;Count steps&quot;)),<br>      body: Center(<br>        child: ElevatedButton(<br>          onPressed: () =&gt; FlutterBackgroundService().invoke(&quot;stopService&quot;),<br>          child: const Text(&quot;Stop Background Service&quot;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>With the example code, even if you minimize or terminate the app (by removing it from the recent apps list or through the settings), the code will continue executing in the background. However, it’s important to note that the operating system may shut down background operations if it detects that the app hasn’t been used for a long period, in order to manage system resources efficiently. This depends on how the operating system manages background tasks, as it may stop them to optimize system resources.</p><h3>Checklist before running</h3><ul><li>Permissions added (FOREGROUND_SERVICE for Android, Background Fetch for iOS).</li><li>foregroundServiceType declared for Android 14+. (For more information please check <a href="https://developer.android.com/about/versions/14/changes/fgs-types-required">Foreground Service Types</a>)</li><li>Background task identifiers added to Info.plist for iOS.</li></ul><h3>Conclusion: Letting Your App Work While You Sleep</h3><p>Implementing background tasks involves understanding platform differences. Android lets you run services continuously with proper setup, while iOS enforces strict time and resource limits. Balancing these constraints is crucial to offering a smooth user experience.</p><p>It’s also important to manage user expectations. Be transparent by using persistent notifications or providing app documentation that explains what your app is doing in the background.</p><p>Lastly, always keep an eye on resource management. Background services use CPU, battery, and memory, so poor implementation can lead to frustration and uninstalls. Consider all aspects before jumping in.</p><p>Thanks so much for reading! 🧚‍♀️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d1e6ccf1b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>