0

I have declared a custom freezed model in a flutter web project as follows:

@freezed
class User with _$User {
  const factory User({
    required int id,
    required String name,
    required Address address,
    @Default(null) Contact? contact,
  }) = _User;

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

The models for Address and Contact are as follows:

@Freezed()
class Address with _$Address {
  const factory Address({
    required String type,
    required String address,
    required String subDistrict,
    required String district,
    required String state,
    required String country,
    required String pincode,
    Coordinates? coordinates,
  }) = _Address;

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

@Freezed()
class Coordinates with _$Coordinates {
  const factory Coordinates({
    required double latitude,
    required double longitude,
  }) = _Coordinates;

  factory Coordinates.fromJson(Map<String, dynamic> json) => _$CoordinatesFromJson(json);
}
@Freezed()
class Contact with _$Contact {
  const factory Contact({
    @Default([]) List<String> email,
    @Default([]) List<String> mobile,
    @Default([]) List<String> landline,
    @Default([]) List<String> fax,
  }) = _Contact;

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

Now, the issue is that when I try to create an instance of this model from json, it throws the following error:

NoSuchMethodError: tried to call a non-function, such as null: 'user$.User.fromJson'

However, this is not happening for all the models in the project. I am facing this issue only for the aforementioned one.

I tried not setting @Default(null) as well but the same issue arises. I have ensured that the data being passed is json and not a String.

What could be the issue here?

Flutter 3.7.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 62bd79521d (2 weeks ago) • 2023-03-30 10:59:36 -0700
Engine • revision ec975089ac
Tools • Dart 2.19.6 • DevTools 2.20.1

dependencies:
  freezed_annotation: ^2.2.0
  json_annotation: ^4.8.0

dev_dependencies:
  build_runner: ^2.3.3
  freezed: ^2.3.2
  json_serializable: ^6.6.1

Just found that this happens in debug mode. Runs fine in release mode. This is the stacktrace:

C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50   <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1660:54                                 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18                           handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 767:44                           handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 796:13                           _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 567:5                            [_completeWithValue]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 640:7                            callback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 40:11                     _microtaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 49:5                      _startMicrotaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15  <fn>

1 Answers1

0

Add the part statement yourfile.g.dart

Make sure that you have successfully run the build_runner

Try running with --delete-conflicting-outputs

If you need to serialize/deserialize nested freezed classes, you also have to add @JsonSerializable(explicitToJson: true) or set explicit_to_json inside your build.yaml

@Default(null) can/should be removed. It adds nothing.

Edit

I've just copied your models, succesfully generated all files, created models, serialized and deserialized it. Works fine in release mode and debug mode.

I removed the @Default(null) on contact.

The models:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'temp.freezed.dart';
part 'temp.g.dart';

@freezed
class User with _$User {
  const factory User({
    required int id,
    required String name,
    required Address address,
    Contact? contact,
  }) = _User;

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

@Freezed()
class Address with _$Address {
  const factory Address({
    required String type,
    required String address,
    required String subDistrict,
    required String district,
    required String state,
    required String country,
    required String pincode,
    Coordinates? coordinates,
  }) = _Address;

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

@Freezed()
class Coordinates with _$Coordinates {
  const factory Coordinates({
    required double latitude,
    required double longitude,
  }) = _Coordinates;

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

@Freezed()
class Contact with _$Contact {
  const factory Contact({
    @Default([]) List<String> email,
    @Default([]) List<String> mobile,
    @Default([]) List<String> landline,
    @Default([]) List<String> fax,
  }) = _Contact;

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

Using the models here:

import 'dart:convert';

import 'dart:io';
import 'package:console_app/temp.dart';

void main(List<String> arguments) {
  var user = User(
    id: 42,
    name: 'name',
    contact: Contact(
      email: ['test@email.com'],
      fax: ['0123-456789'],
      landline: ['0246-8101214'],
      mobile: ['0135-791113'],
    ),
    address: Address(
        type: 'type',
        address: 'address',
        subDistrict: 'subDistrict',
        district: 'district',
        state: 'state',
        country: 'country',
        pincode: 'pincode',
        coordinates: Coordinates(
          latitude: 12.34567,
          longitude: 98.7654,
        )),
  );
  var jsonData = jsonEncode(user.toJson());
  var file = File('user.json');
  file.writeAsStringSync(jsonData);
  var readUserFromFile = User.fromJson(jsonDecode(file.readAsStringSync()));
  assert(user == readUserFromFile);
  print(readUserFromFile);
}

This is the resulting json file:

{
  "id": 42,
  "name": "name",
  "address": {
    "type": "type",
    "address": "address",
    "subDistrict": "subDistrict",
    "district": "district",
    "state": "state",
    "country": "country",
    "pincode": "pincode",
    "coordinates": { "latitude": 12.34567, "longitude": 98.7654 }
  },
  "contact": {
    "email": ["test@email.com"],
    "mobile": ["0135-791113"],
    "landline": ["0246-8101214"],
    "fax": ["0123-456789"]
  }
}

and this is the resulting print:

User(id: 42, name: name, address: Address(type: type, address: address, subDistrict: subDistrict, district: district, state: state, country: country, pincode: pincode, coordinates: Coordinates(latitude: 12.34567, longitude: 98.7654)), contact: Contact(email: [test@email.com], mobile: [0135-791113], landline: [0246-8101214], fax: [0123-456789]))
Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • I have done that. The build runner completes the build successfully. As I said, I have multiple models in the project where I am not facing the issue. It happens only for this one. Thanks for your reply :) – Damien Leon Apr 14 '23 at 05:08
  • Are address and contact also freezed models? – Robert Sandberg Apr 14 '23 at 05:11
  • Yes. I tried passing the json to these address and contact seperately and they work fine. – Damien Leon Apr 14 '23 at 05:14
  • Ok, I just found that this isn't happening when I run in release mode. Only on debug mode. Any idea what could be causing this? – Damien Leon Apr 14 '23 at 05:16
  • Should be no difference between debug and release mode. Sounds like something is cached. See my edit and try again. – Robert Sandberg Apr 14 '23 at 05:28
  • I did this and even tried deleting the cache folder and reinstalled the dart sdk. The issue still persists. – Damien Leon Apr 14 '23 at 06:07
  • I cannot see anything else that is wrong. You'll have to present your entire files containing the User, Address and Contact models so that the problem can be replicted by "us". – Robert Sandberg Apr 14 '23 at 06:16
  • Sorry for the late reply. I have added the other models in the question. – Damien Leon Apr 17 '23 at 04:20
  • Hmmm. I still am unable to get around this issue. Must be that my system is corrupted probably/ Will try resetting it. Thank you so much for your help. – Damien Leon Apr 18 '23 at 23:35