How to Use flutter_local_notifications in Flutter with GetX: Full Code Example with Beautiful UI

The flutter_local_notifications package enables you to display local notifications in your Flutter app. Combined with GetX for state management, you can efficiently schedule and manage notifications with real-time updates.


Prerequisites

Ensure the following dependencies are added to your pubspec.yaml file:

 dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  flutter_local_notifications: ^12.0.4

Run flutter pub get to install the dependencies.


Step 1: Setting up the Notification Controller

We'll create a controller that manages notification scheduling and real-time state updates using GetX.

notification_controller.dart

 import 'package:get/get.dart';
 import 'package:flutter_local_notifications/flutter_local_notifications.dart';

 class NotificationController extends GetxController {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = 
      FlutterLocalNotificationsPlugin();
  
  @override
  void onInit() {
    super.onInit();
    initializeNotifications();
  }

  void initializeNotifications() async {
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
    );

    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  void showNotification() async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      'your_channel_id',
      'your_channel_name',
      importance: Importance.high,
      priority: Priority.high,
    );

    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);

    await flutterLocalNotificationsPlugin.show(
      0,
      'Hello!',
      'This is a local notification.',
      platformChannelSpecifics,
     );
   }
 }

In this controller:

  • initializeNotifications: Initializes the local notifications system.
  • showNotification: Schedules and displays a basic notification.

Step 2: Setting up the View with Beautiful UI

We’ll now create the view where users can trigger the notifications. The UI will be designed to look modern and attractive.

notification_view.dart

 import 'package:flutter/material.dart';
 import 'package:get/get.dart';
 import 'notification_controller.dart';

 class NotificationView extends GetView {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Local Notifications'),
        centerTitle: true,
        backgroundColor: Colors.teal,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // App logo
            Image.asset('assets/notification.png', height: 200),
            const SizedBox(height: 20),
            
            // Notification button
            ElevatedButton(
              onPressed: controller.showNotification,
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                primary: Colors.teal, // button color
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: const Text(
                'Show Notification',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 20),

            // Subtitle
            const Text(
              'Tap the button to show a notification!',
              style: TextStyle(fontSize: 16, color: Colors.grey),
             ),
           ],
         ),
       ),
     );
   }
 }

In this view:

  • AppBar: Displays a styled app bar with a centered title.
  • Image.asset: Adds an image as a visual element (e.g., a logo).
  • ElevatedButton: A styled button to trigger notifications.
  • Text: A simple subtitle to guide the user.

Step 3: Setting up the Binding

The binding will inject the NotificationController into the view.

notification_binding.dart

 import 'package:get/get.dart';
 import 'notification_controller.dart';

 class NotificationBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => NotificationController());
   }
 }

Step 4: Setting up the Main App

Finally, configure the routing and binding in your main.dart.

main.dart

 import 'package:flutter/material.dart';
 import 'package:get/get.dart';
 import 'notification_view.dart';
 import 'notification_binding.dart';

 void main() {
  runApp(MyApp());
 }

 class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/',
      getPages: [
        GetPage(
          name: '/',
          page: () => NotificationView(),
          binding: NotificationBinding(),
        ),
      ],
      title: 'Local Notifications Example',
      theme: ThemeData(
        primarySwatch: Colors.teal,
       ),
     );
   }
 }

Step 6: Android and iOS Permissions

Android

In your AndroidManifest.xml, add the following permissions:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

Also, ensure that you add the necessary notification channel in the Android setup (if required).

iOS

For iOS, you need to request notification permissions. Add this to your Info.plist:

 <key>UIBackgroundModes</key>
 <array>
  <string>fetch</string>
  <string>remote-notification</string>
 </array>

In this tutorial, we implemented local notifications in Flutter for both Android and iOS using the flutter_local_notifications package with GetX for state management. The example provided includes a fully functional code setup with a beautified UI, ensuring the notification feature in your Flutter app is well-organized and visually appealing.

With this guide, you now have a complete solution for managing local notifications across both platforms using Flutter and GetX. Let me know if you need further assistance or customizations!