ingmbk
ingmbk

Reputation: 152

null safety Dart

I have 2 clasees one for user

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

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

and class message

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,
  }
  );

}

in class meesage i have defined a list of message

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,
  ),];

and in the main i want to change the color if Chats.unread is True for that i aded this line

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

But i get this error Try checking that the value isn't 'null' before using it as a condition how to avoid null safety in Dart !

Upvotes: 1

Views: 116

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63604

You are using ternary operator,

use like true? onTrueValue: falseValue.

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

Upvotes: 0

enzo
enzo

Reputation: 11496

You should use the ?? operator instead of only ?:

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

In some cases, you can avoid this check by rethinking your model. For example, if a message can only have two states - read and unread -, you can require to whoever create an instance of Message to pass a value to the unread parameter. If that's the case, you can do something like that:

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,
  });
}

You can do the same for isLiked and sender.

Upvotes: 1

Related Questions