【问题标题】:Meaning of `?.` in Flutter with respect to RemoteMessage`?.` 在 Flutter 中相对于 RemoteMessage 的含义
【发布时间】:2021-09-11 11:48:31
【问题描述】:

https://pub.dev/documentation/firebase_messaging_platform_interface/latest/firebase_messaging_platform_interface/RemoteMessage/RemoteMessage.html

RemoteMessage 确实有一个名为 notification 的字段。
但是当我们说:message.notification?.title 是什么意思?

? 表示该字段可以为空,但是当我们说?.title 时,是否意味着notification 中有一个title 字段我们正在尝试访问

https://blog.logrocket.com/flutter-push-notifications-with-firebase-cloud-messaging/

   FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      // Parse the message received
      PushNotification notification = PushNotification(
        title: message.notification?.title,
        body: message.notification?.body,
      );
   }

【问题讨论】:

    标签: firebase flutter firebase-cloud-messaging


    【解决方案1】:

    很快 - 是的,您正在尝试访问 title 并且您知道它可以为 null

    这是零安全性。 来自https://dart.dev/codelabs/null-safety

    如果您希望 String 类型的变量接受任何字符串或 null 值,请通过在类型名称后添加问号 (?) 为变量指定可空类型。例如,String 类型的变量?可以包含字符串,也可以为空。

    另外:

    如果你确定一个可空类型的表达式不为空,你可以使用空断言运算符 (!) 让 Dart 将其视为不可空。

    通过添加!就在表达式之后,告诉 Dart 该值不会为空,并且将其分配给不可为空的变量是安全的。

    【讨论】:

    • 请指出Flutter的API文档。示例 - showSimpleNotification() API 文档在哪里?
    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 2023-01-03
    • 2012-12-26
    • 2018-05-16
    • 2019-12-03
    • 2012-08-01
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多