【问题标题】:getting error "type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' '"when calling API using post method使用 post 方法调用 API 时出现错误“type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' '”
【发布时间】:2020-02-14 13:53:10
【问题描述】:

我正在尝试使用 post 方法进行 API 调用,以传递一个参数并获取响应。 我尝试过的代码如下'

void senddata() async {
    try {
      http.Response response = await http.post(Uri.encodeFull("http://192.168.1.61:8080/mobile/unlock"), 
      body: {
        'qr_string': barcode,
      });
      if (response.statusCode < 200 ||
          response.statusCode > 400 ||
          json == null) {

        throw new Exception("Error while fetching data");
      } else if (response.statusCode == 200) {
        var data = json.decode(response.body);


        if (data["status"] == "true") {
          showResult("Successfuly Unlocked");
          buttontxt = "Lock";
          mesagestatus = 1;
        } else if (data["status"] == "false") {
          showResult("Not permitted.Vehicle in use!");
          buttontxt = "Un-Lock";
          mesagestatus = 2;
        }
      }
    } on SocketException catch (_) {} catch (e) {
             }
  }

在我的 pubspec.yaml 中 我添加了依赖

http: ^0.12.0+2

但我的问题是当我尝试拨打电话时显示以下错误

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' 

我尝试了很多,但每次都显示同样的错误。

这是我的完整代码

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:io';

class QrScan extends StatefulWidget {
  @override
  _QrSCannState createState() => _QrSCannState();
}

class _QrSCannState extends State<QrScan> {
  String barcode = "";
  bool isProgress = false;
  String buttontxt = "Un-Lock";
  int mesagestatus = 0;
  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (isProgress) {
      return Scaffold(
        body: Center(
          child: CircularPercentIndicator(
            radius: 100.0,
            lineWidth: 10.0,
            percent: 0.8,
            header: new Text("Icon header"),
            center: new Icon(
              Icons.person_pin,
              size: 50.0,
              color: Colors.blue,
            ),
            backgroundColor: Colors.grey,
            progressColor: Colors.blue,
          ),
        ),
      );
    } else {
      return Scaffold(
          appBar: new AppBar(
            title: new Text('App Name'),
          ),
          body: new Center(
            child: new GestureDetector(
              onTap: () {
                if (mesagestatus == 0) {
                  scan();
                } else if (mesagestatus == 1) {
                  lockbike();
                }

              },
              child: Container(
                height: 100,
                width: 100,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    gradient: LinearGradient(colors: [
                      Color.fromRGBO(143, 148, 251, 1),
                      Color.fromRGBO(143, 148, 251, .6),
                    ])),
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.lock_open,
                        color: Colors.white,
                        size: 50.0,
                      ),
                      Text(
                        buttontxt,
                        style: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ));
    }
  }

  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      senddata();
      setState(() => this.barcode = barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    }
  }

  void senddata() async {
    try {

      http.Response response = await http.post(Uri.encodeFull("http://192.168.1.61:8080/mobile/unlock"), 
      body: {
        'qr_string': barcode,
      });

      if (response.statusCode < 200 ||
          response.statusCode > 400 ||
          json == null) {


        throw new Exception("Error while fetching data");
      } else if (response.statusCode == 200) {


        var data = json.decode(response.body);
        print("smartbike" + data);

        if (data["status"]) {
          showResult("Successfuly Unlocked");
          buttontxt = "Lock";
          mesagestatus = 1;
        } else if (!data["status"]) {
          showResult("Not permitted.Vehicle in use!");
          buttontxt = "Un-Lock";
          mesagestatus = 2;
        }
      }
    } on SocketException catch (_) {} catch (e) {
      print("jijost"+e.toString());//  **here the error is thrown**

    }
  }

  Future showResult(String message) {
    return showDialog(
      context: context,
      builder: (context) => new AlertDialog(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(20.0))),

            content: Container(
              height: 240,
              child: Column(
                children: <Widget>[
                  Icon(
                    Icons.check_circle_outline,
                    color: Colors.green,
                    size: 100.0,
                    semanticLabel: 'Thanks',
                  ),
                  Text(message),
                  SizedBox(height: 20),
                  MaterialButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text(
                      ' Close ',
                      style: TextStyle(color: Colors.white),
                    ),
                    color: Colors.red,
                    onPressed: () {
                      setState(() {});
                      Navigator.of(context).pop(false);
                    },
                    padding: EdgeInsets.all(13),
                  ),
                ],
              ),
            ),
          ),
    );
  }

  void lockbike() async {
    try {
      http.Response response = await http
          .post(Uri.encodeFull("http://localhost:8080/mobile/lock"), body: {
        "qr_string": "Monster122C",
      });

      if (response.statusCode < 200 ||
          response.statusCode > 400 ||
          json == null) {
        throw new Exception("Error while fetching data");
      } else if (response.statusCode == 200) {
        var data = json.decode(response.body);

        if (data["status"] == "true") {
          showResult("Successfully Un Locked");
          buttontxt = "Un-Lock";
          mesagestatus = 1;
        }
      }
    } on SocketException catch (_) {} catch (e) {
      print(e.toString());
    }
  }
}

API 响应如下所示

For success:

 {
    "status": true
}

 For Failure :

 {
    "status": false,
    "info": "Not permitted.Vehicle in use!"
}

【问题讨论】:

  • 您的data 在控制台上打印什么?
  • { "qr_string" : "Monster122C" } 我的参数会是这样的
  • 您的回答将是还是这个?
  • 成功:{ "status": true } 失败:{ "status": false, "info": "Not allowed.!" } 我的回答是这样的
  • 对不起,这不是一个可重现的代码,当我点击按钮时,应用程序崩溃并显示HttpException: Connection closed before full header was received

标签: http flutter flutter-dependencies


【解决方案1】:

根据您在评论中提到的,您的回复不在String,而是在bool,因此您需要进行相应的更改。

替换

if (data["status"] == "true") 

if (data["status"]) 

也替换

else if (data["status"] == "false")

else if (!data["status"])

【讨论】:

  • 根据您提供的信息应该已经解决了问题,请发布您的完整data回复。您还可以分享您看到错误的行号吗?
猜你喜欢
  • 2021-10-22
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 2022-11-19
  • 2023-02-17
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多