18

I ran a flutter upgrade today...

I'm now on v0.2.11 and I'm getting a strange runtime error in this function:

Future apiCall([Map params = const {}]) async {
  loading = true;
  Map stringParams = {};
  params.forEach((k,v)=>stringParams[k.toString()] = v.toString());
  Uri url = new Uri.https(apiDomain, apiPath, stringParams);
  print(url);
  var result = await http.post(
    url,
    body: {'apikey': apiKey}
  );
  loading = false;
  print(result.body);
  return json.decode(result.body);
}

I'm calling the function without any params and I get the subtype error.

This code works in DartPad.

Does anyone have an idea what might be going on?

1
  • This isn't an answer in and of itself, but this page might be of help for you to understand the new type-safe features in Dart 2.0. Commented Apr 13, 2018 at 20:06

3 Answers 3

23

The constructor for Uri.https requires a Map with a runtime type of Map<String, String>. When you create stringParams without any type annotations, you are actually creating a Map<dynamic, dynamic>. The correct way to create this for Dart 2 is

Map<String, String> stringParams = {};
// or
var stringParams = <String, String>{};

The reason this used to work is that in Dart 1, even in strong mode, dynamic was fuzzy and acted like both Object and null - meaning a dynamic type was assignable to and from anything. In Dart 2, dynamic acts just like Object, except you can call methods or access properties on it without a downcast.

Sign up to request clarification or add additional context in comments.

1 Comment

What happens if my object is of type Map<String, dynamic>. How to make a post request in that case? It keeps giving the above mentioned error.
12

I used this

    if(json["key"]!= null){
       this.active_guests = json["key"].cast<String, int>();
     }

1 Comment

How about nested maps :'(
1

You can send nested JSON params like this:

  1. Convert it to a string using json.encode.

  2. Send "Content-Type:application/json" in header.

var uri = "${Config.baseURL}/your/endpoint";
var headers = {
  'Content-Type': 'application/json'
};
final response = await http.post(
  uri,
  body: json.encode(data),
  headers: headers
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.