DEV Community

Cover image for Getting to know Flutter: Local notifications
TheOtherDev/s
TheOtherDev/s

Posted on

Getting to know Flutter: Local notifications

While your app can be fine without advanced ways to build your users' loyalty, notifications are a really important feature that you should consider implementing. It can be a reminder on how much you love your users or a way to remind them of important events. Well, in Flutter using this great tool is pretty easy but you need to know a few concepts to master it! In this tutorial we'll see how to create a simple notification and a scheduled one.

flutter_local_notifications

This is the plugin we'll use and it's the most popular one on pub.dev. You can find it here and add it easily to your project:

dependencies:
  flutter_local_notifications: ^9.1.5

Enter fullscreen mode Exit fullscreen mode

This plugin supports iOS and Android and can show pretty much whatever you want as you were developing on native platform. Before starting with Dart code we'll need to check specific configuration for iOS and Android. Also let's add this package too:

flutter_native_timezone: ^2.0.0

Enter fullscreen mode Exit fullscreen mode

With this we can schedule timed notifications without caring for the timezones of the device.

A simple notification

Let's do an easy "hello world"! First we need to initialize the plugin with iOS and Android specifications. For Android we'll need to specify the channel and the icon. The channel can be initialized directly but the icon need to be added to the initialization.

  static const AndroidNotificationDetails _androidNotificationDetails =
  AndroidNotificationDetails(
    'MYID',
    'NOTIFICATION',
    channelDescription: 'Description',
    playSound: true,
    priority: Priority.high,
    importance: Importance.high,
  );

Enter fullscreen mode Exit fullscreen mode
Future<void> init() async {
    final AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');
  }
Enter fullscreen mode Exit fullscreen mode

iOS initialization is pretty straightforward too:

final IOSInitializationSettings initializationSettingsIOS =
        const IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );
Enter fullscreen mode Exit fullscreen mode

Also we want to init "Timezones" plugin. The final code for initialization will result:

import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

Future<void> init() async {
    final AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    final IOSInitializationSettings initializationSettingsIOS =
        const IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );

    final InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
      macOS: null,
    );

    tz.initializeTimeZones();

    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
    );
  }
Enter fullscreen mode Exit fullscreen mode

We can do that in a initState() without much issues. Also we'll need to ask for notifications permission on iOS this way:

final bool result = await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<
        IOSFlutterLocalNotificationsPlugin>()
    ?.requestPermissions(
    alert: true,
    badge: true,
    sound: true,
    );
Enter fullscreen mode Exit fullscreen mode

After that we are ready to trigger a notification!

Then we can finally create our notification:

const NotificationDetails platformChannelSpecifics =
                NotificationDetails(android: _androidNotificationDetails);
            await flutterLocalNotificationsPlugin.show(
              Random().nextInt(9000),
//NOTIFICATION ID - SHOULD BE UNIQUE/RANDOM
              'Hello',
              'World!',
              platformChannelSpecifics,
            );
Enter fullscreen mode Exit fullscreen mode

The result will be this:
Notification image

Scheduled notification

Scheduling a notification requires the same things as above but also a date time. It's best here to use directly Timezone plugin as it will take care of pretty much everything. We are now scheduling a notification to 5 seconds in the future:

var tzDateTime = tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5));

            await flutterLocalNotificationsPlugin.zonedSchedule(
              0,
              'Scheduled Hello',
              'Scheduled World!',
              tzDateTime,
              platformChannelSpecifics,
              androidAllowWhileIdle: true,
              uiLocalNotificationDateInterpretation:
                  UILocalNotificationDateInterpretation.absoluteTime,
            );
Enter fullscreen mode Exit fullscreen mode

In conclusion

Local notifications ca be a bit hard to initialize but they are a breeze to use once we understand them. This plugin offers a lot of options to customize notifications like media embedding and selection behavior but I'll leave them to you to discover!

For more awesome Flutter tutorials check out our website!

Discussion (0)