【问题标题】:flutter notification - Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference颤振通知 - 尝试在空对象引用上调用虚拟方法“int java.lang.Integer.intValue()”
【发布时间】:2022-01-04 23:25:00
【问题描述】:

我正在尝试使用 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);
}

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

 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.

我的 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

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

E/MethodChannel#dexterous.com/flutter/local_notifications(7752): 处理方法调用失败 E/MethodChannel#dexterous.com/flutter/local_notifications(7752): java.lang.NullPointerException:尝试调用虚拟方法'int 空对象引用上的 java.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(错误,尝试调用虚拟方法 '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/颤动​​(7752):在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:215) E/颤动​​(7752):在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1024) E/颤动​​(7752):在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1362) E/颤动​​(7752):在 com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1241) E/颤动​​(7752):在 io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262) E/颤动​​(7752):在 io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178) E/颤动​​(7752):在 io.flutter.embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206) E/颤动​​(7752):在 io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$6ZD1MYkhaLxyPjtoFDxe45u43DI.run(未知 来源:12)E/颤振(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(Native Method) E/颤动​​(7752):在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) E/颤动​​(7752):在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E/flutter (7752):)电子/颤振(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/颤振(7752):#2
FlutterLocalNotificationsPlugin.show (包:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:194:7) E/颤振(7752):

【问题讨论】:

  • 分享您的 pubspec.yaml - 您使用的是什么版本的 fl_lo_no?也许它已经过时了。
  • 您是否遵循了这里的所有 Android 前置要求? pub.dev/packages/flutter_local_notifications#-android-setup
  • 你初始化flutter本地通知了吗?
  • 抱歉我的无知,但我如何确保我的插件已更新? #理查德堆
  • 类中的第一行初始化了颤振本地通知,对吗?

标签: flutter notifications


【解决方案1】:

有了这个截图,你可以发送本地通知

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),
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2020-11-28
    • 1970-01-01
    • 2015-01-24
    • 2020-09-17
    相关资源
    最近更新 更多