Open In App

Background local notifications in Flutter

Last Updated : 11 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes user wants some very important features like the latest news updates, latest articles updates, weather condition alert, complete his/her profile update, future events update and much more in his/ her Android or iOS device without opening App and if you would like to develop this kind of Android and iOS application then this article will help you to do so. In this process, we set up background jobs that periodically check update about the latest events or alert.

Flutter:

It is an open-source UI software development toolkit created by Google. It comes in handy while developing applications for Android, Mac, Windows, Google Fuchsia, iOS, Linux, and the web through a single codebase.

Dart:

It is a client-optimized programming language for apps on multiple platforms. It is used to developed mobile, desktop, server, and web applications. Dart is an object-oriented language that also has garbage-collection property and has a syntax similar to the C programming language. It can compile in both native code or JavaScript.

Flutter WorkManager:

It is used as a wrapper around the Android’s WorkManager and also the iOS performFetchWithCompletionHandler, which effectively enables the headless execution of Dart code in the background. WorkManager provides an easy-to-use API where we can define a background job that should run once, or periodically, apply multiple constraints like for example if a task needs an internet connection, or if the battery should be fully charged, and much more.

Flutter Local Notifications:

It is a cross-platform plugin for displaying local notifications in a flutter application. It offers a bunch of features like for example scheduling when notifications should appear, periodically show a notification (interval-based), handle when a user has tapped on a notification when the app is in the foreground, background, or terminated, specify a custom notification sound and much more.

Android Studio:

It is the official integrated development environment(IDE) for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android development, and this hole representation of Android Studio will be used as IDE.

Here, We are creating background jobs with headless execution. To get started we need to install certain flutter plugins and Android Studio must be installed in the local system.

Before getting started Flutter development toolkit in the local system and  Flutter plugin in Android Studio IDE must be installed.

  • Open Android Studio and create a new flutter application project with a name called ‘geeksforgeeks’.
  • Once the project is created and sync successfully, connect your Android device to Android Studio and make sure Developer options and USB debugging are On.
  • Run the project by clicking on the first green icon at the center top to cross-check the project is built and running successfully(first time Android Studio takes a little more time as usual).
  • Now, It’s time to install the necessary plugins, open the ‘pubspec.yaml’ file from geeksforgeeks -> pubspec.yaml project structure and copy-paste two dependencies that are Workmanager and flutter_local_notifications as follows.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  # Use with the Workmanager class for background jobs headless execution.
  workmanager: ^0.2.3
  # Use with FlutterLocalNotificationsPlugin class for local push notifications.
  flutter_local_notifications: ^1.4.4+2
  • Once, you have done the above steps then click on ‘Packages get’ flutter command appearing at the center top to get install all necessary packages and plugins.
  • Now, It’s time to add some required permissions, open the ‘AndroidManifest.xml’ file from geeksforgeeks -> android -> app -> src -> main -> AndroidManifest.xml project directory structure and copy-paste following permissions.
<!-- Add below permission inside 'manifest' tag -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- Add below permission inside 'application' tag -->
<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>

Now, It is time to code, open ‘main.dart’ file from geeksforgeeks -> lib -> main.dart project directory structure and copy-paste following the entire code.

Dart




import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:workmanager/workmanager.dart';
 
void main() {
   
  // needed if you intend to initialize in the `main` function
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().initialize(
     
      // The top level function, aka callbackDispatcher
      callbackDispatcher,
     
      // If enabled it will post a notification whenever
      // the task is running. Handy for debugging tasks
      isInDebugMode: true
  );
  // Periodic task registration
  Workmanager().registerPeriodicTask(
    "2",
     
    //This is the value that will be
    // returned in the callbackDispatcher
    "simplePeriodicTask",
     
    // When no frequency is provided
    // the default 15 minutes is set.
    // Minimum frequency is 15 min.
    // Android will automatically change
    // your frequency to 15 min
    // if you have configured a lower frequency.
    frequency: Duration(minutes: 15),
  );
  runApp(MyApp());
}
 
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) {
     
    // initialise the plugin of flutterlocalnotifications.
    FlutterLocalNotificationsPlugin flip = new FlutterLocalNotificationsPlugin();
     
    // app_icon needs to be a added as a drawable
    // resource to the Android head project.
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var IOS = new IOSInitializationSettings();
     
    // initialise settings for both Android and iOS device.
    var settings = new InitializationSettings(android, IOS);
    flip.initialize(settings);
    _showNotificationWithDefaultSound(flip);
    return Future.value(true);
  });
}
 
Future _showNotificationWithDefaultSound(flip) async {
   
  // Show a notification after every 15 minute with the first
  // appearance happening a minute after invoking the method
  var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      'your channel id',
      'your channel name',
      'your channel description',
      importance: Importance.Max,
      priority: Priority.High
  );
  var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
   
  // initialise channel platform for both Android and iOS device.
  var platformChannelSpecifics = new NotificationDetails(
      androidPlatformChannelSpecifics,
      iOSPlatformChannelSpecifics
  );
  await flip.show(0, 'GeeksforGeeks',
    'Your are one step away to connect with GeeksforGeeks',
    platformChannelSpecifics, payload: 'Default_Sound'
  );
}
 
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks Demo',
      theme: ThemeData(
         
        // This is the theme
        // of your application.
        primarySwatch: Colors.green,
      ),
      home: HomePage(title: "GeeksforGeeks"),
    );
  }
}
 
class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  // This widget is the home page of your application.
  // It is stateful, meaning
  // that it has a State object (defined below)
  // that contains fields that affect
  // how it looks.
 
  // This class is the configuration for the state.
  // It holds the values (in this
  // case the title) provided by the parent
  // (in this case the App widget) and
  // used by the build method of the State.
  // Fields in a Widget subclass are
  // always marked "final".
 
  final String title;
 
  @override
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
     
    // This method is rerun every time setState is called.
    // The Flutter framework has been optimized
    // to make rerunning build methods
    // fast, so that you can just rebuild
    // anything that needs updating rather
    // than having to individually change
    //instances of widgets.
    return Scaffold(
      appBar: AppBar(
         
        // Here we take the value from
        // the MyHomePage object that was created by
        // the App.build method, and use it
        // to set our appbar title.
        title: Text(widget.title),
      ),
      body: new Container(),
    );
  }
}


Finally, Run the project by clicking on the first green icon at the center top to see the output, and your job gets done.

Output: 

References:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads