'Should you use required named parameters when making a data model in flutter?

Is it good practice to require named parameters for data models in flutter when you know that the data should always have a specific field like an id or username? I think this would remove unnecessary null checking, but I've always seen model classes just use named parameters with fromJson and toJson methods especially if the data is being pulled from a database like Firebase. So is there a reason not to require fields?

Also when would it be a good idea to require a String field and initially populate it with an empty String vs making it nullable and initializing it with a null value?



Solution 1:[1]

Below is my opinion, i'm not sure it's true for all but it works for me

Reason 1: it's too long and unnecessary to write the whole thing out, some Jsons can be very complicated to do this, moreover when you get the data in JSON you'll want to simply initialize var A = A.fromJson(jsonData) instead of having to pass it one by one into the Model, moreover this can be repeated many times.

Reason 2: String with null(String?) and String with empty value(String) is very different. With me, I use String? to determine that "it has not received value yet", if the value is non-null then it has received a value including empty. In contrast to a String whose initial value is empty, I cannot distinguish whether it has received empty or has not received data.

Example: when i assign empty value to text2, it cannot distinguish whether it received the value before. This can be used to calculate the display of the Indicators before the variable actually gets a value.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tuan