Nitneuq
Nitneuq

Reputation: 5042

How to run with iOS device a flutter app?

Here is a simple code to detect vertical position of device

But I don't found how to run this code in background with flutter

I try to use isolate but console print only 20s after foreground

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

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


 logic() async {

  accelerometerEvents.listen((AccelerometerEvent event) {
    print(event.y);

    if (event.y>5.0||event.y<-5.0){
      print("notification fire");    }
  });
}



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

class _MyAppState extends State<MyApp> {



  Future<void> _run() async {
    final isolate = await FlutterIsolate.spawn(logic(), "test");

    Timer(Duration(seconds: 1), () {
      print("Resuming Isolate 1");
      isolate.resume();
    });

  }


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: ElevatedButton(
            child: Text('Run'),
            onPressed: _run,
          ),
        ),
      ),
    );
  }
}

Upvotes: 0

Views: 132

Answers (1)

Dan Gerchcovich
Dan Gerchcovich

Reputation: 525

  1. By background I'd take it you mean a background fetch, which means that the app needs to run even though the app is not currently in the foreground.
  2. And if by background you mean, it must run on a seperate thread, then in that case you will have to use an isolate. An isolate is essentially a seperate piece of memory (core) that runs separately to the main isolate (core) that flutter runs on. The heavy work is moved into this isolate, so the main app (isolate) does not get blocked and seem janky.

Please review the documentation for info here: https://api.dart.dev/stable/2.12.2/dart-isolate/dart-isolate-library.html

There are two plugins you should take a look at:

  1. This will help you with Background Fetch

https://pub.dev/packages/background_fetch

  1. This will help you to write up isolates. I should also mention that 3rd party plugin api or flutter api, cannot be invoked in seperate isolates. It's an issue mostly with how dart was designed, since it was made by google to be single threaded.

https://pub.dev/packages/flutter_isolate

Upvotes: 1

Related Questions