Flutter 从数据库检索数据时出现问题

问题描述 投票:0回答:1

所以我正在创建一个简单的议程应用程序,问题是当我查找所有联系人时,我有两个选择,这些联系人确实出现,并且它们被写入数据库和使用 Google Apps 脚本创建的后端。一旦我进行备份,数据就会写入“数据库”(目前只是一个 Google Sheets 文档),但是一旦我尝试恢复它,在应用程序中显示的只是错误,我有这个用于后端:

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;
  }
}

这是将数据备份到数据库的:

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;
  }

正在请求为备份的数据创建的 JSON,但无法检索回来。在记录器中显示这一点。

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

我这里有这个按钮选项:

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);
}

感谢任何帮助!

database flutter mobile sqflite
1个回答
0
投票

预期为 JSON,但得到的是 text/html;字符集=utf-8

这样的

FormatException
来自响应本身,您期待
json
响应,但整个响应是
HTML
形式:

通常,当响应是 HTML 时,这是因为发生了与客户端相关的错误,例如您没有授权。或者对于我的情况,有一个请求限制6个请求/秒,所以我在

HTML
中得到了响应,这导致了
FormatException

因此,为了检测您的请求有什么问题,请将该请求链接放入搜索引擎中,并找出响应的内容以找出问题所在。

© www.soinside.com 2019 - 2024. All rights reserved.