jsonflutterdartfreezed

Flutter EqualUnmodifiableListView error when i try to add json array inside the variable


To use the output received from the server, which is in the following format:

{
  "data": [{
    "id": 6,
    "config": "data",
  }]
}

And in Flutter, for converting this data, I have the following code using the Freezed library, and I don't have any issues:

@freezed
class ConfigsDto with _$ConfigsDto {
  const factory ConfigsDto({
    required List<Config> data,
  }) = _ConfigsDto;

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

@freezed
class Config with _$Config {
  const factory Config({
    required String config,
  }) = _Config;

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

my model:

Future<ConfigsDto> getConfigs(String provider) async {
    try {
      return await _signupRepository.getConfigs(provider);
    } on Exception catch (e) {
      handleError(e);
      rethrow;
    }
}

and repository:

Future<ConfigsDto> getConfigs(String provider) {
  return _restApi.getConfigs(provider);
}

RestClient api implementation with retrofit:

@POST(DV.allConfigs)
Future<ConfigsDto> getConfigs(
  @Query('provider') String provider,
);

Now, to put this array inside a list and use it, I declared the following variable:

final List<ConfigsDto> _blogs = [];

And to add the array output to this variable, I wrote this code:

First, receive it from the server:

final res = await model.getConfigs(providerName);

result:

ConfigsDto(data: [Config(id: 6, config: {
  "dns": {
    "hosts": {
      "domain:googleapis.cn": "googleapis.com"
    },
    "servers": [
      "1.1.1.1"
    ]
  },
  "inbounds": [
    {
      "listen": "127.0.0.1",
      "sniffing": {
        "destOverride": [
          "http"
        ],
        "enabled": true
      },
      "tag": "socks"
    },
    {
      "listen": "127.0.0.1"
    }
  ],
  "log": {
    "loglevel": "error"
  },
  "outbounds": [
    {
      "protocol": "vless",
      "streamSettings": {
      },
      "tag": "proxy"
    }
  ],
  "stats": {}
}, provider: 'test')])

Then, I want to put it inside the variable _blogs:

_blogs.clear();
_blogs.addAll(res.data as List<ConfigsDto>);

However, this line gives me the following error:

type 'EqualUnmodifiableListView<Config>' is not a subtype of type 'List<ConfigsDto>' in type cast


Solution

  • You have an EqualUnmodifiableListView<Config> (which derives from List<Config>) and want a List<ConfigsDto>, but Config and ConfigsDto seem like unrelated types, and therefore List<Config> and List<ConfigsDto> are also unrelated. Casts cannot convert between unrelated types.

    You perhaps intend to perform a transformation instead:

    _blogs.add(ConfigDto(data: res.data));