发送发布请求时,类型“ int”不是类型转换中类型“字符串”的子类型

时间:2019-01-21 05:10:13

标签: post flutter http-post

发送帖子请求时出现奇怪的错误。

// 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);

这是错误:

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)

我可以在另一个屏幕上正常工作,我唯一看到的区别是,正在工作的屏幕只有Strings,而这个屏幕只有int,double和String。

3 个答案:

答案 0 :(得分:1)

要解决您的问题,只需在发送之前对数据进行编码。

 import 'dart:convert';
 ...

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

如果您的API不支持JSON,则只需将所有数据作为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);

答案 1 :(得分:1)

第1步:在标题中使用"content-type": "application/json"

第2步:像编码身体一样 jsonEncode( {"param1": 10, "param2":20,"param3": "abc","param4": true})

示例代码类似

 headers: {
      "content-type": "application/json",
    },
    body:jsonEncode( {
      "qualificationId": 10,
      "year":2001,
      "instituteName": "example",
      "isActive": true
    })

答案 2 :(得分:0)

签出 and like this one.-一个颤动的库来发出http请求(受python请求模块启发)

发布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']);

发布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']);