Flutter加载本地mock recipes.json的http报错、模型及加载方法咨询
问题解决方案
1. 修复http.get参数类型不匹配报错
当前http包新版本要求传入的第一个参数是Uri类型,不再支持直接传字符串,修复方式如下:
- 将URL字符串通过
Uri.parse()转为Uri对象后再传入
// 修复前(报错) var response = await http.get("你的请求地址"); // 修复后 final requestUri = Uri.parse("你的请求地址"); var response = await http.get(requestUri);
如果需要拼接查询参数,也可以用Uri.https()构造,避免手动拼接字符串出错。
2. 本地recipes.json文件加载配置
Flutter默认不会自动打包lib目录下的自定义文件,需要先完成两步配置:
第一步:声明assets资源
打开项目根目录下的pubspec.yaml,在flutter节点下添加资源声明,注意严格遵循yaml缩进规则:
flutter: assets: - lib/mock_data/recipes.json
第二步:编写本地文件加载逻辑
加载本地assets需要用到rootBundle,需先导入package:flutter/services.dart,替换原有网络请求逻辑如下:
// 导入依赖 import 'dart:convert'; import 'package:flutter/services.dart' show rootBundle; Future<List<RecipeModel>> fetchRecipes() async { // 加载本地json字符串 final jsonStr = await rootBundle.loadString('lib/mock_data/recipes.json'); // 解码json数组 final List<dynamic> recipesJson = json.decode(jsonStr); // 转换为模型列表 final recipes = <RecipeModel>[]; for (var item in recipesJson) { recipes.add(RecipeModel.fromJson(item)); } // 删除原有多余的throw逻辑,否则会直接抛出异常无法返回数据 return recipes; }
3. RecipeModel 修正与适配protobuf建议
现有模型的错误修正
你当前编写的RecipeModel存在多处错误:
- 构造函数声明了
required非空参数,但fromJson中允许传null,类型约束冲突 - 字段映射完全错位:比如
videoLink错误读取了audioAssetPath字段,author错误读取了isRemoteUrl字段,category错误读取了iconUrl字段 - 类型不匹配:
time定义为String类型,但代码中尝试把vol字段转成double赋值
修正后的示例(假设你的json字段和模型字段一一对应):
class RecipeModel { RecipeModel({ required this.id, required this.name, required this.videoLink, required this.author, required this.category, required this.time, }); String id; String name; String videoLink; String author; String category; // 如果后续protobuf用到数值类型,可提前调整为num/double String time; factory RecipeModel.fromJson(Map<String, dynamic> json) => RecipeModel( id: json["id"] as String, name: json["name"] as String, videoLink: json["videoLink"] as String, author: json["author"] as String, category: json["category"] as String, time: json["time"] as String, ); }
如果需要兼容空值,可将字段改为可空类型(String? id),移除required修饰符。
后续适配protobuf的建议
- 提前统一模型字段的类型:比如如果protobuf中time是数值类型,现在就可以将当前的
String time调整为num time,减少后续适配成本 - 不要把解析逻辑硬耦合在业务代码中:可以给
RecipeModel新增factory RecipeModel.fromProto(protobufObj)的工厂方法,上层调用逻辑完全不用改动 - 优先用代码生成工具处理json/protobuf的解析逻辑,避免手写映射出现错位错误
内容的提问来源于stack exchange,提问作者user14709104
相关产品推荐
相关产品推荐

