flutter - Flutter 显示来自模拟 .json 文件的数据
问题描述
我正在尝试从recipes.json
颤振的模拟文件中加载数据,并且我有这样的结构
lib
|__mock_data
|__recipes.json
|__src
|__models
|__components
|__screens
|__app.dart
|__main.dart
现在我创建了一个看起来像这样的模型:
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;
String time;
factory RecipeModel.fromJson(Map<String, dynamic> json) => RecipeModel(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
videoLink:
json["audioAssetPath"] == null ? null : json["audioAssetPath"],
author: json["isRemoteUrl"] == null ? null : json["isRemoteUrl"],
category: json["iconUrl"] == null ? null : json["iconUrl"],
time: json["vol"] == null ? null : json["vol"].toDouble(),
);
}
在我要显示数据的页面中,我正在执行此操作:
Future<List<RecipeModel>> fetchRecipes() async {
String url =
"https://raw.githubusercontent.com/boriszv/json/master/random_example.json";
var response = await http.get(url); ----------->The argument type 'String' can't be assigned to the parameter type 'Uri'
print(response);
var recipes = <RecipeModel>[];
var recipesJson = json.decode(response.body);
for (var index in recipesJson) {
recipes.add(RecipeModel.fromJson(index));
}
throw '';
}
@override
void initState() {
super.initState();
fetchRecipes();
}
分配 URL 时出现错误以及如何加载当前recipe.json
数据?
json
注意:模型写对了吗?因为可能会从protobuf
解决方案
要加载本地文件,您可以将文件放在 assets 文件夹中。
Future<List<RecipeModel>> loadLocalRecipe() async { try { String response = await rootBundle.loadString('assets/recipe.json'); List<dynamic> result = json.decode(response); return result.map((n) => RecipeModel.fromJson(n)).toList(); } catch (e) { throw Padding( padding: EdgeInsets.only(top: 50), child: Center( child: Text('Convert Error'), ), ); } }
发布规范.yaml
flutter: assets: - assets/receipe.json
要获取服务器数据,您可以使用它。
Future<List<RecipeModel>> getRecipe() async { try { final http.Response response = await http.get("https://example.com", headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); // print(response.body); List<dynamic> result = json.decode(response.body) as List; return result.map((n) => RecipeModel.fromJson(n)).toList(); } catch (e) { throw Padding( padding: EdgeInsets.only(top: 50), child: Center( child: Text('Connection Error'), ), ); } }
推荐阅读
- c++ - C++:将 const 用于当前是枚举的函数参数
- angular - Angular:HTML 画布应该是组件还是服务?
- statnet - 节点动态——STATNET / TERGM 中的进入和退出
- python - 在 Python 中提取部分 JSON 响应
- python - 按钮的像素宽度和高度?
- bazel - Bazel 查询依赖于文件
- templates - 如何在 Golang 中同时使用“html/template”和“text/template”
- spring - @NotNull 没有在 Spring Framework 中验证并且没有产生正确的结果
- javascript - 纸张下拉单击上的聚合物 3.0 未捕获参考错误
- sql - SQL 使用 AND 查找列中的两个值