首页 > 解决方案 > 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

标签: flutterdart

解决方案


  • 要加载本地文件,您可以将文件放在 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'),
      ),
      );
     }
    }
    

推荐阅读