Home > Net >  http dart: How to send a Map in the query parameters of a request?
http dart: How to send a Map in the query parameters of a request?

Time:02-28

I have a http request like this using the http package:

import 'package:http/http.dart' as http;

Uri url = Uri.http(
  'http://sample.com',
  '/request',
  {
    'dataMap': {
      'key1': ['item1', 'item2']
      'key2': ['item1', 'item2']
    },
  },
);

I get this error:

 _TypeError (type '_InternalLinkedHashMap<String, List<String>>' is not a subtype of type 'Iterable<dynamic>')

The error is not thrown if I don't put a map in the query parameters.

So how do I send a Map?

CodePudding user response:

You could jsonEncode the map:

import 'dart:convert';

void main() {
  Uri url = Uri.http(
    'sample.com',
    '/request',
    {
      'dataMap': jsonEncode({
        'key1': ['item1', 'item2'],
        'key2': ['item1', 'item2']
      }),
    },
  );
  
  print(url);
}

CodePudding user response:

You can achieve this way :

  _request() async {
    
    
    var outer = {};
    
    outer['dataMap'] =  {
          'key1': ['item1', 'item2'],
           'key2': ['item1', 'item2']
    };
    
    print(jsonEncode(outer));
 
    
    
    return  http.post(Uri.parse('https://www.example.com/request'), body: jsonEncode(outer));
    
    
  }
  • Related