Я пытаюсь сделать вызов API, используя метод post для передачи одного параметра и получения ответа. код, который я попробовал, приведен ниже '
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!"
}