Search code examples
flutterdartdio

How to add a Map to MapEntry in flutter dio package


I want to send a form data to the backend using the Dio package one of the fields accepts a map instead of a String.

formData.fields.add(MapEntry('category', _category));
    formData.fields.add(MapEntry('license_number', _licenseNumber.text));
    formData.fields.add(MapEntry('license_issued_on', _licenseIssueDateString));
//The line below is the one causing the error. The argument type 'Map<String, Object>' can't be assigned to the parameter type 'String'.
   formData.fields.add(MapEntry('address', {'address': _address.text, 'lattitude': _addressLat, 'longitude': _addressLng}));

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values How can I go around this issue?


Solution

  • Convert a map to a JSON string. Naturally backend has to decode a string.

    fields → List<MapEntry<String, String>> The form fields to send for this request.

    import 'dart:convert';
    
    formData.fields.add(MapEntry('address', jsonEncode({'address': _address.text, 'lattitude': _addressLat, 'longitude': _addressLng})));