I have a method to read the data from the database. The code is completely working, but there is a problem, it is if I run the code and there is no data in the database, I get the error:
JavaScript
x
E/flutter (29414): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (29414): No Data Found.
E/flutter (29414): ^
And my code:
JavaScript
Future<List<data>> FetchT() async {
apiURL = 'https://*******.com/getList.php?C=' +
gatName.toString();
var response = await http.get(apiURL);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<data> listOfFruits = items.map<data>((json) {
return data.fromJson(json);
}).toList();
return listOfFruits;
} else {
//throw Exception('Failed to load data from Server.');
}
}
PHP code:
JavaScript
<?php
include 'connt.php';
$C= $_GET["C"];
$sql = "SELECT * FROM top WHERE C=? ORDER BY id DESC ";
$result = $con->query($sql);
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$C);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
echo "No Data Found.";
}
echo $json;
$con->close();
?>
I previously searched the old topics here and tried all the topics and problems similar to mine, but I did not find a solution to my problem.
How can I solve this problem?
Advertisement
Answer
You didn’t specify the header code if no data is found.
You should change your php code to this:
JavaScript
<?php
include 'connt.php';
$C= $_GET["C"];
$sql = "SELECT * FROM top WHERE C=? ORDER BY id DESC ";
$result = $con->query($sql);
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$C);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
http_response_code(404);
$json = json_encode(["error" => "No Data Found."]);
}
echo $json;
$con->close();
?>