크로스 플랫폼/Flutter <Dart>

[Flutter] URI.https type 'int' is not a subtype of type 'Iterable<dynamic>' 에러 해결

TaeGyeong Lee 2023. 12. 17. 03:36

문제 상황

URI.https 인스턴스의 속성을 정의할 때, 파라미터 value 값에 int 자료형이 들어가는 경우 발생할 수 있습니다.

▶ #0 예제 코드

    int number = 3;
    
    final Uri uri = Uri.https(APU_AUTHORITY, API_PATH, {
      "number": number,
      "count": 1,
    });

 

해결 방안

파라미터 내 모든 value 를 String 자료형으로 만들어 줍니다.

▶ #1 수정된 예제 코드

    int number = 3;
    
    final Uri uri = Uri.https(APU_AUTHORITY, API_PATH, {
      "number": number.toString(),
      "count": "1",
    });

 

원인

Uri.https의 원형은 아래와 같습니다. 팩토리 패턴이 적용되었으며 두 가지 방식으로 Uri.http 인스턴스 속성을 정의할 수 있음을 확인할 수 있습니다. 제 #0 예제코드는 첫 번째 방식으로 속성을 정의했네요. (중요한 내용은 아닙니다.)

▶ #2 /bin/pkg/.../lib/core/uri.dart 일부

  factory Uri.http(
    String authority, [
    String unencodedPath,
    Map<String, dynamic /*String?|Iterable<String>*/ >? queryParameters,
  ]) = _Uri.http;
  
  ...
    factory Uri.https(String authority,
      [String unencodedPath,
      Map<String, dynamic>? queryParameters]) = _Uri.https;

 

queryParameters의 자료형을 눈여겨 볼 필요가 있습니다. 두 가지 방식 모두 queryParatmers의 자료형을 아래와 같이 명시하고 있습니다.

Map<String, dynamic>? queryParameters

Map 자료형의 key는 문자열이고 value는 dynamic 이네요? 자료형을 명시하지 않았음을 확인할 수 있습니다. dynamic을 잘 모르시는 경우 여기를 클릭하세요. 

 

dynamic이면 int 자료형의 값을 넣어도 문제가 없어야 합니다. 하지만 에러가 발생했습니다. 코드를 좀 더 훑어보겠습니다.

...
  /// Cache the computed return value of [queryParameters].
  late final Map<String, String> queryParameters =
      UnmodifiableMapView<String, String>(Uri.splitQueryString(this.query));

  /// Cache the computed return value of [queryParametersAll].
  late final Map<String, List<String>> queryParametersAll =
      _computeQueryParametersAll(this.query);
...

queryParamters와 queryParamtersAll이 정의되어 있습니다. 그런데 자료형이 Map<String, String>,  Map<String, List<String>> 을 반환하도록 되어 있네요. 더 들어갈 필요도 없이 value의 자료형으로 int가 들어갈 수 없는 구조임을 알 수 있습니다.

URI.https내 파라미터 value의 자료형을 dynamic 자료형으로 명시한 이유는 한 가지 자료형이 아닌 String 또는 List<String> 두 가지 자료형 모두 받을 수 있기 위해 사용되었습니다. 

따라서, value 값은 String 또는 List<String> 자료형을 가져야 합니다.

 

참고 자료

 

queryParameters property - Uri class - dart:core library - Dart API

The URI query split into a map according to the rules specified for FORM post in the HTML 4.01 specification section 17.13.4. Each key and value in the resulting map has been decoded. If there is no query, the empty map is returned. Keys in the query strin

api.dart.dev

 

flutter URI.https: type 'int' is not a subtype of type 'Iterable<dynamic>' error

I am trying to call a method on web service as a get http method. I got error that I don't know why I got error. This is my method: Future<dynamic> httpGet2({ DirectsBody queryParams,

stackoverflow.com

 

Effective Dart: Design

Design consistent, usable libraries.

dart-ko.dev