Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

Flutter run Dart function in the background

I have a dart function someFunction which takes a couple of minutes to run (it has a good amount of network requests it awaits on). Currently when I run the function and move my app to the background it seems that the requests that were queued up before leaving the app are executed, but then the function stops, and also doesn't resume when I return to the app. What I would like to do is to have the function run in the background until completion, even if the app is not in the foreground, and also send a notification once the function finishes if the app is not in the foreground.

I've looked at some solutions like the background-fetch plugin and isolates, but unless im missing something they seem to be only for native code, or periodical background tasks. What i'm looking for is a task that runs once no matter what and returns back to the main thread with a result it can react to

The non Dart dependencies of the function incase this is relevant:

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
question from:https://stackoverflow.com/questions/65642713/flutter-run-dart-function-in-the-background

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

have you try this package, workmanager with WidgetsBindingObserver (App lifecycle)?

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    //Do whatever you want in background
    if (state == AppLifecycleState.paused ||
        state == AppLifecycleState.detached) {
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...