如何在使用 flutter_local_notifications 时在 Flutter 中将 Future<Null> 转换为 Future<dynamic>?

问题描述

我在 Flutter 中使用 Flutter_local_notifications 插件,在初始化它时出现了这个错误

The argument type 'Future<Null> Function(int,String,String)' can't be assigned to the parameter type 'Future<dynamic> Function(int,String?,String?)?'

我使用的代码是:

void main() async {
  SystemChrome.setEnabledsystemUIOverlays([systemUIOverlay.bottom]);
  WidgetsFlutterBinding.ensureInitialized();

  WidgetsFlutterBinding.ensureInitialized();

  var initializationSettingsAndroid = AndroidInitializationSettings('logo');
  var initializationSettingsIOS = IOSInitializationSettings(
      requestAlertPermission: true,requestBadgePermission: true,requestSoundPermission: true,onDidReceivelocalnotification:
          (int id,String title,String body,String payload) async {}),//Error on this line
          
        
  var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,iOS: initializationSettingsIOS);
  await FlutterlocalnotificationsPlugin.initialize(initializationSettings,onSelectNotification: (String payload) async {
    if (payload != null) {
      debugPrint('notification payload: ' + payload);
    }
  });
  runApp(MyApp());
}

有没有办法在这函数中将 Future 转换为 Future>?
帮助将不胜感激。谢谢!

解决方法

您似乎正在使用该软件包的 null safe 版本。

随着 null-safetyNullable 类型的引入,您需要仔细检查包提供的参数。

onDidReceiveLocalNotification 不保证 titlebodypayload 不会为空。这就是为什么定义在他们的代码中,

typedef DidReceiveLocalNotificationCallback 
  = Future<dynamic> Function(int id,String? title,String? body,String? payload);

注意 ? 符号表示它们是 Nullable 类型,因此您应该以相同的方式定义回调。

把你的代码改成这个,

onDidReceiveLocalNotification:
      (int id,String? payload) async {})
,

得到了解决方案,关于flutter中的NULL安全性
将错误行更改为:

onDidReceiveLocalNotification:
          (int id?,String title?,String body?,String payload?) async {}),//Error on this line