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

499 Views Asked by At

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

There are 1 best solutions below

2
Ruble On

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();