1

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'],
    );
  }
}
Ruble
  • 2,589
  • 3
  • 6
  • 29
Nashaf
  • 23
  • 7

1 Answers1

1

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();
Ruble
  • 2,589
  • 3
  • 6
  • 29
  • Thank you for the replay. if i'm not wrong toJson() will give right? but I want Map in this case how the freezed model should be ? chatGPT gave me a solution like this and it's working I just want to confirm is this approach is correct ? (https://chat.openai.com/share/228fc6ad-029c-4490-a8d6-f04c01b807d8) – Nashaf Jul 20 '23 at 09:41
  • 1
    Typically your json has values of different types. Therefore, the word `dynamic` is used. Specifically in this case, when you are certain that your fields will only be `String` do something like this `Map toMap() => toJson().cast();`. This will cause an error if the value be `null` – Ruble Jul 20 '23 at 09:46
  • okay thank you very much – Nashaf Jul 20 '23 at 09:48