简体   繁体   English

什么是flutter/Dart中的factory和formJson Model class?

[英]What is factory and formJson in flutter/Dart Model class?

To access data we need to pass response to a dart model. what is the purpose behind this?要访问数据,我们需要将响应传递给 dart model。这背后的目的是什么? i tried reading the dart model code where "factory" and other keyword like "formJson" are there.我尝试阅读 dart model 代码,其中包含“factory”和“formJson”等其他关键字。 what is the implementation of this?这是什么实现?

simple model class code below:简单的 model class 代码如下:

factory Posts.fromJson(Map<String, dynamic> json) => Posts(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
    );

In Dart, we use the factory keyword to identify a default or named constructor.在 Dart 中,我们使用 factory 关键字来标识默认或命名构造函数。 We use the factory keyword to implement constructors that do not produce new instances of an existing class.我们使用工厂关键字来实现不生成现有 class 的新实例的构造函数。

Syntax句法

class Class_Name {
  factory Class_Name() {
    // TODO: return Class_name instance
  }
}

We must follow some rules when using the factory constructor.在使用工厂构造函数时,我们必须遵循一些规则。

The return keyword is used.使用 return 关键字。 It does not have access to the this keyword.它无权访问 this 关键字。 Return value A factory constructor can return a value from a cache or a sub-type instance.返回值工厂构造函数可以从缓存或子类型实例返回值。

Example The following code shows how to use the factory keyword in Dart:示例 以下代码显示如何在 Dart 中使用 factory 关键字:

// create Class Car
class Car {
    //class properties
    String name;
    String color;

    //constructor
    Car({ this.name, this.color});

    // factory constructor that returns a new instance
    factory Car.fromJson(Map json) {
    return Car(name : json['name'], 
    color : json['color']);
    }
}

void main(){
    // create a map
    Map myCar = {'name': 'Mercedes-Benz', 'color': 'blue'};
    // assign to Car instance
    Car car = Car.fromJson(myCar);
    //display result
    print(car.name);
    print(car.color);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM