user5927645
user5927645

Reputation:

pass parameters as Map in flutter http.get GET request

Is there any way to conveniently pass both parameters/queries as a Map<String,Dynamic> itself along with headers into the get request in flutter. As of now, I'm using http package and can only do it with url string manipulations as follows:

var headers={
    'accept': 'application/json',
    'Accept-Language': 'en_US',
    'user-agent': 'Mozilla/5....'
    };
final response = await http.get(Uri.parse(url+'?district_id=$district_id'+'&date=$date'), headers:headers);

the http.get only accepts url and headers, unlike in python get where payload dictionaries can be used as parameters. I want achieve it simply, like:

final response = await http.get(Uri.parse(url), params:params, headers:headers);

or any other method without string manipulation.

Update: I tried using Uri constructor. But it throws error. The Map I need to pass is

{'district_id':298, 'date':'10-06-2021'}; \\has int and String as values.

Error:

type 'int' is not a subtype of type 'Iterable'

As of now, I could only make it work by changing the int 298 to String '298'.

Upvotes: 2

Views: 3628

Answers (1)

Amir Panahandeh
Amir Panahandeh

Reputation: 9039

You can use dio.request which accepts a Map<String, dynamic> object called queryParameters.

dio.request(path,
    options: Options(method: 'GET', headers: headers),
    queryParameters: {'district_id': districtId},
)

Upvotes: 1

Related Questions