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';
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) {
}
}
Related
I want to load data continuously from server when app is start and stop it when app is closed.
So, how to achieve this ?
for example in flutter
start app.
method is start to running, whatever widget on screen .
close app.
method stop.
you can execute your funtion on bakcground.
people are usually use workmanager package. here : https://pub.dev/packages/workmanager
another option, you also can use flutter_isolate
final isolate = await FlutterIsolate.spawn(your-asycn-funtion, "hello2");
want to create a screen that launch when a firebase notification is received while the app is in the background or terminated in flutter (like package callKeep ).please anyone help me create that.
You just need to handle its background handler method it will works.You need to initialize this method in main() method.
Future<void> backgroundHandler(RemoteMessage message) async {
debugPrint(message.toString());
debugPrint(message.data.toString());
debugPrint(message.notification!.title);
}
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
I am using Android 11 Wireless Debugging to develop my app. Whenever the device automatically locks itself, it takes a while to re-establish the connection for hot reloading.
To overcome this I am using wakelock, which I only need to use if my app is in debug mode, not in release mode.
In lib/main.dart I have the following code:
import 'package:flutter/foundation.dart' as Foundation;
import 'package:wakelock/wakelock.dart';
...
void main() {
if (Foundation.kDebugMode) {
Wakelock.enable();
}
runApp(App());
}
As you can see the wakelock package is only used if the app is running in debug mode.
Is there a way to only import wakelock if the app is running in debug mode?
Tested it as
pubspec.yaml
dev_dependencies:
wakelock: ^0.2.1+1
Usage
import 'package:flutter/foundation.dart';
import 'package:wakelock/wakelock.dart';
import 'package:flutter/material.dart';
main() async {
WidgetsFlutterBinding.ensureInitialized();
if (kDebugMode) {
print('activating wakelock in debug');
Wakelock.enable();
}
runApp(App());
}
Sidenote:
If all you need is the device to stop locking itself after some time then try increasing the sleep delay under the Display setting on the device itself, or use a setting in developer options called Stay awake while charging which allows the device to stay on forever while charging.
When and how we use it?
How it works?
WidgetsFlutterBinding
You have to use it, in this way:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
https://flutter.dev/docs/resources/architectural-overview#architectural-layers
The WidgetFlutterBinding is used to interact with the Flutter engine. Firebase.initializeApp() needs to call native code to initialize Firebase, and since the plugin needs to use platform channels to call the native code, which is done asynchronously therefore you have to call ensureInitialized() to make sure that you have an instance of the WidgetsBinding.
Answerd By https://stackoverflow.com/users/7015400/peter-haddad
Answer Link https://stackoverflow.com/a/63873689
WidgetsBinding.ensureInitialized() This initialised communication between the Dart Layer and Flutter Engine.
We need to call this method if we need the binding to be initialised before calling [runApp]. Flutter cannot directly interact with flutter engine until and unless binding is established.
Example 1: Shows Firebase platform initialisation between flutter and native code, which Firestore class do internally.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firestore.initializeApp();
runApp(
...
)
}
OR
Example 2: Shows device orientation changes before even app starts, for this also we need to established binding connection.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown
]);
runApp(
...
)
}
Internally, WidgetsBinding.ensureInitialized() supports various binding likes GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding
ServicesBinding listens for platform messages and directs them to the handler for incoming messages (BinaryMessenger).
PaintingBinding is responsible for binding to the painting library.
RenderBinding binds the render tree to the Flutter engine.
WidgetBinding binds the widget tree to the Flutter engine.
SchedulerBinding is the scheduler for running immediate tasks.
SemanticsBinding binds the semantics layer and the Flutter engine.
GestureBinding is a binding for the gesture subsystem.
I am trying to force my Flutter app to only use Portrait mode. My main() method looks like this.
void main() {
SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS)
.then((_) => runApp(MyApp()));
}
Here is the definition of ALLOWED_ORIENTATIONS:
const List<DeviceOrientation> ALLOWED_ORIENTATIONS = [
DeviceOrientation.portraitUp
];
I just separated all the settings and such to another file to make modifying them later on easier.
When I run this code, I get the following error.
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception:
ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()`
has been called (for example, during plugin initialization), then you need to explicitly
call the `WidgetsFlutterBinding.ensureInitialized()` first.
It looks like there is some race condition that's failing. I am just not sure what is causing it. Removing the SystemChrome.setPreferredOrientations() line makes the app compile as expected. So, I am thinking the error has something to do with that line.
Any advice?
Like the error says
If you're running an application and need to access the binary
messenger before runApp() has been called (for example, during
plugin initialization), then you need to explicitly call the
WidgetsFlutterBinding.ensureInitialized() first.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
await SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS);
runApp(MyApp());
}