You need to enable JavaScript to run this app. 使用flutter_local_notifications显示本地通知时空值校验运算符报错
优惠活动
大模型
产品
解决方案
定价
更多

使用flutter_local_notifications显示本地通知时空值校验运算符报错

问题原因

报错是因为在执行插件初始化操作前,未提前初始化Flutter的Widgets绑定,导致和原生端通信的平台通道尚未就绪,触发了空安全异常。

解决步骤

  1. 在main函数的最开头添加WidgetsFlutterBinding.ensureInitialized(),确保在调用任何和原生交互的插件逻辑前,Flutter引擎绑定已完成初始化。
  2. 调整selectNotification方法的入参类型为可空类型String?,匹配插件最新的参数要求。

修正后完整代码

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() async {
  // 新增这行,优先初始化Widgets绑定
  WidgetsFlutterBinding.ensureInitialized();
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

// added boat.png in the drawables folder
  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('boat.png');

  final InitializationSettings initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
    iOS: null,
    macOS: null,
  );
  await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: selectNotification);

  void showNotification() async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
            'your channel id', 'your channel name', 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            showWhen: false);
    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
        0, 'plain title', 'plain body', platformChannelSpecifics,
        payload: 'item x');
  }

  showNotification();
  runApp(MyApp());
}

// 调整入参为可空类型String?
Future selectNotification(String? payload) async {
  if (payload != null) {
    debugPrint('notification payload: $payload');
  }
  // Modified the example code - it navigated to a different screen. I am just printing the payload
  print(payload); 
}

内容的提问来源于stack exchange,提问作者Anshul Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 18:54:03