Flutter Freezed是否有toMap()方法?如果没有,我该如何添加?

huangapple go评论70阅读模式
英文:

Dose Flutter Freezed have toMap() method ? if not how I can add?

问题

在这个模型中,当我使用了freezed时,我发现我缺少了toMap()方法。

我想将公司对象更改为Map<String, String>

class Company {
  final String? id;
  final String? name;

  Company({
    this.id,
    this.name,
  });

  Map<String, String> toMap() {
    return {
      'id': id!,
      'name': name!,
    };
  }

  factory Company.fromJson(Map<String, dynamic> json) {
    return Company(
      id: json['id'],
      name: json['name'],
    );
  }
}
英文:

In this model when i use freezed i'm missing toMap() method

I want change the company object into Map&lt;String, String&gt;

class Company {
  final String? id;
  final String? name;

  Company({
    this.id,
    this.name,
  });

  Map&lt;String, String&gt; toMap() {
    return {
      &#39;id&#39;: id!,
      &#39;name&#39;: name!,
    };
  }

  factory Company.fromJson(Map&lt;String, dynamic&gt; json) {
    return Company(
      id: json[&#39;id&#39;],
      name: json[&#39;name&#39;],
    );
  }
}

答案1

得分: 1

fromJson|toJson方法可以根据您的字段自动生成。我建议您注意文档中的这一部分 - Freezed: FromJson/ToJson

您的模型最终会类似于以下内容:

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';

part 'company.freezed.dart';
part 'company.g.dart';

@freezed
class Company with _$Company {
  const factory Company({
    required String? id,
    required String? name,
  }) = _Company;

  factory Company.fromJson(Map<String, dynamic> json)
      => _$CompanyFromJson(json);
}

现在您只需在控制台中运行以下命令:

flutter pub run build_runner build

如果您需要具有该名称的确切toMap()方法,可以这样做:

Map<String, dynamic> toMap() => toJson();
英文:

The fromJson|toJson methods can be generated automatically based on your fields. I recommend that you pay attention to this section of the documentation - Freezed: FromJson/ToJson

Your model will end up looking something like this:

import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;
import &#39;package:flutter/foundation.dart&#39;;

part &#39;company.freezed.dart&#39;;
part &#39;company.g.dart&#39;;

@freezed
class Company with _$Company {
  const factory Company({
    required String? id,
    required String? name,
  }) = _Company;

  factory Company.fromJson(Map&lt;String, dynamic&gt; json)
      =&gt; _$CompanyFromJson(json);
}

Now all you have to do is run the command in the console:

flutter pub run build_runner build

If you need exactly toMap() method with that name, you can do it like this:

Map&lt;String, dynamic&gt; toMap() =&gt; toJson();

huangapple
  • 本文由 发表于 2023年7月20日 16:55:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定