【问题标题】:Flutter/Dart: Type 'int' is not a subtype of type 'String' in type castFlutter/Dart:类型“int”不是类型转换中“String”类型的子类型
【发布时间】:2020-03-19 05:56:50
【问题描述】:

我已经回答了这个问题,但没有一个涵盖我似乎遇到的情况(由于缺乏理解答案,我可能错了)。因此,我应该问。

我已经用 Postman 用相同的参数和数据测试过 API,它工作得很好。

onPressed: ()async {
                        print('Counter: $counter, Type: $type, Phone: $phone, Token: $token');
                        print(counter.runtimeType);
                        if(counter != 0){
                          print('above post now');
                          var response = await http.post(
                            acceptPass, //final URL in string

                            body:{
                              'type': type, //string
                              'phone': phone, //string
                              'qty': counter //int. Tried sending as string too, didn't work.
                            },
                            headers: {
                              'token': token //string
                            }
                          );
                          print("something with the response here ");
                          print(response.statusCode);
                        }

                      },

没有一个值是空的,我确实将它们打印出来并在将它们放入 post 方法之前检查它们。我还尝试将每个变量类型转换为字符串,然后发布它,但无济于事。

【问题讨论】:

  • 你试过.., body: json.encode({'type':type,...}), ..
  • 其他请求顺利通过,因为都是表​​单数据。
  • 请在抛出异常时显示调试器中的局部变量。
  • 变量包含数据,我无法显示。但正如我所说,它们不是空字符串或 null,并且该数据用于另一个可以正常工作的请求中

标签: flutter dart


【解决方案1】:

body 必须是 Map<String, String>。因此,您需要将int 转换为字符串,然后再将其放入地图中。

在counter 之后添加.toString()。

要让编译器帮助您进行类型检查,您可以显式键入映射,如下所示。

  body: <String, String>{
    'fieldName': 'fieldValue',
    //etc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2020-11-24
    • 2022-07-06
    相关资源
    最近更新 更多