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

How to cast Future<Null> to Future<dynamic> in Flutter while using flutter_local_notifications?

我在 flutter 中使用 flutter_local_notifications 插件,在初始化它时遇到了这个错误。

The argument type 'Future<Null> Function(int, String, String, String)' can't be assigned to the parameter type 'Future<dynamic> Function(int, String?, 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>?
帮助将非常感激。谢谢!

解决了,关于flutter中的NULL Safety
将错误行更改为:

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

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

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

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

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

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

将您的代码更改为此,

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