Home > other >  How to solve type 'String' is not a subtype of type 'int' of 'index' i
How to solve type 'String' is not a subtype of type 'int' of 'index' i

Time:11-18

I am fetching list of countries from my Api using Bio but when I try to get them in my screen widget, it returns an error => type 'String' is not a subtype of type 'int' of 'index'

This is my code:

Future<void> getCountries() async {
    try {
      final response = await _apiService.getCountries();
      var arr = response['list'];
      log(arr); // type 'List<dynamic>' is not a subtype of type 'String'
    } catch (e) {
      log(e.toString());
      rethrow;
    }
  }

This is my ApiProvider code:

Future<dynamic> getCountries() async {
    dio.interceptors.add(
      LogInterceptor(
        requestBody: true, responseBody: true
      )
    );
    try {
      return _request(
        () => dio.get(
          ApiPath.countries,
          options: Options(
            responseType: ResponseType.json
          )
        )
      );
    } on DioError catch (ex) {
      log(ex.toString());
    }
  }

This is response from Api:

{"success":true,"list":[{"id": 1, "name": "Abkhazia"}, {"id":2, "name": ""Afghanistan"}]}

CodePudding user response:

Is the exception thrown at the line log(arr);? This is because log takes a String parameter. Use log('$arr'));. Or better, define the type List arr instead of var arr.

  • Related