【问题标题】:Flutter show data from mock .json fileFlutter 显示来自模拟 .json 文件的数据
【发布时间】:2021-04-27 18:26:03
【问题描述】:

我正在尝试从颤振中的模拟 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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:
    • 要加载本地文件,可以将文件放在 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'),
            ),
          );
        }
      }
      
    • pubspec.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'),
        ),
        );
       }
      }
      

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 2021-10-17
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多