Search code examples
flutterdartgetter-setterdart-null-safety

The return type of getter 'description' is 'String?' which isn't a subtype of the type 'String' of its setter 'description'


I have created method where one of my parameters are option so, I used [] to declare optional parameters. For that I have make _description nullable. but when I use it in getters and setters it is giving me error says "The return type of getter 'description' is 'String?' which isn't a subtype of the type 'String' of its setter 'description'." can anyone please help me?

class Note {
  late int _id;
  late String _title;
  late String? _description;
  late String _date;
  late int _priority;

  Note(this._title, this._date, this._priority, [this._description]);
  Note.withId(this._id, this._title, this._date, this._priority,
      [this._description]);

  // All the getters
  int get id => _id;
  String get title => _title;
  String? get description => _description;
  String get date => _date;
  int get priority => _priority;

  // All the setters
  set title(String newTitle) {
    if (newTitle.length <= 255) {
      this._title = newTitle;
    }
  }

  set description(String newDescription) {
    if (newDescription.length <= 255) {
      this._description = newDescription;
    }
  }

  set date(String newDate) {
    this._description = newDate;
  }

  set priority(int newPriority) {
    if (newPriority >= 1 && newPriority <= 2) {
      this._priority = newPriority;
    }
  }
}

I have tried getter make nullble


Solution

  • I think it is because in the get method you have String? get description => _description; with ? to check if it is null. But in your setter you have

     set description(String newDescription) {
        if (newDescription.length <= 255) {
          this._description = newDescription;
        }
      }
    

    That doesn't have the ?. Try this:

     set description(String? newDescription) {
        if (newDescription!.length <= 255) {
          this._description = newDescription;
        }
      }