Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type 'List<String>' is not a subtype of type 'String' in type cast

Tags:

flutter

dart

I have this:

List<String> _filters = <String>[8, 11];

I pass this _filters into this endpoint:

this.api.setInterests(token, _filters)
  .then((res) {
    print(res);
  });

which looks like this:

  Future setInterests(String token, List<String> interests) {
    return _netUtil.post(BASE_URL + "/setinterests", body: {
      "token": token,
      "interests": interests
    }).then((dynamic res) {
      return res;
    });
  }

Passing _filters always throws the error:

type 'List<String>' is not a subtype of type 'String' in type cast

I don't know what else dart wants from me.

like image 490
KhoPhi Avatar asked Jun 29 '18 21:06

KhoPhi


People also ask

Is List string a subtype of List object?

List<String> isn't type related to List<Object> in any way, not anymore than List<String> is related to List<Number> . The type is List<String> , the entire signature is the type . But like with everything, there are exceptions; these are called Wildcard Parameterized Types .

How do you convert a list list to dynamic string in flutter?

In dart and flutter, this example converts a list of dynamic types to a list of Strings. map() is used to iterate over a list of dynamic strings. To convert each element in the map to a String, toString() is used. Finally, use the toList() method to return a list.


2 Answers

  1. You need to add json.encode(data) in body
  2. Add these two header
    'Content-type': 'application/json',
    'Accept': 'application/json',
  3. Create map of your data

    final Map<String, dynamic> data = new Map<String, dynamic>();
     data['token'] = token;
     data['interests'] = interests;
    
  4. Call api like this

    http.post(url,<br>
    body: json.encode(data),
    headers: { 'Content-type': 'application/json',
      'Accept': 'application/json'},
    encoding: encoding)
    .then((http.Response response) {
    
         // print(response.toString());
    
    }
    
like image 45
Sanjayrajsinh Avatar answered Sep 30 '22 18:09

Sanjayrajsinh


I found the answer. I just added .toString() to the _filters List.

  this.api.setInterests(token, _filters.toString())
  .then((res) {
    print(res);
  });
like image 111
KhoPhi Avatar answered Sep 30 '22 18:09

KhoPhi