So i’m creating a simple agenda app, the thing is i have two options once i’m looking for all the contacts, the do appear and they are written into a database and a backend created with Google Apps Script. Once i do the backup the data is written into the “database”(Which is currently just a Google Sheets doc) but once i try to recover it, to be shown in the app theres just errors, i have this for the backend:
import 'package:http/http.dart' as http;
import 'package:logger/logger.dart';
class BackendHelper {
static const String _server = "script.google.com";
static Logger logger = Logger();
static Future<int> sendData(String jsonData) async {
var client = http.Client();
int code = -1;
try {
var response = await client.post(
Uri.https(_server, "macros/s/AKfycby3g-CRk53h4Rr07VWxJr4d6CYm33_-cft8nOeIlwAuOFwAjzMz6jDamo_HHxpFtTz-/exec"),
body: {'acc': '2', 'tbl': 'Contacts', 'data': jsonData},
);
code = response.statusCode;
logger.i(response.statusCode);
} finally {
client.close();
}
return code;
}
static Future<String> getData() async {
var client = http.Client();
String responseBody = '';
try {
var response = await client.get(
Uri.https(_server, "macros/s/AKfycby3g-CRk53h4Rr07VWxJr4d6CYm33_-cft8nOeIlwAuOFwAjzMz6jDamo_HHxpFtTz-/exec"),
headers: {'acc': '1', 'tbl': 'Contacts'},
);
if (response.statusCode == 200) {
if (response.headers['content-type']?.contains('application/json') == true) {
responseBody = response.body;
logger.i('Data retrieved successfully');
} else {
logger.e('Expected JSON but got ${response.headers['content-type']}');
responseBody = 'Invalid response: Expected JSON';
}
} else {
logger.e('Failed to retrieve data. Status code: ${response.statusCode}');
responseBody = 'Error: ${response.statusCode}';
}
} finally {
client.close();
}
return responseBody;
}
}
Here’s the one that backups the data into the database:
static Future<int> sendData(String jsonData) async {
var client = http.Client();
int code = -1;
try {
var response = await client.post(
Uri.https(_server, "macros/s/AKfycby3g-CRk53h4Rr07VWxJr4d6CYm33_-cft8nOeIlwAuOFwAjzMz6jDamo_HHxpFtTz-/exec"),
body: {'acc': '2', 'tbl': 'Contacts', 'data': jsonData},
);
code = response.statusCode;
logger.i(response.statusCode);
} finally {
client.close();
}
return code;
}
Is asking for the JSON created for the data that’s backedup, but it’s not able to retrieve ir back. In the logger shows this.
Expected JSON but got text/html; charset=utf-8
I/flutter (11811): │ #0 _ContactListWidgetState.recoverContacts
I/flutter (11811): │ #1 <asynchronous suspension>
I/flutter (11811):
Failed to parse JSON: FormatException: Unexpected character (at
Invalid response: Expected JSON
I have this option for the button here:
Future<void> recoverContacts() async {
var response = await BackendHelper.getData();
try {
List<dynamic> recoveredContacts = json.decode(response);
ContactProvider conProv = ContactProvider();
await conProv.open("ContactsDB");
await conProv.deleteAllContacts();
for (var contactData in recoveredContacts) {
Contact contact = Contact(
name: contactData['name'],
phone: contactData['phone'],
email: contactData['email'],
);
await conProv.insert(contact);
}
await conProv.close();
await loadAllContacts();
var snackBar = const SnackBar(
content: Text('Contactos recuperados exitosamente.'),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
logger.i("RECOVER CONTACTS FINISHED.");
} catch (e) {
logger.e('Failed to parse JSON: $e');
var snackBar = const SnackBar(
content: Text('Error recuperando contactos: Formato de datos incorrecto.'),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
Appreciate any help!
Expected JSON but got text/html; charset=utf-8
Such FormatException
s are coming from the response itself, you are expecting a json
response but the whole response is in HTML
form:
Generally when response is HTML that’s because something wrong related to Client has been occurred such as you are not authorized. or for my case there was a request limit 6 request/second so i got the response in HTML
which lead to FormatException
.
So, for detecting what’s wrong with your request, put that request link in a search engine and figure out what the response is saying to figure out the problem.