Search code examples
androidflutterandroid-notifications

How do I show a custom Android notification using Flutter widgets?


I want to show custom notifications on Android using Flutter widgets? I'll like to know if that is possible.

What I've done:

I tried using showing a Flutter widget in an Android Fragment and display that Fragment using RemoteViews for custom Android notifications.

A notification shows but it does not include the Flutter widget. See screenshot below:

Screenshot showing a notification without any content

Code:

 var newFlutterFragment: FlutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
     .shouldAttachEngineToActivity(false)
     .build()
 if (fragmentManager != null) {
     fragmentManager
         .beginTransaction()
         .add(
             R.id.fragment_container,
             newFlutterFragment,
             TAG_FLUTTER_FRAGMENT
         )
         .commit()
 }



 val notificationLayout = RemoteViews(packageName, R.layout.activity_layout)
 val notificationLayoutExpanded = RemoteViews(packageName, R.layout.activity_layout)


 var builder = NotificationCompat.Builder(this, CHANNEL_ID)
     .setSmallIcon(R.drawable.ic_bg_service_small)
     .setCustomContentView(notificationLayout)
     .setCustomBigContentView(notificationLayoutExpanded)
     .setPriority(NotificationCompat.PRIORITY_DEFAULT)

 var notificationId = 1;

 with(NotificationManagerCompat.from(this)) {
     // notificationId is a unique int for each notification that you must define
     notify(notificationId, builder.build())
 }

Solution

  • In order for Flutter widgets to work, there should be a Flutter framework working. It works only for regular views. In the remote view, there is no such possibility because it is rendered by the Android system itself but not the app, and it does not know about Flutter, which is packaged inside the app but not the system. Moreover, even not all the Android native widgets can be rendered as remote views.

    There are some options you can do here, though:

    • If your flutter framework is present, you can rasterize the flutter widget and show it in the ImageView inside the remote view. It won't be interactive, though. You can combine it with some Android native buttons.
    • Use service with ui - in theory, it can render a flutter view, but it is hard to achieve since it is hardly possible to show fragments outside of the activity, and showing a plain view will require proper lifecycle handling for the Flutter framework, which is not a trivial task.
    • Make all the logic needed in Flutter and pass the data to and from the native implementation via platform channels. As of May 2023 platform channels should work both on main and background threads.
    • Implement all the stuff as Android native and don't bother with Flutter because Flutter is meant for cross-platform, and all the previous stuff would not work on iOs; hence the point of Flutter is absent in this case.