skip to Main Content
class Quote {
  String text;
  String author;

  Quote({ this.text, this.author });
}

In vscode, without required, it will shown me error and force me to add required inside the constructor before this.text

class Quote {
  String text;
  String author;

  Quote({ required this.text, required this.author });
}

This is the answer that copilot recommend me to do so? But I’m confuse why does I need to add required before this.text???

2

Answers


  1. In situation where if you want that while calling this class the value must be given those variables should be marked as required, and to do so you directly create a variable and require it, just like below.

    class Quote {
      String text;
      String author;
    
      Quote({required this.Text, required this.Author });
    }
    

    but if you are aware that this value is not necessary to be passed while calling this class, you can make it nullable, while making it nullable either you can give it a default value or just mark it as nullable using ?

    class Quote {
      String? text;
      String? author = 'xyz';
    
      Quote({this.Text, this. Author });
    }
    

    Now you can call this class with or without passing any value, but you should keep in mind that since the text variable is nullable and it also doesn’t have any default value, so if you didn’t pass the value to text and tried to use the value of it, it will throw and error, to overcome this you can use null check operator ??

    Quote myQuote = Quote();
    print(myQuote.text);
    

    Now since neither i have passed the value to text nor it has any default value, and so it will cause an error, to overcome this you can do it like,

    print(myQuote.text ?? 'Text is empty');
    

    Now if the text value is not empty then the myQuote.text value will be printed else 'Text is empty' wil be printed.

    Login or Signup to reply.
  2. When you define a property without’?’ it means that the property cannot be null so when you want to create an instance of this class you must define a value of the property. if you do not want the required property you must put ‘?’ after the type which means the property can be null.

    class Quote {
      String? text;
      String author;
    
      Quote({ this.text,required this.author });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search