【问题标题】:How to create a model in flutter如何在颤振中创建模型
【发布时间】:2021-10-12 11:48:49
【问题描述】:

我正在观看旧的颤振课程,因为我真的找不到新的课程。但是由于 Flutter 是不断更新的,所以一旦你从旧课程中学习,它就会变得更具挑战性。

这是我的问题:

  1. fromObject 还在这里还是刚改成 fromJson?
  2. 您有模型样品吗?
  3. 我怎样才能使我的 _id 是唯一的?(使用 sql 等)

我正在尝试这样的事情,但在“Product.fromObject”中出现错误。

class Product {
  int _id;
  String _name;
  String _description;
  double _price;

  Product(this._id, this._name, this._description, this._price);
  Product.withId(this._id, this._name, this._description, this._price);

  int get id => _id;
  String get name => _name;
  String get description => _description;
  double get price => _price;

  set name(String value) {
    if (value.length >= 2) {
      _name = value;
    }
  }

  set description(String value) {
    if (value.length >= 10) {
      _description = value;
    }
  }

  set price(double value) {
    if (value > 0) {
      _price = value;
    }
  }

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{};
    map["name"] = _name;
    map["description"] = _description;
    map["price"] = _price;
    map["id"] = _id;

    return map;
  }

  Product.fromObject(dynamic o) {
    _id = o["id"];
    _name = o["name"];
    _description = o["description"];
    _price = o["price"];
  }
}```

【问题讨论】:

    标签: flutter


    【解决方案1】:

    现在改为fromJson。

    class Post{
      int userid;
      int id;
      String title;
      String body;
    
      Post({userid, id, title, body});
    
      Post fromJson(Map<String, dynamic> json){
        Post post = Post();
        post.userid = json["userId"];
        post.id = json['id'];
        post.title = json['title'];
        post.body = json['body'];
        return post;
      }
    
      Map<String, dynamic> toJson(Post post){
        Map<String, dynamic> data = {
          "userId": post.userid,
          "id": post.id,
          "title": post.title,
          "body": post.body
        };
        return data;
      }
    
    }
    

    我附上了一个示例模型类供您参考。

    【讨论】:

      【解决方案2】:

      您可以在此处阅读有关 json 序列化的信息:https://flutter.dev/docs/development/data-and-backend/json

      从json解析的正确方法是工厂方法,调用fromJson并取一个map。

      【讨论】:

      • 不完全回答我的问题,但谢谢。
      猜你喜欢
      • 2021-11-24
      • 2021-07-07
      • 1970-01-01
      • 2021-02-25
      • 2021-02-06
      • 2021-12-26
      • 1970-01-01
      • 2020-04-27
      • 2022-11-28
      相关资源
      最近更新 更多