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

Posted

技术标签:

【中文标题】使用flutter_local_notifications时如何在Flutter中将Future<Null>转换为Future<dynamic>?【英文标题】:How to cast Future<Null> to Future<dynamic> in Flutter while using flutter_local_notifications? 【发布时间】:2021-08-17 19:47:32 【问题描述】:

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

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

【问题讨论】:

这是哪个包? local_notifications 还是 flutter_local_notifications ? flutter_local_notifications 【参考方案1】:

您似乎正在使用该软件包的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 )

【讨论】:

【参考方案2】:

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

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

【讨论】:

写了一个关于类型的详细答案。如果您觉得它有用,请考虑接受它。

以上是关于使用flutter_local_notifications时如何在Flutter中将Future<Null>转换为Future<dynamic>?的主要内容,如果未能解决你的问题,请参考以下文章

在使用加载数据流步骤的猪中,使用(使用 PigStorage)和不使用它有啥区别?

今目标使用教程 今目标任务使用篇

Qt静态编译时使用OpenSSL有三种方式(不使用,动态使用,静态使用,默认是动态使用)

MySQL db 在按日期排序时使用“使用位置;使用临时;使用文件排序”

使用“使用严格”作为“使用强”的备份

Kettle java脚本组件的使用说明(简单使用升级使用)