Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type 'int' is not a subtype of type 'String' in type cast when sending a post request

I have a weird error showing up when sending a post request.

// this map is passed to a function
final Map<String, dynamic> activityData = {
  "userId": 1,
  "name": activityName.text,
  "description": activityDescription.text,
  "startAt": activityStartAt.text,
  "endsAt": activityEndAt.text,
  "lat": _latitude,
  "long": _longitude,
  "category": 2,
  "status": "pending"
};

// this code bellow is inside a async function
final http.Response response =
        await http.post(Uri.encodeFull(url), body: activityData);

this is the error :

E/flutter (32582): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (32582): type 'int' is not a subtype of type 'String' in type cast
E/flutter (32582): #0      CastMap.forEach.<anonymous closure> (dart:_internal/cast.dart:286:25)
E/flutter (32582): #1      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection/runtime/libcompact_hash.dart:370:8)
E/flutter (32582): #2      CastMap.forEach (dart:_internal/cast.dart:285:13)
E/flutter (32582): #3      mapToQuery (package:http/src/utils.dart:17:7)
E/flutter (32582): #4      Request.bodyFields= (package:http/src/request.dart:128:17)
E/flutter (32582): #5      BaseClient._sendUnstreamed (package:http/src/base_client.dart:163:17)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #6      BaseClient.post (package:http/src/base_client.dart:54:7)
E/flutter (32582): #7      post.<anonymous closure> (package:http/http.dart:70:16)
E/flutter (32582): #8      _withClient (package:http/http.dart:166:20)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #9      post (package:http/http.dart:69:5)
E/flutter (32582): #10     _MainModel&Model&ConnectedModel&UsersModel&ActivitiesModel.createActivity (package:activmap/scoped-models/connectedModel.dart:62:15)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #11     _NewActivityState.save (package:activmap/pages/newActivity.dart:271:11)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #12     _NewActivityState.build.<anonymous closure> (package:activmap/pages/newActivity.dart:248:30)
E/flutter (32582): #13     _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter (32582): #14     _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter (32582): #15     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter (32582): #16     TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter (32582): #17     TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
E/flutter (32582): #18     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
E/flutter (32582): #19     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
E/flutter (32582): #20     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
E/flutter (32582): #21     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19)
E/flutter (32582): #22     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter (32582): #23     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter (32582): #24     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter (32582): #25     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter (32582): #26     _invoke1 (dart:ui/hooks.dart:168:13)
E/flutter (32582): #27     _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)

I have it working fine on another screen the only difference that I can see is that the one that's working only have Strings, while this one has int, double and String.

like image 912
Abdellah Chadidi Avatar asked Jan 21 '19 05:01

Abdellah Chadidi


4 Answers

For flutter version 2.0.6 and http dart package ^0.13.3, you will need to parse the URL and encode your payload using json.encode from the dart:convert library like so:

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

-------
 
var url = Uri.parse('http://10.0.2.2:8000/api/test'); 
var response = await http.post(url,  body: json.encode({ 'name': 'mac', 'password': 'test' }));

 print(response.body);
like image 160
Macdonald Avatar answered Nov 07 '22 05:11

Macdonald


To fix your issue you just have to encode the data before sending.

 import 'dart:convert';
 ...

 final http.Response response =
    await http.post(Uri.encodeFull(url), body: json.encode(activityData));

If your API doesn't support JSON, then you just have to pass all your data as String.

    final Map<String, dynamic> activityData = {
      "user_id": "1",
      "name": activityName.text,
      "description": activityDescription.text,
      "startAt": activityStartAt.text,
      "endsAt": activityEndAt.text,
      "lat": "$_latitude",
      "long": "$_longitude",
      "category": "2",
      "status": "pending"
    };

     final http.Response response =
    await http.post(Uri.encodeFull(url), body: activityData);
like image 25
diegoveloper Avatar answered Nov 07 '22 07:11

diegoveloper


Step 1: use "content-type": "application/json" in header

Step 2: encode your body like jsonEncode( {"param1": 10, "param2":20,"param3": "abc","param4": true})

Example Code Like

 headers: {
      "content-type": "application/json",
    },
    body:jsonEncode( {
      "qualificationId": 10,
      "year":2001,
      "instituteName": "example",
      "isActive": true
    })
like image 7
Ahmed Raza Avatar answered Nov 07 '22 07:11

Ahmed Raza


Check out requests - a flutter library to make http requests (inspired by python requests module)

Posting application/x-www-form-urlencoded:

var r = await Requests.post(
  "https://reqres.in/api/users", body: {
    "userId": 10,
    "id": 91,
    "title": "aut amet sed",
  },
  bodyEncoding: RequestBodyEncoding.FormURLEncoded);

r.raiseForStatus();
dynamic json = r.json();
print(json['id']);

Posting application/json:

var r = await Requests.post("https://reqres.in/api/users", json: {
    "userId": 10,
    "id": 91,
    "title": "aut amet sed",
    "body": "libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat",
  });

r.raiseForStatus();
dynamic body = r.json();
print(json['id']);
like image 1
Jossef Harush Kadouri Avatar answered Nov 07 '22 07:11

Jossef Harush Kadouri