Search code examples
flutterdarturi

Flutter Uri.https doesn't give any errors


There's not much to say about my problem.

The code is:

Future<bool> getThatUrl(cid) async { //cid = 0, for example
  Map<String, dynamic> parameters = Map();
  String email = 'anymail@anymail.com';
  parameters['email'] = email;
  parameters['problematic_id'] = cid;
  print(parameters); // prints: {email: anymail@anymail.com, problematic_id: 0}
  var uri = Uri.https('mywebpage.com', '/page.php', parameters);
  print(uri); // prints: 
}

The problem is, that uri is (not generated? and) not printed, unless I remove parameters['problematic_id'] = 0. If I remove it, then it prints https://mywebpage.com/page.php?email=anymail%40anymail.com which is correct, but I need that problematic_id=0 there, too.

I tried using only one parameter, but if it's parameters['problematic_id'] = 0 then it still doesn't work.


Solution

  • This is actually an intended behavior.

    I can see that at internal implementation, each value of queryParameters should be either a Iterable or a String? (String or null) and you are passing int (cid = 0) instead.

    Since queryParameters are in anyway treated as String, you don't have to worry about the type here. So, it's better to just call toString() or convert your cid to string to solve this.

    Here's a solution code:

    Uri getUri(String email, int cid) {
      Map<String, dynamic> parameters = {
        'email': email,
        'problematic_id': "$cid"
      };
      print(parameters);
      var uri = Uri.https('mywebpage.com', '/page.php', parameters);
      print(uri);
      return uri;
    }
    
    void main() {
      final cid = 0;
      final email = 'anymail@anymail.com';
    
      getUri(email, cid);
    }
    

    Here line number 4, "$cid" will convert the cid to string hence solving the issue.

    Hope this helps.

    Edit:

    A value in the map must be either null, a string, or an Iterable of strings.

    (Thanks to @jamesdlin for the comment)