0

I need to send the body with Content-Type: application/x-form-urlencoded

The body request in json is the following

{"skip":0,"take":50,"pageSize":50,"page":0,"filter":{"logic":"and","filters":[{"operator":"startsWith","field":"nazione","value":"it"}]}}

I need to convert it into:

skip=0&take=50&page=1&pageSize=50&filter%5Blogic%5D=and&filter%5Bfilters%5D%5B0%5D%5Boperator%5D=startsWith&filter%5Bfilters%5D%5B0%5D%5Bfield%5D=nazione&filter%5Bfilters%5D%5B0%5D%5Bvalue%5D=it

In jQuery I can get this result simply passing the json to $.param, does exist anything similar in dart?

I'm using http (from 'package:http/http.dart') and I don't know how to transform body in order to use in http.post:

http.post(url, headers: Map<String, String>.from({'application/x-www-form-urlencoded; charset=UTF-8'}), body: ???)

body is built in this way:

var filters = [
    Map<String, String>.from({
        'operator': 'startsWith', 
        'field': 'nazione', 
        'value': 'it'
    })
];

var filter = Map<String, dynamic>.from({
    'logic': 'and',
    'filters': filters
});

var body = Map<String, dynamic>.from({
    'skip': 0,
    'take': 50,
    'pageSize': 50,
    'page': 1,
    'filter': filter
});

Trying

Uri(
    scheme: 'https',
    host: 'myhost',
    port: 8443,
    queryParameters: body,
    pathSegments: ["api", "coutries", "grid"]);

I get the error

type 'int' is not a subtype of type 'Iterable<dynamic>'

Because I should convert body as:

Map<String, String>.from({
      'take': 50.toString(),
      'skip': 0.toString(),
      'pageSize': 50.toString(),
      'page': 1.toString(),
      'filter[logic]': 'and',
      'filter[filters][0][operator]': 'startsWith',
      'filter[filters][0][field]': 'nazione',
      'filter[filters][0][value]': 'it'
})

In this case queryParameter in Uri works. I'm new to Dart, so before I try to resolve from scratch this problem I would like to know if exists some easy and correct way to do this.

assistbss
  • 527
  • 7
  • 25

1 Answers1

0

Use queryParameters of the Uri class:

Uri(scheme: 'http', host: 'example.com', queryParameters: {...})
Patrick
  • 3,578
  • 5
  • 31
  • 53