使用post方法调用API时出现错误“类型'_InternalLinkedHashMap <String,dynamic>'不是类型'String''的子类型”

时间:2019-10-17 15:28:37

标签: http flutter flutter-dependencies

我正在尝试使用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!"
}

1 个答案:

答案 0 :(得分:0)

根据您在评论中提到的内容,您的回复不在T[K]中,而在<T, K extends keyof T>(obj: T, key: K, value: T[K]) 中,因此您需要进行相应的更改。

替换

String

bool

也替换

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

if (data["status"])