json_serializable not generating code for final fields and getters - flutter

This is my class:
#JsonSerializable()
class Foo {
final int a = 0;
int get b => 42;
}
The generated code doesn't include any of the a or b field:
Foo _$FooFromJson(Map<String, dynamic> json) => Foo();
Map<String, dynamic> _$FooToJson(Foo instance) => <String, dynamic>{};
Note: Please don't write solutions for doing something like Foo(this.a) or Foo() : a = 0 etc. I need to keep my structure as it is.

Simple answer - this won't be possible as this is done intentionally by design.
If adjusting your model structure is out of the question, you can try manual conversion or a mix of these two.
After encountering the same issues myself, not long ago, I opted in for manual converting my models - and also a combination of two in some cases.
With #JsonSerializable, you can make use of the from/to generated methods, and then in addition, manually convert your final and getter fields.
Another option you can try, at least for the getter fields, is making use of #JsonSerializable(crateFactory: false). This will indicate the engine to convert getters as well.
I suggest reading Flutter JSON Docs in detail and figuring out what will suit you the most, depending on your models, what you want, or what you can compromise on.
Worth reading the Github thread on getter conversion.
There's no out of the box workaround for final fields though, but as per this Github thread on final fields, PRs are welcome :)

If you want easier json parsing, use Dart Data Class Generator extension in VS Code.

I think since a is final, it is considered a constant and not variable and b is a getter and not a variable, there are no variables (fields) for json_serializable to generate code for.
You need to add a default constructor before json_serializable can run. Since you have no fields, you wil have an empty constructor and empty methods generated.
class Foo {
final int a = 0;
int get b => 42;
const Foo();
factory Foo.fromJson(Map<String, dynamic> json) => Foo();
Map<String, dynamic> toJson() => <String, dynamic>{};
}

Related

Dynamic Type Casting in Dart/Flutter

I am in the middle of writing a library to dynamically serialise/deserialise any object in Dart/Flutter (Similar in idea to Pydantic for Python). However, I am finding it impossible to implement the last component, dynamic type casting. This is required in order convert types from JSON, such as List to List (or similar). The types are retrieved from objects using reflection.
The below is the desired implementation (though as far as I understand this is not possible in Dart).
Map<String, Type> dynamicTypes = {"key": int };
// Regular casting would be "1" as int
int value = "1" as dynamicTypes["key"];
Is there some workaround which makes this possible to implement? Or have I reached a dead end with this (hence no other dynamic serialisation/deserialisation package already exists).
Conducting more research into this issue, it seems in Dart's current implementation this is impossible due to runtime reflection being disabled as referenced here in the official docs.
There are ongoing discussions about the support for this and the associated package dart:mirrors here on GitHub, but so far though there is some desire for such functionality it is highly unlikely to ever be implemented.
As a result, the only options are:
Use code generation libraries to generate methods.
Manual serialisation/deserialisation methods.
Implement classes with complex types such as lists and maps to be dynamic, enabling (all be it limited) automatic serialisation/deserialisation.
Your question does not specify how exactly dynamicTypes is built, or how its key is derived. So there is perhaps a detail to this that is not clear to me.
But what about something like this?
class Caster<T> {
final T Function(String) fromString;
Caster(this.fromString);
}
void main() {
Map<String, Caster> dynamicTypes = { "key": Caster<int>((s) => int.parse(s)) };
int v = dynamicTypes['key']!.fromString('1');
print(v);
}
Or, if you have the value as a dynamic rather than a string:
class Caster<T> {
T cast(dynamic value) => value as T;
}
void main() {
Map<String, Caster> dynamicTypes = { "key": Caster<int>() };
dynamic a = 1;
int v = dynamicTypes['key']!.cast(a);
print(v);
}
Or even more succinctly:
void main() {
dynamic a = 1;
int v = a;
print(v);
}

Access class variables like objects using strings in dart/flutter

I have a class called preferences below
preferences.dart:
class Preferences {
Map<String, int> cuisineTypes;
Map<String, int> mealSpecialties;
Map<String, int> allergiesAndDietaryRestrictions;
Preferences({
required this.cuisineTypes,
required this.mealSpecialties,
required this.allergiesAndDietaryRestrictions
});
}
I want to update the variables in this class based on the string preferenceCategory. My code currently has to look like three lines to accomplish this.
if(preferenceCategory == 'cuisineTypes') localGlobalState.person.preferences!.cuisineTypes[preferenceType] = preferenceValueUpdated;
if(preferenceCategory == 'mealSpecialties') localGlobalState.person.preferences!.mealSpecialties[preferenceType] = preferenceValueUpdated;
if(preferenceCategory == 'allergiesAndDietaryRestrictions') localGlobalState.person.preferences!.allergiesAndDietaryRestrictions[preferenceType] = preferenceValueUpdated;
I would like to accomplish this on one line like below, but I can't because class variables can't be accessed by strings like objects.
localGlobalState.person.preferences![preferenceCategory][preferenceType] = preferenceValueUpdated;
Is there alternative around this? My restriction is that I can't/shouldn't update preferences.dart if I don't have to.

New list still references old list after being cloned

I have a list of maps which are initialized as follow
List<dynamic> _people = [];
Map<String, dynamic> _person = {
'image' : null,
'name': null,
'age': null
};
On one of the methods inside the program I intend to copy the value inside _people to a new List variable so I can make changes to it.
List _peopleCopy = List.from(_people);
for (var i=0; i < _people.length; i++) {
if (_people[i]['image'] != null) {
List<num> img = new List.from(_people[i]['image'].readAsBytesSync());
_peopleCopy[i]['image'] = img;
}
}
Now the problem here is that everytime I assign the value of img to _peopleCopy, it would change the respective value on _people list as well even though I did List.from() method to clone it. Obviously, I wanted to preserve the original content of _people list. What did I do wrong here?
For such case what I do is, I store the originalJson of the object inside a variable in the object class like below,
class People {
int? age;
String? image;
String? name;
Map<String, dynamic> originalJson = {};
People({this.age, this.image, this.name});
People.fromJson(Map<String, dynamic> json) {
originalJson = json;
age = json['age']?.toInt();
image = json['image']?.toInt();
name = json['name']?.toString();
}
Map<String, dynamic> toJson() {
'age' = age;
'image' = image;
'name' = name;
}
}
So when you are parsing the http reponse, now all you have to do is,
People.fromJson(json.decode(response.body));
This way you can preserve the json and while cloning the list of People, all you have to do is,
// With the following line _people will now be new list with new objects but with mutated _people data
_people = _people.map((e) => People.fromJson(e.toJson())).toList();
// With the following line _people will now be new list with new objects but with data which we have recieved from the API call
_people = _people.map((e) => People.fromJson(e.originalJson)).toList();
This way of maintaining the class should for sure help you out..
You have successfully created a new list. But the list contains the references to the same maps. So changing a map will change it in both lists since it's the same element.
You need to copy the elements, too.
Since your map also contains a dynamic type that you probably want to deep copy, I would suggest to just jsonEncode/jsonDecode your whole structure. Serializing and Deserializing is not the most efficient way, but it will create a deep copy of whatever structure is in there.
That said, Dart is a real programming language. It helps a lot to use it that way. If you use actual types, instead of dynamic, it becomes less guessing, praying and duct-typing and more solid, fact based programming. Since this seem to be JSON structures, use model classes. Then you can have your own deep copy methods and have compiler support that you just don't get when you use dynamic.

Use a variable to sort by a key in a List<Map> instead of explicitly naming the key name

This is probably very easily answered, but I got a little stumped. Couldn't find a reference this this kind of question anywhere, which seems amazing.
I have a List<Map> and I want to sort it by the key provided through a variable instead of explicitly naming the key to sort by.
Here is what I have:
adminList.sort((a, b) => (b.sortField).compareTo(a.sortField));
AdminList is my List<Attendee> and a & b want my constructor (key) names ("firstName," "lastName," etc) and won't let me substitute a variable, as toString or anything I've tried. I want to use sortName, which might be assigned as "firstName" now, "lastName" later.
I figured this out. So technically, my named class was not a map, though it feels like one to this novice coder, and in order to access members by a string variable, I needed to create a toMap function within my class, call that, and reference my variable like so:
class AttendeeData {
final String firstName;
final String lastName;
AttendeeData({this.firstName, this.lastName,});
Map<String, dynamic> toMap() {
return {
'firstName':firstName,
'lastName:'lastName,};
}}
Now, I can define sortField, and filter by it. Changing it to lastName whenever I want.
String sortField = 'firstName';
adminList.sort(
(a, b) => (a.toMap()[sortField]).compareTo(b.toMap()[sortField]));

Deserialise JSON response from API into type in Dart

I'm going out of my mind trying to figure this out because it's such a simple thing to do and there's no information on it anywhere.
I have an API call that is returning a Student which is defined like this
class Student {
String photo;
String upn;
String fullName;
String studentClass;
String studentYear;
}
I'm using the dart http library to make a call to an API that returns an array of a number of students. All I want to do is deserialise the string returned by the API into a typed list so that I can actually do something with it.
studentFuture.then((res) {
log(res.body.toString());
List<dynamic> dynamicList = jsonDecode(res.body);
var student = dynamicList[0] as Student;
});
Trying to cast it to Student using as doesn't work, I just get this
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Student' in type cast
All I want is to be able to do something like this like you can in C#
var obj = DeserialiseJson<Type>(jsonString);
No matter what I try I can't get the string to be deserialised into an object, how do I do this?
You can't do this in Dart/Flutter in the way that you want. This is because in order to accomplish this functionality in C#, Java, or any other strongly-typed language that supports this feature, the language uses reflection under the hood to map JSON fields to object fields.
Dart also has reflection functionality in the dart:mirror library. However, this library is disabled in Flutter due to its tendency to create large app footprints due to all the debug information for various types and fields and things needing to be included in the compiled binary. (That's the very simple explanation: the official reason given by the Flutter team goes into more detail.)
What this means is when you deserialize a JSON string, you get an object that is essentially a List<dynamic> or Map<String, dynamic> (depending on the JSON string in question; it may even just be some primitive value). Assuming the latter, you cannot directly convert between a Map and a Student because they are completely different types with nothing in common. There is no implicit way to take the Map and generate a Student because the reflection tools necessary to do so don't exist within a Flutter app. As a result, you get an error saying you cannot convert a Map to a Student, as you can see.
To work around this, you are encouraged to add a toJson/fromJson method to your model class so you can explicitly generate an instance of the class from a deserialized JSON string:
class Student {
String photo;
String upn;
String fullName;
String studentClass;
String studentYear;
factory Student.fromJson(Map<String, dynamic> jsonData) {
return Student()
..photo = jsonData['photo']
..upn = jsonData['upn']
..fullName = jsonData['fullName']
..studentClass = jsonData['studentClass']
..studentYear = jsonData['studentYear'];
}
}
And use it like so:
studentFuture.then((res) {
log(res.body.toString());
List<dynamic> dynamicList = jsonDecode(res.body);
var student = Student.fromJson(dynamicList[0]);
});
This is all well and good, but if you have more than a few model classes you will quickly realize that adding this boilerplate code to every model class gets really tedious really quick. That's why various packages exist to try and alleviate the burden with automatic code generation, such as json_serializable and freezed.
TL;DR: What you are asking for is not currently possible in Flutter Dart, and that isn't likely to change any time soon. You need to either write a manual factory constructor to make the conversion or use a code-gen package that generates the constructors for you.
Have a look at https://pub.dev/packages/json_serializable which, through code generation, will give you methods like
#JsonSerializable()
class Student {
String photo;
String upn;
String fullName;
String studentClass;
String studentYear;
Student({this.photo, this.upn, this.fullName, this.studentClass, this.studentYear});
factory Student.fromJson(Map<String, dynamic> json) => _$StudentFromJson(json);
Map<String, dynamic> toJson() => _$StudentToJson(this);
}
Then you can do:
var list = jsonDecode(res.body);
for (var map in list) {
print(Student.fromJson(map)); // Student class
}