Search code examples
flutterdartbackground-processshakedart-isolates

In background flutter app works only for 1 minute after that it stops it's working, is Dart-Isolates good to try?


made a simple counter app with shake package to increment counter var by shaking phone, things works well when app is running in front (in active state) but opening other app stops this shake feature after one minute, it works only for one minute but not after one minute, i have tried to implement isolate but i couldn't do so, If someone can show me how to implement isolate in following code i will be very thanks full to him, Thank you

Code is here:

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0;
  ShakeDetector detector;

  @override
  void initState() {
    detector = ShakeDetector.autoStart(onPhoneShake: () {
      setState(() {
        _counter++;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(child: Text('$_counter')),
      ),
    );
  }
}


Solution

  • Your app is not running in the background. This is not a desktop operating system, where the windows can overlap and be in the background and the process is still running regardless.

    Mobile device operating systems are all optimized for foreground app handling. Once your app is no longer the app, it can be removed by the operating system at any time. The operating system will keep a screenshot of your app, to make you think it's still there, but if the system deems it necessary, your app will be shut down and selecting the last picture of your app (which you probably interpret as "get this running app into the foreground" as you know it from desktop operating systems) will actually start a new instance of your app, since the old instance is long gone.

    Running code in the background is more complicated than it seems from a desktop mindset that we all have. You can find a good start in the Flutter documentation on running background processes. It might seem overly complicated, because running something in the background is not the norm for mobile operating systems.