Get Class Properties - reflection

I'm need a way to get the properties of a class, as I know this is with reflection, but I don't know how to apply it to Flutter.
This is my class:
class Login {
final String name;
final String email;
final String token;
final String refreshToken;
final String createdAt;
final String expiresAt;
final bool isValid;
Login({this.name, this.email, this.token, this.refreshToken, this.createdAt, this.expiresAt, this.isValid});
}
And I have to do something like getOwnProperties like is done in JS.
I need to get an array of the properties that the class has.

There is no reflection available in Flutter. You can use code generation for example with the reflectable package or custom generation using https://pub.dartlang.org/packages/build

Related

Dart T type- fromJson implementation

I have a normal class like this
class University implements BaseResponseContract {
final String? name;
final int? id;
University({required this.id, required this.name});
factory University.fromJson(Map<String, dynamic> json) => _$UniversityFromJson(json);
Map<String, dynamic> toJson() => _$UniversityToJson(this);
}
and this is BaseResponseContract
abstract class BaseResponseContract<T> {
factory T.fromJson(Map<String, dynamic> json);
}
This gives an error now, I want to correct and
I want to build a general Firebase class to read datas so that I dont have to write from scratch everytime,
abstract class IFirebaseEntity<T> {
final String collectionName;
late final instance;
IFirebaseEntity(this.collectionName) {
instance = FirebaseFirestore.instance.collection(collectionName)
.withConverter(fromFirestore: (snapshot,_)=>**T.fromJson(snapshot)**, toFirestore: toFirestore);
}
However it doesn't work. It doesn't recognize T.fromJson() method,
I want to build a Firebase Entity class to build such a functionality that, I will extend with a T and will be able to use that firebase class generated by the abstract class.
This is an example that extends this FirebaseEntity
class ReadUnivercities extends IFirebaseEntity<University> {
ReadUnivercities(String collectionName) : super(collectionName);
}

Best approach to define models on a flutter firebase application

First let me give you a little bit of context. I'm currently working on a Flutter app using firebase. This is the first app that I make using firebase as a backend for flutter. So, I'm looking for recommendations of which would be the best approach.
First, I have the next model which I use to register a new user into my app.
class user {
String userName;
String firstName;
String lastName;
String password;
String email;
}
My doubt comes when I make the process, so my user can sign up into my app. I want to retrieve my user's ID (document id) from firebase.
Because my app bases on interactions between users. So, when user A sends a request to user B, user B muss be able to see that request, so I need a way to store those request between users on a collection and I plan to use the ID of my users to store those relations between users.
So, would you recommend me to create two separate models like the next two?
One for a new user that just signed in, and another one for a user which signs up.
class newUser {
String userName;
String firstName;
String lastName;
String password;
String email;
}
class registeredUser {
String userID;
}
Or create just a single model like this? And when the user logs in, just store his/her userID (I don't use the other fields in most of my application screens, just when the user wants to change his/her profile.)
class user {
String userID;
String userName;
String firstName;
String lastName;
String password;
String email;
}
I ask this question, because I want to create a maintainable and scalable app.
So, what would you recommend me? Or do you have any other suggestion?
I suggest you use only one model for the user
class User {
String uid;
String userName;
String firstName;
String lastName;
String email;
}
P.S notice the capitalized class name, that's the dart way.
Using the above model would ensure that you don't store plaintext password in firestore which improves the overall data security of your app.

What's the best way to model Custom Object for Document ID in Firestore?

Say I have a collection of 'Users', and am happy for their ID to be the generated Firestore documentId, something like:
Users Collection
GENERATED_FIRESTORE_ID1:
name: "User 1 name"
...: etc.
GENERATED_FIRESTORE_ID2:
name: "User 2 name"
...: etc."
and I am adding them, and retrieving them with a custom object (I'm using Android at the moment but the question I guess is more generalistic). I don't want to have an extra "id" field in the document, just use the document.getId() method to get the generated firestore ID.
Is there a correct way to map a POJO to not have an indivual ID field, but when querying set it for application usage? I am doing it using the #Exclude annotation as follows:
public class User {
// as a side question, do I need #exclude on the field or just the getter?
#Exclude
String uId;
String name;
String email;
//... additional fields as normal
public User() {
}
#Exclude
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.displayName = name;
}
//... etc. etc.
}
and then I create the User object and set its ID as follows:
for (DocumentSnapshot doc : documentSnapshots) {
User user = doc.toObject(User.class);
user.setId(doc.getId());
users.add(user );
}
This works fine, and apologies if this is indeed the way, but I'm new to FireStore (am loving it) and want to make sure I'm doing it right. I just wondered if there was a way this would all be automatic, without #Exclude and then manually setting the ID after doc.toObject(MyCustomObject.class)
There is now an Annotation for this -
You could simply use
#DocumentId
String uID
https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentId.html

get field value of mocked object by reflection

class Person {
private String firstName;
private String lastName;
// getters and setters for firstName, lastName
}
#Test
void test() {
Person p = mock(Person.class);
when(p.getFirstName()).thenReturn("John");
when(p.getLastName()).thenReturn("Peter");
Map<String, Object> someContainerLikeMap = new HashMap<>();
org.springframework.util.ReflectionUtils.doWithFields(p.getClass(), field -> {
someContainerLikeMap.put(field.getName(), field.get(p));
// field.get(p) above, always get null
}
}
I've got two questions:
get by field reflection, field.get(p), always get null;
iteration of fields, what's the best way to just have fields defined in class Person included, that is, firstName, lastName?
Mockito works entirely through subclassing methods automatically with a "proxy object"; it doesn't override, change, or mock fields at all. You'll need a different tool for that.

Custom JsonSerialization

I have a simple class in asp.net mvc that looks like this:
public class JsonResponseItem
{
public string Key { get; set; }
public string Value { get; set; }
public JsonResponseItem(string key, string value)
{
Key = key;
Value = value;
}
}
In my controllers I create a list of that type
List<JsonResponseItem> response = new List<JsonResponseItem>();
so I can easily manage and add to the Json response. A dictionary object is kind of hard to do that with.
When I return the json object
return Json(response);
It deserializes it so I have to reference everything by index first, because of the list. So if I had a property called "IsValid" I would have to reference it like this "IsValid[0]". I have way too much javascript code to make these changes.
How could I deserialize the JsonResponseItem class so I don't need the index reference in there?
Thanks!
A Dictionary<string, string> would serialize into exactly the Json you're asking for. If you don't want to expose directly a dictionary, wrap it around in another class or use Json(response.ToDictionary(item => item.Key).

Resources