【问题标题】:null safety Dart零安全飞镖
【发布时间】:2021-10-11 13:31:36
【问题描述】:

我有 2 个类别供用户使用

class User {
  final int? id;
  final String name;
  final String imageUrl;

  User({
     this.id ,
     this.name ='',
     this.imageUrl='',
  });
}

和课堂信息

import 'package:flutter/material.dart';
import 'package:flutter_chat/models/user_models.dart';
class Message {
  final String time; // Would usually be type DateTime or Firebase Timestamp in production apps
  final String text;
  final bool? isLiked;
  final bool? unread;
  final User? sender;


  Message(
      {
         this.sender,
         this.time='',
          this.text='',
         this.isLiked,
     this.unread,
  }
  );

}

在课堂上我已经定义了一个消息列表

List <Message> Chats = [
  Message(
    sender: james,
    time: '5:30 PM',
    text: 'Hey, how\'s it going? What did you do today?',
    isLiked: false,
    unread: true,
  ),
  Message(
    sender: olivia,
    time: '4:30 PM',
    text: 'Hey, how\'s it going? What did you do today?',
    isLiked: false,
    unread: true,
  ),];

如果 Chats.unread 为 True,我主要想更改颜色,因为我添加了这一行

color: Chats[index].unread ? Color(0xFFFDEFE1),

但我收到此错误尝试在将其用作条件之前检查该值是否不是“空” 如何避免 Dart 中的 null 安全性!

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您应该使用?? operator 而不仅仅是?

    color: Chats[index].unread ?? Color(0xFFFDEFE1),
    

    在某些情况下,您可以通过重新考虑您的模型来避免这种检查。例如,如果一条消息只能有两种状态——已读和未读——,您可以要求创建Message 实例的任何人将值传递给unread 参数。如果是这种情况,您可以这样做:

    class Message {
      final String time;
      final String text;
      // There's not need to use a nullable type here
      final bool unread;
      final bool? isLiked;
      final User? sender;
    
      // Since all fields are final, you can use `const` here
      const Message({
        this.sender,
        this.time='',
        this.text='',
        this.isLiked,
    
        // You can choose one of the two cases below:
        // CASE 1: The caller MUST pass the unread paramater
        required this.unread,
        // CASE 2: The caller may not pass the unread parameter, which will default to false
        this.unread = false,
      });
    }
    

    您可以对isLikedsender 执行相同的操作。

    【讨论】:

      【解决方案2】:

      您正在使用三元运算符,

      使用喜欢 true? onTrueValue: falseValue.

      color: Chats[index].unread==null ? Color(0xFFFDEFE1): Colors.red,

      【讨论】:

      • 它仍然是同样的问题,与未读有关,它是一个聊天的 boll var,错误是在将其用作条件之前尝试检查该值是否不是“空”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多