Home > Net >  flutter local notifcation error , I have been try to create headsup notifcation and i am stuck for m
flutter local notifcation error , I have been try to create headsup notifcation and i am stuck for m

Time:11-26

this is my local_notification_settings.dart

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

class LocalNotificationService{
  static final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();


  static void initialize(){
    final InitializationSettings initializationSettings =
        InitializationSettings(
            android: AndroidInitializationSettings('@mipmap/ic_launcher'));

  
    
  }
  static void display(RemoteMessage message)async{
    try {
      final id  = DateTime.now().millisecondsSinceEpoch ~/1000;
      final NotificationDetails notificationDetails = NotificationDetails(
        android: AndroidNotificationDetails(
          "intraday",
          "intraday channel",
          channelDescription: "this is intraday channel",
          importance: Importance.max,
          priority: Priority.high
        )
      );
      await _notificationsPlugin.show(id, message.notification!.title,
      message.notification!.body, notificationDetails);
    } on Exception catch (e) {
          print(e);
    }
  }
}

and this is my main.dart file

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:stock_market/pages/Models/news.dart';
import 'package:stock_market/pages/blogSpotHome.dart';
import 'package:stock_market/pages/bottomNavigation.dart';
import 'package:stock_market/pages/detailedPage.dart';
import 'package:stock_market/pages/investment_from_db.dart';
import 'package:stock_market/pages/options_from_db.dart';
import 'package:stock_market/pages/stock_from_db.dart';
import 'package:stock_market/pages/utils/route.dart';
import 'package:stock_market/pages/widgets/topNavigation.dart';
import 'package:stock_market/pages/widgets/newTile.dart';
import 'package:stock_market/pages/widgets/themes.dart';
import 'package:stock_market/services/local_notification_services.dart';
import 'pages/home_page.dart';
import 'pages/login.dart';
import 'package:bottom_nav_layout/bottom_nav_layout.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_notification_channel/flutter_notification_channel.dart';
import 'package:flutter_notification_channel/notification_importance.dart';
Future<void> _messageHandler(RemoteMessage message) async {

  print('background message ${message.notification!.body}');
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  LocalNotificationService.initialize();
 
  await Firebase.initializeApp();
  await  FirebaseMessaging.instance.subscribeToTopic("intraday");
   await  FirebaseMessaging.instance.subscribeToTopic("options");
     await  FirebaseMessaging.instance.subscribeToTopic("investment");
       await  FirebaseMessaging.instance.subscribeToTopic("blog");


  // If `onMessage` is triggered with a notification, construct our own
  // local notification to show to users using the created channel.
  // if (notification != null && android != null) {
  //   flutterLocalNotificationsPlugin.show(
  //       notification.hashCode,
  //       notification.title,
  //       notification.body,
  //       NotificationDetails(
  //         android: AndroidNotificationDetails(
  //           channel.id,
  //           channel.name,
  //           channelDescription: channel.description,
  //           icon: android.smallIcon,
  //           // other properties...
  //         ),
  //       ));
  // }


  runApp(MyApp());
}

// class MyApp extends StatefulWidget {
//   const MyApp({ Key? key }) : super(key: key);

//   @override
//   _MyAppState createState() => _MyAppState();

// }

// class _MyAppState extends State<MyApp> {
//   FirebaseMessaging messaging = FirebaseMessaging.instance;
//   // var androidSettings = AndroidInitializationSettings('app_icon');
//    @override
//   initState() {
//     super.initState();
//     ///app in background and user taps it
//     FirebaseMessaging.onMessageOpenedApp.listen((message) {
//       final routeFromMessage = message.data["route"];
//       Navigator.of(context).pushNamed(routeFromMessage);



//      });
//     // ignore: unused_local_variable
//     // var initializationSettingsAndroid =AndroidInitializationSettings('app_icon');

//   }

//   // void messagingF() async{
//   //     messaging.
//   // } 


  

  


  

//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp (
//     themeMode: ThemeMode.light,
//     theme: MyTheme.lightTheme(context),
//     darkTheme: MyTheme.darkTheme(context),
//     debugShowCheckedModeBanner: false,
//       home: MyHome(),

//     );
    
    
    
 
//   }
// }
// Future<void> _createNotificationChannel(String id, String name,
//     String description) async {
//   final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
//   var androidNotificationChannel = AndroidNotificationChannel(
//     id,
//     name,
   
//   );
  
//   await flutterLocalNotificationsPlugin
//       .resolvePlatformSpecificImplementation<
//       AndroidFlutterLocalNotificationsPlugin>()
//       ?.createNotificationChannel(androidNotificationChannel);
      
      
//     }


class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,

            routes: {
         MyRoute.homeRoute: (context) => MyHome(),
        // "/": (context) => WithTabBar(),
        "1": (_) => OptionsRoute(),
        "2": (_) => InvestMentRoute(),
        "3": (_) => NewsPage(),
        // "/news": (context) => const NewsPage(),
        // "/investment": (context) => const InvestMentRoute(),
       
        // MyRoute.dbRoute: (context) => DbRoute(),
        //  MyRoute.news: (context)  => NewsPage()
          
      },
            themeMode: ThemeMode.light,
      theme: MyTheme.lightTheme(context),
      // darkTheme: MyTheme.darkTheme(context),
      //       debugShowCheckedModeBanner: false,
        // home: Nav(),
        // home:MyHome()
      // home: HomePage(),]
      // initialRoute: MyRoute.news,
      // routes: {
      //   // MyRoute.loginRoute: (context) => LoginPage(),
      //   // MyRoute.homeRoute: (context) => HomePage(),
      //   // MyRoute.dbRoute: (context) => DbRoute(),
      //   //  MyRoute.news: (context) => MainNews()
          
      // },

    );
   
  }
}
class MyHome extends StatefulWidget {
  const MyHome({ Key? key }) : super(key: key);

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

class _MyHomeState extends State<MyHome> {
   @override
  initState() {
    super.initState();
    FirebaseMessaging.instance.getInitialMessage().then((message){
        if (message != null) {
             final routeFromMessage = message.data["route"];
                Navigator.of(context).pushNamed(routeFromMessage);
          
    print('Message also contained a notification: ${message.notification}');
  }


    });
    ///app in background and user taps it
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      final routeFromMessage = message.data["route"];
            Navigator.of(context).pushNamed(routeFromMessage);
       
       

    
        // Navigator.push(
        //         context,
        //          MaterialPageRoute(builder: (context) => routeFromMessage()),
        //       );
  // Navigator.pushNamed(context, routeFromMessage);
 


      // pushNamed(routeFromMessage);
          //  


     });


    FirebaseMessaging.onMessage.listen(( message) {
      
  // print('Got a message whilst in the foreground!');
  // print('Message data: ${message.data}');

  if (message.notification != null) {
    print('Message also contained a notification: ${message.notification}');
  }
  LocalNotificationService.display(message);  

});
  }
  @override
  Widget build(BuildContext context) {
        if (mounted){
        setState(() {
     WithTabBar();
    });
    }
 
 return WithTabBar(

        // home: Nav(),
        // home:WithTabBar(),

  
        
      // home: HomePage()
      // initialRoute:"/",


    );
    
  }
}

and this is my androidmanifest.xml file

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.stock_market">
       <uses-permission android:name="android.permission.INTERNET" />
   <application
        android:label="stock_market"
        android:icon="@mipmap/ic_launcher">

        <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_launcher" />
      
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
              <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="intraday"/>
            <intent-filter>
        
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
                 <action android:name="FLUTTER_NOTIFICATION_CLICK"/>
                  <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

and this is the error i am getting , now i know that the icon is causing this , but i have tried everything but nothing seems to work kindly provide a solution which can help

E/MethodChannel#dexterous.com/flutter/local_notifications( 7850): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850): 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( 7850):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:299)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:214)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1023)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1358)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1240)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at android.os.MessageQueue.next(MessageQueue.java:336)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at android.os.Looper.loop(Looper.java:182)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at android.app.ActivityThread.main(ActivityThread.java:7563)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
E/MethodChannel#dexterous.com/flutter/local_notifications( 7850):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
I/flutter ( 7850): 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
I/flutter ( 7850):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:299)
I/flutter ( 7850):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:214)
I/flutter ( 7850):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1023)
I/flutter ( 7850):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1358)
I/flutter ( 7850):  at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1240)
I/flutter ( 7850):  at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
I/flutter ( 7850):  at io

I have tried copying icon to different location and tried every solution available online kindly help me

CodePudding user response:

Change this code :

final InitializationSettings initializationSettings =
    InitializationSettings(
        android: AndroidInitializationSettings('@mipmap/ic_launcher'));

to this :

final InitializationSettings initializationSettings =
    InitializationSettings(
        android: AndroidInitializationSettings('ic_launcher'));

CodePudding user response:

I found the solution, The problem was i initiziled

 LocalNotificationService.initialize(context); 

in

void main() async {

}

instead it had to be done in ,

class MyHome extends StatefulWidget {
  const MyHome({ Key? key }) : super(key: key);

  @override


    class _MyHomeState extends State<MyHome> {
       @override
      initState() {
        super.initState();
        LocalNotificationService.initialize(context); 
        FirebaseMessaging.instance.getInitialMessage().then((message){
            if (message != null) {
                 final routeFromMessage = message.data["route"];
                    Navigator.of(context).pushNamed(routeFromMessage);
              
        print('Message also contained a notification: ${message.notification}');
      }
    
    
        });

hope this helps to anyone who is stuck here

  • Related