Oz Cohen
Oz Cohen

Reputation: 963

flutter notification - Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference

I am trying to create local notification using flutter_local_notifications First I created API Class to my project:

class NotificationApi{
  static final FlutterLocalNotificationsPlugin _notifications = FlutterLocalNotificationsPlugin();
  static Future _notificationDetailes() async => const NotificationDetails(
    android: AndroidNotificationDetails(
      "channel id",
      "channel name",
      channelDescription: "channel description",
      importance: Importance.max,
      playSound: true
    ),
    iOS: IOSNotificationDetails(),
  );
  
  static Future showNotification({int id =0, String? title, String? body, String? payload}) async =>
      _notifications.show(id, title, body, await _notificationDetailes(), payload: payload);
}

then I trigger the notification with a floating button:

 floatingActionButton: FloatingActionButton(
    onPressed: () {
      NotificationApi.showNotification(
          title:  "Oz Cohen",
          body: "Hey!! this is my first Notification!",
          payload: "oz.ss"
      );
    },
    child: const Icon(Icons.add),
  ), // This trailing comma makes auto-formatting nicer for build methods.

My pubspec.yaml file:

name: unico
description: A new Flutter project.

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

   
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.4
  keyboard_dismisser: ^2.0.0
  fluttertoast: ^8.0.8
  flutter_spinkit: ^5.1.0
  google_fonts: ^2.2.0
  switcher_button: ^0.0.4
  file_picker: ^4.3.0
  get: ^4.6.1
  intl: ^0.17.0

  #notificatios
  flutter_local_notifications: ^9.2.0
  firebase_messaging: ^11.2.4

  #Google Sign In
  google_sign_in: ^5.2.1
  # Google Icon
  font_awesome_flutter: ^9.2.0

  # fire base services:
  firebase_auth: ^3.3.4
  firebase_core: ^1.10.6
  cloud_firestore: ^3.1.5
  firebase_storage: ^10.2.4

  # State Management
  provider: ^6.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_lints: ^1.0.0

flutter:

  uses-material-design: true

  assets:
    - assets/images/

  fonts:
    - family: Pacifico
      fonts:
        - asset: fonts/Pacifico-Regular.ttf

and when I press the button instead of showing the notification the output is:

E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): Failed to handle method call E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:300) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:215) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1024) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1362) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1241) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at io.flutter.embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$6ZD1MYkhaLxyPjtoFDxe45u43DI.run(Unknown Source:12) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at android.os.Handler.handleCallback(Handler.java:873) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at android.os.Handler.dispatchMessage(Handler.java:99) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at android.os.Looper.loop(Looper.java:193) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at android.app.ActivityThread.main(ActivityThread.java:6669) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at java.lang.reflect.Method.invoke(Native Method) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E/flutter ( 7752): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null, java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference E/flutter ( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:300) E/flutter ( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:215) E/flutter ( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1024) E/flutter ( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1362) E/flutter ( 7752): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1241) E/flutter ( 7752): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262) E/flutter ( 7752): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178) E/flutter ( 7752): at io.flutter.embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206) E/flutter ( 7752): at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$6ZD1MYkhaLxyPjtoFDxe45u43DI.run(Unknown Source:12) E/flutter ( 7752): at android.os.Handler.handleCallback(Handler.java:873) E/flutter ( 7752): at android.os.Handler.dispatchMessage(Handler.java:99) E/flutter ( 7752): at android.os.Looper.loop(Looper.java:193) E/flutter ( 7752): at android.app.ActivityThread.main(ActivityThread.java:6669) E/flutter ( 7752): at java.lang.reflect.Method.invoke(Native Method) E/flutter ( 7752): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) E/flutter ( 7752): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E/flutter ( 7752): ) E/flutter ( 7752): #0
StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7) E/flutter ( 7752): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18) E/flutter ( 7752): E/flutter ( 7752): #2
FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:194:7) E/flutter ( 7752):

Upvotes: 7

Views: 10851

Answers (4)

Bhargav Raviya
Bhargav Raviya

Reputation: 399

There is the issue of fluter flutter_local_notifications package is an image of the flutter icon, not a specification

only add the icon field of "@mipmap/ic_launcher"

final AndroidInitializationSettings androidInitializationSettings =
      const AndroidInitializationSettings('@mipmap/ic_launcher');

And

AndroidNotificationDetails androidNotificationDetails =
        const AndroidNotificationDetails(
      'channelId',
      'channelName',
      importance: Importance.max,
      priority: Priority.high,
      icon: '@mipmap/ic_launcher',
    );

Upvotes: 4

Elefiku young
Elefiku young

Reputation: 71

this is what help me

NotificationDetails( android: AndroidNotificationDetails(
          channelId,
          channelName,
          icon: "appIcon", //add app icon here
          importance: Importance.max, ,
        ),

Upvotes: 6

Onalo Joseph
Onalo Joseph

Reputation: 265

I had same issue, I just had to initialize My Local notification class before I call my showNotification function.

Upvotes: 1

Fabien
Fabien

Reputation: 53

with this snipped you can send local notification

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance_channel', // id
    'High Importance Notifications', // title
    description: 'This channel is used for important notifications.', // description
    importance: Importance.high,
    playSound: true);

// flutter local notification
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

// firebase background message handler
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('A Background message just showed up :  ${message.messageId}');
}

Future<void> main() async {
  // firebase App initialize
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

// Firebase local notification plugin
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

//Firebase messaging
  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Push Notification',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Push Notification'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, title}) : super(key: key);

  final String title = "";

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                channelDescription : channel.description,
                color: Colors.blue,
                playSound: true,
                icon: '@mipmap/ic_lancher',
              ),
            ));
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new messageopen app event was published');
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        showDialog(
            context: context,
            builder: (_) {
              return AlertDialog(
                title: Text("${notification.title}"),
                content: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [Text("${notification.body}")],
                  ),
                ),
              );
            });
      }
    });
  }

  void showNotification() {
    setState(() {
      _counter++;
    });

    flutterLocalNotificationsPlugin.show(
        0,
        "Testing $_counter",
        "This is an Flutter Push Notification",
        NotificationDetails(
            android: AndroidNotificationDetails(channel.id, channel.name,
                channelDescription: channel.description,
                importance: Importance.high,
                color: Colors.blue,
                playSound: true,
                icon: '@mipmap/ic_launcher')));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'This is Flutter Push Notification Example',
            ),
            // Text(
            //   '$_counter',
            //   style: Theme.of(context).textTheme.headline4,
            // ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: showNotification,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 3

Related Questions