Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Using path provider when app is in background

Tags:

I am currently trying to implement FCM and local notifications into my Flutter app. I have successfully configured FCM and the Local notifications for normal notifications, But i also have a different type of notification that I would like to display with an Image, When my app is in the foreground the notification is displayed without error, However when I terminate the app / move it to background I get an exception when trying to save the image using path provider.

The exception:

MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)

I'm assuming this error is occurring because the path provider method channel is closed when the app is not in the foreground, Is there something I can do to fix this? Or if not the flutter_local_notifications plugin requires a filepath to a bitmap, Can I achieve saving the image and getting a path in a different way that will work in background (without path provider)? (What I actually would like to display is an image from a link like this one: https://is1-ssl.mzstatic.com/image/thumb/WNUBiv2P6YSklHn9eA5nlg/1000x1000bb.jpeg)

Saving the image:

 static Future<String> saveImage(Image image) {
    final completer = Completer<String>();
    image.image.resolve(ImageConfiguration()).addListener(ImageStreamListener((imageInfo,_) async {
      final byteData = await imageInfo.image.toByteData(format: ImageByteFormat.png);
      final pngBytes = byteData.buffer.asUint8List();
      final fileName = pngBytes.hashCode;
      final directory = await getApplicationDocumentsDirectory();
      final filePath = '${directory.path}/$fileName';
      final file = File(filePath);
      await file.writeAsBytes(pngBytes);
      completer.complete(filePath);
    }));
    return completer.future;
  }
like image 983
barbecu Avatar asked Jun 28 '20 14:06

barbecu


1 Answers

you need to register path provider in Application.java as well.

import io.flutter.plugins.pathprovider.PathProviderPlugin;

...

    @Override
    public void registerWith(PluginRegistry registry) {
PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"));
    }

Now that flutter uses Kotlin as the default language for android side, here is the Kotlin code:

override fun registerWith(registry: PluginRegistry) {
    io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"))
}
like image 153
Jim Avatar answered Sep 19 '22 12:09

Jim