flutterdartbuilt-value

How to create nested object using built value


I want to create a nested object to send as request to api. Help is much appreciated.

Below is the nested built value class


abstract class BuiltUpdateProfileRequest
    implements
        Built<BuiltUpdateProfileRequest, BuiltUpdateProfileRequestBuilder> {
  // fields go here
  String get firstName;
  String get lastName;
  String get phoneNumber;
  @nullable
  ProfileBilling get billing;

  BuiltUpdateProfileRequest._();

  factory BuiltUpdateProfileRequest(
          [updates(BuiltUpdateProfileRequestBuilder b)]) =
      _$BuiltUpdateProfileRequest;

  static Serializer<BuiltUpdateProfileRequest> get serializer =>
      _$builtUpdateProfileRequestSerializer;
}

abstract class ProfileBilling
    implements Built<ProfileBilling, ProfileBillingBuilder> {
  // fields go here
  @nullable
  String get address1;
  @nullable
  String get address2;
  @nullable
  String get city;
  @nullable
  String get state;
  @nullable
  String get country;
  @nullable
  String get zip;
  ProfileBilling._();

  factory ProfileBilling([updates(ProfileBillingBuilder b)]) = _$ProfileBilling;

  static Serializer<ProfileBilling> get serializer =>
      _$profileBillingSerializer;
}

Below is request object but it throws error at billing under phone number stating a value of type profile billing cannot be assigned to a variable of type ProfileBillingBuilder.

 final ProfileBilling profileBilling = ProfileBilling((b) => b
      ..address1 = ""
      ..address2 = ""
      ..city = ""
      ..state = ""
      ..country = ""
      ..zip = "");

 final BuiltUpdateProfileRequest builtUpdateProfileRequest =
        BuiltUpdateProfileRequest((b) => b
          ..firstName = firstName
          ..lastName = lastName
          ..phoneNumber = phoneNo
          ..billing = profileBilling);

Solution

  • You need to call the method toBuilder() to create ProfileBillingBuilder variable;

    final BuiltUpdateProfileRequest builtUpdateProfileRequest =
        BuiltUpdateProfileRequest((b) => b
          ..firstName = firstName
          ..lastName = lastName
          ..phoneNumber = phoneNo
          ..billing = profileBilling.toBuilder());