Flutter, why use "static" in the fromJson method? - flutter

static TodoEntity fromJson(Map<String, Object> json) {
return TodoEntity(
json['task'] as String,
json['id'] as String,
json['note'] as String,
json['complete'] as bool,
);
}
static TodoEntity fromSnapshot(DocumentSnapshot snap) {
return TodoEntity(
snap.data()['task'],
snap.id,
snap.data()['note'],
snap.data()['complete'],
);
}
I`m studying "fromJson" method right now and
In this example, why they use "static"?
I wonder why

Because fromJson is related the class and not the object (this is the case for every static variable/method)
So from the name fromJson, You need to create TodoEntity object from your json, which means you don't have the object yet which means you can't call fromJson, So using static here is a must,
Another alternative is passing your json via constructor, but using static is must clean and common.
Example without static:
To create new object from json
var json = {...};
TodoEntity todo = TodoEntity();
TodoEntity todo2 = todo.fromJson(json);
or
var json = {...};
TodoEntity todo = TodoEntity();
todo = todo.fromJson(json);
as you can see you need always an object (todo) to call fromJson
but using static
var json = {...};
TodoEntity todo = TodoEntity.fromJson(json);
static means you can call this function without having an object

The static keyword required to implement "Static Factory Method" pattern for methods which are producing new instances of given class.
If these methods were not static, you had to have the an instance of TodoEntity to call them.
But they are static, so there's no need to create any instance to call them:
TodoEntity.fromJson(jsonMap);

Related

vue 3 reactive custom class object with methods

Let's say in my component I have simple computed array of items, all of which are type of custom class Item. Item is an object of a custom class with private methods.
// items is a computed array
const items = computed(() => [new Item("first"), new Item("second"),...]);
// item class
class Item{
constructor(itemName){
this.itemName = itemName;
this.inStock = this.#itemInStock(itemName);
// other properties initialized by some other private methods
}
#itemInStock(item){
return items.indexOf(item) !== -1;
}
}
Now I have been reading about reactivity, here, and if I understood vue uses Proxies to catch attempt to read property and Reflects to use binding, but will it catch methods as well? Can I use private methods in class instance and then use that class instance in template?
Private methods should not be accessed directly e.g. Item.itemInStock should fire error.
Please note that I don't intent to use any of my methods directly in template nor anywhere in application (that is why I made them private)
you can use method reactive and toRefs.
first, you can import this methode.
import { reactive, toRefs } from 'vue
second, you change on your computed
const items = computed(() => reactive[new Item("first"), new Item("second"),...]);
and you change return with
return toRefs(items.indexOf(item))
if your data is object, you should add spread in your return
return ...toRefs(items.indexOf(item))

why we should use static keyword in dart in place of abstract?

I m preparing a class in my flutterfire project and their I want to use some method Which can't change further so that I want to know consept of static keyword in Dart ?
"static" means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies members.
Static methods
Static methods (class methods) don’t operate on an instance, and thus don’t have access to this. They do, however, have access to static variables.
void main() {
print(Car.numberOfWheels); //here we use a static variable.
// print(Car.name); // this gives an error we can not access this property without creating an instance of Car class.
print(Car.startCar());//here we use a static method.
Car car = Car();
car.name = 'Honda';
print(car.name);
}
class Car{
static const numberOfWheels =4;
Car({this.name});
String name;
// Static method
static startCar(){
return 'Car is starting';
}
}
static keyword in dart used to declare a variable or method that belongs to just the class not the instants which means the class has only one copy of that variable or method and those static variables(class variables) or static methods(class methods) can not be used by the instances created by the class.
for example if we declare a class as
class Foo {
static String staticVariable = "Class variable";
final String instanceVariable = "Instance variable";
static void staticMethod(){
print('This is static method');
}
void instanceMethod(){
print('instance method');
}
}`
the thing here to remember is static variables are created only once and every instance crated by the class has different instance variables. therefore you can not call static variables form the class instances.
following codes are valid,
Foo.staticVariable;
Foo().instanceVariable;
Foo.staticMethod();
Foo().instanceMethod();
there for following codes will give errors
Foo().staticVariable;
Foo.instanceVariable;
Foo().staticMethod;
Foo.instanceMethod
Use of static variables and methods
you can use static variables when you have constant values or common values that are relevant for the class.
you can read more here - https://dart.dev/guides/language/language-tour#class-variables-and-methods

What is required for EF Core's IMethodCallTranslator to work with `EF.Functions` to provide a custom function?

I'm trying to implement a custom IMethodCallTranslator in EF Core 3.1 with the Sqlite provider.
I have created:
An extension method off of this DbFunctions which is called at query time
An implementation of IMethodCallTranslator which is Translate not called
A derived RelationalMethodCallTranslatorProvider which I'm passing an instance of my IMethodCallTranslator. This constructor is hit. I also tried overriding RelationalMethodCallTranslatorProvider.Translate and this was not hit.
An implementation of IDbContextOptionsExtension (and its info class) which registers the RelationalMethodCallTranslatorProvider as a singleton IMethodCallTranslatorProvider.
All of this is added via OnConfiguring by getting the IDbContextOptionsBuilderInfrastructure form of the options.
Am I missing something? I've tried following: https://github.com/tkhadimullin/ef-core-custom-functions/tree/feature/ef-3.1-version in my code, yet it's invoking the extension method, not my translator.
Apparently, you can't pass a reference to your full entity class to the function for further processing:
Doesn't work:
public static string DoWork(this DbFunctions _, object entity, string key)
//...
dbContext.Items.Select(i => new { Entity = i, String = EF.Functions.DoWork(i, i.StringValue) });
Where this will:
public static string DoWork(this DbFunctions _, string key)
//...
dbContext.Items.Select(i => new { Entity = i, String = EF.Functions.DoWork(i.StringValue) });
Also, generics are supported so it would be a nice way to introspect call and get the type of the entity for the model in a RelationalMethodCallTranslatorProvider.
public static string DoWork<T>(this DbFunctions _, string key)
//...
dbContext.Items.Select(i => new { Entity = i, String = EF.Functions.DoWork<Item>(i.StringValue) });

Deserialize request body to specific class instead of JsonObject

Say we have this:
Router router = Router.router(vertx);
router.put("/products/:productID").handler(this::handleAddProduct);
and this:
private void handleAddProduct(RoutingContext ctx) {
String productID = ctx.request().getParam("productID");
HttpServerResponse response = ctx.response();
JsonObject product = ctx.getBodyAsJson();
products.put(productID, product);
response.end();
}
my question is - how can we deserialize ctx.getBodyAsJson() to a specific Java class instead of the generic JsonObject class?
you can use JsonObject.mapTo(Class), e.g.:
JsonObject product = ctx.getBodyAsJson();
Product instance = product.mapTo(Product.class);
UPDATE
you can customize the (de)serialization behavior by manipulating the ObjectMapper instance(s) associated with the Json class. here are some examples:
// only serialize non-null values
Json.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// ignore values that don't map to a known field on the target type
Json.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
keep in mind Json holds a reference to two different ObjectMappers:
mapper, and
prettyMapper

Typescript - Get uninitialized properties after compilation

I am currently writing a wrapper around socket.io. Comming from a very object-oriented background, I want to implement the concept of Models in my framework/wrapper.
If you happen to know socket.io you might know that you get the data that is associated with an event as a parameter, now I have implemented a custom routing system where the handler of the route gets the data in an express.js like request object.
The idea is to have model classes that look something like this:
class XRequestModel
#v.String({ message: 'The username must be a string!' })
public userName: string;
}
And the route event might look something like this:
#RouteConfig({ route: '/something', model: XRequestModel })
class XEvent extends Route {
public on(req: Request<XRequestModel>, res: Response) {
// Handle Event
}
}
And to complete the example here is how the request object might look like:
class Request<T> {
public data: T;
}
Now generics in typescript are very limited since the type information is removed after compilation, I can not use the generic Request parameter ( which is the type of the model ) to get metadata from the model - Metadata, in this case, is the validation decorator. To overcome this issue I give a reference of the Model class to the RouteConfig of the RouteEvent, which is internally used and would allow me to create instances of the model, get the properties and so on...
The idea here is to give the handler of a route, a request object with pre-validated, typesafe data.
The thing holding me back from this, is the fact that unused properties, get removed after compilation by typescript, So I cannot get the metadata of the model. Initializing the class-property would solve this:
class XRequestModel
#v.String({ message: 'The username must be a string!' })
public userName: string = '';
}
But I think this makes for some very verbose syntax, and I dont want to force the user of this wrapper to init all the model properties.
An implementation side-note:
The user of the framework has to register the classes to a 'main' class and from there I can get the Route-class via decorator reflection.
When I try to get the properties of the model without initialized properties - First model example.
// Here the route.config.model refers to the model from the RouteConfig
Object.getOwnPropertyNames(new route.config.model());
>>> []
Here is what I get with initialized properties:
Object.getOwnPropertyNames(new route.config.model());
>>> [ 'userName' ]
Here a link to the GitHub repository: https://github.com/FetzenRndy/SRocket
Note that models are not implemented in this repo yet.
Basically, my question is: How can I get the properties of a class that has uninitialized properties after compilation.
The problem is that if no initialization happens, no code is emitted for the fields, so at runtime the field does not exist on the object until a value is assigned to it.
The simplest solution would be to initialize all fields even if you do so with just null :
class XRequestModel {
public userName: string = null;
public name: string = null;
}
var keys = Object.getOwnPropertyNames(new XRequestModel())
console.log(keys); // [ 'userName', 'name' ]
If this is not a workable solution for you, you can create a decorator that adds to a static field on the class and the walk up the prototype chain to get all fields:
function Prop(): PropertyDecorator {
return (target: Object, propertyKey: string): void => {
let props: string[]
if (target.hasOwnProperty("__props__")) {
props = (target as any)["__props__"];
} else {
props = (target as any)["__props__"] = [];
}
props.push(propertyKey);
};
}
class XRequestModelBase {
#Prop()
public baseName: string;
}
class XRequestModel extends XRequestModelBase {
#Prop()
public userName: string;
#Prop()
public name: string;
}
function getAllProps(cls: new (...args: any[]) => any) : string[] {
let result: string[] = [];
let prototype = cls.prototype;
while(prototype != null) {
let props: string[] = prototype["__props__"];
if(props){
result.push(...props);
}
prototype = Object.getPrototypeOf(prototype);
}
return result;
}
var keys = getAllProps(XRequestModel);
console.log(keys);