英文:
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<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'],
);
}
}
答案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 '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);
}
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<String, dynamic> toMap() => toJson();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论