Flutter Local Notification, Realtime And Scheduled Push Notification For Offline Devices

Follow @desiprogrammer_

Setting Up Everything

You will have to first install the flutter local notification plugin by adding the below text to your pubspes.yaml file under dependencies and then use flutter get to get the packages.


cupertino_icons: ^0.1.3
# Add The Following

flutter_local_notifications: ^1.4.4+2     
    

After fetching all the plugins, we have to set up our Android application for using it. we'll have to add a couple of user permissions and receiver details in our app's manifest file that's located in android>app>src>main>AndroidManifest.xml. Use the details given below to add the data to your own project.


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testproject">

<!-- Add The Given Three Permissions on top after manifest declaration. -->

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

Now add the following receivers in your application tag but not inside the activity.


<application
android:name="io.flutter.app.FlutterApplication"
  android:label="testproject"
  android:icon="@mipmap/ic_launcher">

<!-- Add The Given Three Permissions on top after manifest declaration. -->

<receiver android:name="
com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
  <intent-filter>
  <action android:name="android.intent.action.BOOT_COMPLETED"/>
  <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
  </intent-filter>
</receiver>
<receiver android:name="
com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />            
                

Intilializing The Plugin

Now we have to initialize the plugin with some of the options. We have to start by importing the flutter_local_notifications plugin that we just installed. Then create a variable of type FlutterLocalNotificationsPlugin. I will name it as fltrNotification.

Also, make sure that you add an app-icon as a drawable resource in your android project. Add a .png icon inside android>app>src>main>res>drawable.


@override
void initState() {
  super.initState();
  var androidInitilize = new AndroidInitializationSettings('app_icon');
  var iOSinitilize = new IOSInitializationSettings();
  var initilizationsSettings =
      new InitializationSettings(androidInitilize, iOSinitilize);
  fltrNotification = new FlutterLocalNotificationsPlugin();
  fltrNotification.initialize(initilizationsSettings,
      onSelectNotification: notificationSelected);
}
            

NOTE : The notificationSelected function is invoked when a notification is tapped. It expects a payload parameter, which is a string.

Given below is a function to handle the code which just shows a Dialog when tapped along the payload passed.It can be further customised to pass real world data and handle that accordingly.


Future notificationSelected(String payload) async {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      content: Text("Notification : $payload"),
    ),
  );
}
            

Creating Notifications

To create a notification we have to first set notification details for both platforms and then a general notification detail. Once the notification details are set, it can be used to show or schedule any notification.

We will use the show method of the FlutterLocalNotificationsPlugin variable that takes id, title, body, notification details and payload as parameters.


Future _showNotification() async {
  var androidDetails = new AndroidNotificationDetails(
      "Channel ID", "Desi programmer", "This is my channel",
      importance: Importance.Max);
  var iSODetails = new IOSNotificationDetails();
  var generalNotificationDetails =
      new NotificationDetails(androidDetails, iSODetails);

   await fltrNotification.show(
       0, "Task", "You created a Task", 
       generalNotificationDetails, payload: "Task");
}
            

Scheduling Notifications

In the same _showNotification function with all the details set we can also schedule a notification that accepts the same parameters as the show method, but only a scheduled time as an extra parameter.


var scheduledTime; = DateTime.now().add(Duration(seconds : 5));
fltrNotification.schedule(1, "Times Uppp", task, 
    scheduledTime, generalNotificationDetails);
    

Complete Source Code

As In Youtube Video


  import 'package:flutter/material.dart';
  import 'package:flutter_local_notifications/flutter_local_notifications.dart';
      
  void main() {
    runApp(MyApp());
  }
      
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: "Notifications",
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          accentColor: Colors.red,
          primaryColor: Colors.red,
        ),
        home: HomePage(),
      );
    }
  }
      
  class HomePage extends StatefulWidget {
    @override
    _HomePageState createState() => _HomePageState();
  }
  
  class _HomePageState extends State {
    FlutterLocalNotificationsPlugin fltrNotification;
    String _selectedParam;
    String task;
    int val;
  
    @override
    void initState() {
      super.initState();
      var androidInitilize = new AndroidInitializationSettings('app_icon');
      var iOSinitilize = new IOSInitializationSettings();
      var initilizationsSettings =
          new InitializationSettings(androidInitilize, iOSinitilize);
      fltrNotification = new FlutterLocalNotificationsPlugin();
      fltrNotification.initialize(initilizationsSettings,
          onSelectNotification: notificationSelected);
    }
      
  Future _showNotification() async {
    var androidDetails = new AndroidNotificationDetails(
        "Channel ID", "Desi programmer", "This is my channel",
        importance: Importance.Max);
    var iSODetails = new IOSNotificationDetails();
    var generalNotificationDetails =
        new NotificationDetails(androidDetails, iSODetails);
      
    // await fltrNotification.show(
    //     0, "Task", "You created a Task", generalNotificationDetails, payload: "Task");
    var scheduledTime;  
    if (_selectedParam == "Hour") {
      scheduledTime = DateTime.now().add(Duration(hours: val));
    } else if (_selectedParam == "Minute") {
      scheduledTime = DateTime.now().add(Duration(minutes: val));
    } else {
      scheduledTime = DateTime.now().add(Duration(seconds: val));
    }
      
    fltrNotification.schedule(
        1, "Times Uppp", task, scheduledTime, generalNotificationDetails);
  }
      
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: TextField(
                decoration: InputDecoration(border: OutlineInputBorder()),
                onChanged: (_val) {
                  task = _val;
                },
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                DropdownButton(
                  value: _selectedParam,
                  items: [
                    DropdownMenuItem(
                      child: Text("Seconds"),
                      value: "Seconds",
                    ),
                    DropdownMenuItem(
                      child: Text("Minutes"),
                      value: "Minutes",
                    ),
                    DropdownMenuItem(
                      child: Text("Hour"),
                      value: "Hour",
                    ),
                  ],
                  hint: Text(
                    "Select Your Field.",
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                  onChanged: (_val) {
                    setState(() {
                      _selectedParam = _val;
                    });
                  },
                ),
                DropdownButton(
                  value: val,
                  items: [
                    DropdownMenuItem(
                      child: Text("1"),
                      value: 1,
                    ),
                    DropdownMenuItem(
                      child: Text("2"),
                      value: 2,
                    ),
                    DropdownMenuItem(
                      child: Text("3"),
                      value: 3,
                    ),
                    DropdownMenuItem(
                      child: Text("4"),
                      value: 4,
                    ),
                  ],
                  hint: Text(
                    "Select Value",
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                  onChanged: (_val) {
                    setState(() {
                      val = _val;
                    });
                  },
                ),
              ],
            ),
            RaisedButton(
              onPressed: _showNotification,
              child: new Text('Set Task With Notification'),
            )
          ],
        ),
      ),
    );
  }
      
    Future notificationSelected(String payload) async {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          content: Text("Notification Clicked $payload"),
        ),
      );
    }
  }
      
    

NOTE : We are still in development phase, so couple of things might not work on the site 🤕.