颤振通知 - 尝试在空对象引用上调用虚拟方法“int java.lang.Integer.intValue()”

Oz *_*hen 7 notifications flutter

我正在尝试使用 flutter_local_notifications 创建本地通知 首先,我为我的项目创建了 API 类:

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);
}
Run Code Online (Sandbox Code Playgroud)

然后我用浮动按钮触发通知:

 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.
Run Code Online (Sandbox Code Playgroud)

我的 pubspec.yaml 文件:

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
Run Code Online (Sandbox Code Playgroud)

当我按下按钮而不是显示通知时,输出是:

E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): 无法处理方法调用 E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): java.lang.NullPointerException: 尝试调用虚拟方法 'int java.lang. lang.Integer.intValue()' 在空对象引用上 E/MethodChannel#dexterous.com/flutter/local_notifications( 7752):位于 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:300) E/MethodChannel#dexterous .com/flutter/local_notifications(7752):在com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:215)E/MethodChannel#dexterous.com/flutter/local_notifications(7752):在com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin .showNotification(FlutterLocalNotificationsPlugin.java:1024)E/MethodChannel#dexterous.com/flutter/local_notifications(7752):在com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1362)E/MethodChannel#dexterous.com/flutter /local_notifications(7752):在com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1241)E/MethodChannel#dexterous.com/flutter/local_notifications(7752):在io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler .onMessage(MethodChannel.java:262) E/MethodChannel#dexterous.com/flutter/local_notifications(7752):位于 io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178) E/MethodChannel#dexterous .com/flutter/local_notifications(7752):在io.flutter.embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206)E/MethodChannel#dexterous.com/flutter/local_notifications(7752) :位于io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$6ZD1MYkhaLxyPjtoFDxe45u43DI.run(来源未知:12)E/MethodChannel#dexterous.com/flutter/local_notifications(7752):位于android.os.Handler。 handleCallback(Handler.java:873)E/MethodChannel#dexterous.com/flutter/local_notifications(7752):在android.os.Handler.dispatchMessage(Handler.java:99)E/MethodChannel#dexterous.com/flutter/local_notifications(第7752章):在android.os.Looper.loop(Looper.java:193)E/MethodChannel#dexterous.com/flutter/local_notifications(7752):在android.app.ActivityThread.main(ActivityThread.java:6669)E/ MethodChannel#dexterous.com/flutter/local_notifications(7752):在java.lang.reflect.Method.invoke(本机方法)E/MethodChannel#dexterous.com/flutter/local_notifications(7752):在com.android.internal.os .RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) E/MethodChannel#dexterous.com/flutter/local_notifications( 7752): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E/flutter (7752):[错误:flutter/lib/ui/ui_dart_state.cc(209)]未处理的异常:PlatformException(错误,尝试在 null 对象引用上调用虚拟方法 'int java.lang.Integer.intValue()',null,java.lang.NullPointerException:尝试调用虚拟方法 'int java.lang.Integer.intValue( )' 在空对象引用上 E/flutter (7752):在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:300) E/flutter (7752):在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin) .java:215) E/flutter ( 7752): 在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1024) E/flutter ( 7752): 在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java :1362)E/flutter(7752):在com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1241)E/flutter(7752):在io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel) .java:262) E/flutter (7752): 在 io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178) E/flutter (7752): 在 io.flutter.embedding.engine.dart .DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206) E/flutter ( 7752):位于 io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$6ZD1MYkhaLxyPjtoFDxe45u43DI.run(来源未知:12) E/flutter(7752):在android.os.Handler.handleCallback(Handler.java:873) E/flutter(7752):在android.os.Handler.dispatchMessage(Handler.java:99)E/flutter(7752) :在 android.os.Looper.loop(Looper.java:193) E/flutter (7752):在 android.app.ActivityThread.main(ActivityThread.java:6669) E/flutter (7752):在 java.lang。 Reflect.Method.invoke(本机方法)E/flutter(7752):在com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)E/flutter(7752):在com.android.internal .os.ZygoteInit.main(ZygoteInit.java:858) E/flutter (7752): ) E/flutter (7752): #0显示(FlutterLocalNotificationsPlugin.java:1362)E / flutter(7752):在com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1241)E / flutter(7752):在io.flutter.plugin.common.MethodChannel $ IncomingMethodCallHandler.onMessage(MethodChannel.java:262) E/flutter (7752):在 io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178) E/flutter (7752):在 io.flutter。 embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206) E/flutter ( 7752): 在 io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$6ZD1MYkhaLxyPjtoFDxe45u43DI.run(来源未知:12) E/flutter ( 7752): 在 android.os.Handler.handleCallback(Handler.java:873) E/flutter ( 7752): 在 android.os.Handler.dispatchMessage(Handler.java:99) E /flutter(7752):在android.os.Looper.loop(Looper.java:193)E / flutter(7752):在android.app.ActivityThread.main(ActivityThread.java:6669)E / flutter(7752):在java.lang.reflect.Method.invoke(本机方法)E / flutter(7752):在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493)E / flutter(7752):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E/flutter (7752): ) E/flutter (7752): #0显示(FlutterLocalNotificationsPlugin.java:1362)E / flutter(7752):在com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1241)E / flutter(7752):在io.flutter.plugin.common.MethodChannel $ IncomingMethodCallHandler.onMessage(MethodChannel.java:262) E/flutter (7752):在 io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178) E/flutter (7752):在 io.flutter。 embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206) E/flutter ( 7752): 在 io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$6ZD1MYkhaLxyPjtoFDxe45u43DI.run(来源未知:12) E/flutter ( 7752): 在 android.os.Handler.handleCallback(Handler.java:873) E/flutter ( 7752): 在 android.os.Handler.dispatchMessage(Handler.java:99) E /flutter(7752):在android.os.Looper.loop(Looper.java:193)E / flutter(7752):在android.app.ActivityThread.main(ActivityThread.java:6669)E / flutter(7752):在java.lang.reflect.Method.invoke(本机方法)E / flutter(7752):在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493)E / flutter(7752):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E/flutter (7752): ) E/flutter (7752): #0
StandardMethodCodec.decodeEnvelope (包:flutter/src/services/message_codecs.dart:607:7) E/flutter (7752): #1 MethodChannel._invokeMethod (包:flutter/src/services/platform_channel.dart:167:18) E /flutter(7752):E/flutter(7752):#2
FlutterLocalNotificationsPlugin.show(包:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:194:7)E/flutter(7752):

Fab*_*ien 3

有了这个片段,您可以发送本地通知

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),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)