You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter从Google Drive导入JSON文件报错求助

问题根源

你使用的Google Drive链接是网页预览链接,调用http.get后返回的是HTML页面代码,而非JSON内容,因此json.decode会抛出解析错误,这就是导入失败的核心原因。而Firestore Storage的链接直接指向原始文件,所以能正常读取。

解决步骤
  1. 替换Google Drive链接为直接下载地址
    将原链接中的/view?usp=sharing替换为/uc?export=download&id=文件ID,或者/export?format=json。你的文件ID是1tAxO2kRD0NVBhefA3srbj1SKQ2l8u9Wc,正确的URL示例:

    https://drive.google.com/uc?export=download&id=1tAxO2kRD0NVBhefA3srbj1SKQ2l8u9Wc
    

    或:

    https://drive.google.com/file/d/1tAxO2kRD0NVBhefA3srbj1SKQ2l8u9Wc/export?format=json
    
  2. 确保文件权限设置正确
    打开Google Drive中的JSON文件,点击右上角「分享」,将权限设置为「知道链接的任何人都能查看」,否则请求会返回权限错误。

  3. 优化错误调试(推荐)
    原代码仅显示“error”,无法定位具体问题,修改FutureBuilder的错误提示,显示具体错误信息:

    if (snapshot.hasError) {
      return Center(child: Text('错误信息: ${snapshot.error}'));
    }
    

    同时在UsersApi中添加异常捕获,便于调试:

    static Future<List<User>> getApps() async {
      try {
        final url = Uri.parse(
            'https://drive.google.com/uc?export=download&id=1tAxO2kRD0NVBhefA3srbj1SKQ2l8u9Wc');
        final response = await http.get(url);
        // 检查响应状态码
        if (response.statusCode != 200) {
          throw Exception('请求失败,状态码: ${response.statusCode}');
        }
        final body = json.decode(response.body);
        return body.map<User>(User.fromJson).toList();
      } catch (e) {
        print('获取数据失败: $e');
        rethrow; // 抛出异常让FutureBuilder捕获
      }
    }
    
修改后的完整UsersApi代码
import 'dart:convert';
import 'package:http/http.dart' as http;

class UsersApi {
  static Future<List<User>> getApps() async {
    try {
      final url = Uri.parse(
          'https://drive.google.com/uc?export=download&id=1tAxO2kRD0NVBhefA3srbj1SKQ2l8u9Wc');
      final response = await http.get(url);

      if (response.statusCode != 200) {
        throw Exception('请求失败,状态码: ${response.statusCode}');
      }

      final body = json.decode(response.body);
      return body.map<User>(User.fromJson).toList();
    } catch (e) {
      print('获取数据失败: $e');
      rethrow;
    }
  }
}

内容的提问来源于stack exchange,提问作者SameJall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:45:49