0

I'm trying to load data from a mock recipes.json file in flutter and I have a structure like this

lib
|__mock_data
   |__recipes.json
|__src
   |__models
   |__components
   |__screens
|__app.dart
|__main.dart

Now I have created a model which looks like this:

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(),
      );
}

In the page where I want to show the data I'm doing this:

  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();
  }

I get a error when assigning the URL and also how to load the current recipe.json data?

N.B: Are the models written right?Because there might be a shift from json to protobuf

1 Answer 1

2
  • To load a local file, you can put the file in the assets folder.

    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
    
  • To get server data, you can use this.

    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'),
      ),
      );
     }
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.