1

so I have a json file(mock data). It goes something like this:

{
    "data":
    [
        {
            "id": "1",
            "name": "Kacchi Biriyani",
            "videoLink": "https://www.youtube.com/watch?v=K4TOrB7at0Y",
            "author": "Alan Ford",
            "category":"Biriyani",
            "time": "15 min",
            "steps": {
                "step 1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
                "step 2": "Suspendisse vel sapien elit"
            },
            "isFavorite": "yes"
        },
        {
            "id": "2",
            "name": "Mughal Biriyani",
            "videoLink": "https://www.youtube.com/watch?v=aNVviTECNM0",
            "author": "Ricky James",
            "category":"Biriyani",
            "time": "10 min",
            "steps": {
                "step 1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
                "step 2": "Suspendisse vel sapien elit",
                "step 3": "Proin luctus, quam non dapibus pretium",
                "step 4": "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
            },
            "isFavorite": "yes"
        }

    ]
}

This is what I have as my model:

class RecipeModel {
  final String id;
  final String name;
  final String videoLink;
  final String author;
  final String category;
  final String time;
  RecipeModel({
    required this.id,
    required this.name,
    required this.videoLink,
    required this.author,
    required this.category,
    required this.time,
  });

  factory RecipeModel.fromJson(Map<String, dynamic> json) {
    return RecipeModel(
      id: json['id'],
      name: json['name'],
      videoLink: json['videoLink'],
      author: json['author'],
      category: json['category'],
      time: json['time'],
    );
  }
}

Now as you can see the steps:{...} are dynamic so it can be different for different items. One item can have 5 steps on the other hand another item can have more than 10 steps.

How can I write a dynamic List in my model for steps data that's coming from json?

Update 1:

  List<RecipeModel> recipes = [];
  Future<List<RecipeModel>> getRecipeData() async {
    // var response = await http.get(
    //   Uri.https("jsonplaceholder.typicode.com", 'users'),
    // );
    String response = await DefaultAssetBundle.of(context)
        .loadString('assets/json/recipe.json');
    var result = json.decode(response);

    for (var u in result["data"]) {
      RecipeModel recipe = RecipeModel(
        id: u['id'] ?? "",
        name: u['name'] ?? "",
        videoLink: u['videoLink'] ?? "",
        author: u['author'] ?? "",
        category: u['category'] ?? "",
        time: u['time'] ?? "",
        // steps: u["steps"],
      );
      recipes.add(recipe);
    }
3
  • Can you change your json structure or is it set as is? Commented Apr 29, 2021 at 20:31
  • it is as it is. It's just a mock file I'm using since the apis are not ready yet. but different recipes can have steps Commented Apr 29, 2021 at 20:33
  • Recommend that you use code generation for your models. It'll help when your project gets bigger. pub.dev/packages/json_serializable Commented Apr 29, 2021 at 22:13

2 Answers 2

1

Cast the map of steps into a List<String> type using the from method.


// The steps from your api call.
var json = { "steps": { "step 1": "foo", "step 2": "bar" } }

// Convert the steps from the map to a List.
List<String> steps = List<String>.from(json["steps"].values);

// The result.
steps = ['foo', 'bar']


Update

This is what your RecipeModel should look like.


class RecipeModel {
  final String id;
  final String name;
  final String videoLink;
  final String author;
  final String category;
  final String time;
  // The dynamic list of steps.
  final List<String> steps;

  RecipeModel({
    required this.id,
    required this.name,
    required this.videoLink,
    required this.author,
    required this.category,
    required this.time,
    // The dynamic list of steps.
    required this.steps,
  });

  factory RecipeModel.fromJson(Map<String, dynamic> json) {
    return RecipeModel(
      id: json['id'],
      name: json['name'],
      videoLink: json['videoLink'],
      author: json['author'],
      category: json['category'],
      time: json['time'],
      // The dynamic list of steps.
      steps: List<String>.from(json['steps'].values),
    );
  }
Sign up to request clarification or add additional context in comments.

7 Comments

I was actually looking to modify my model class. I can fetch the data no problem. Please check the model I've already provided
Yes, you can still use your model class. Simply add this to your fromJson method ~ steps: List<String>.from(json[‘steps’].values)
I'm looking to create a model of steps. I want to write that dynamic list in my Recipe.model.dart file. I know how to access the data from .json file and store it in a list
Could you give an example of what it would look like because, I am not sure what your question is.
Are you familiar with MVC pattern? M stands for model which is basically a model for the incoming data. In my case the json data I'm getting has recipeName, recipeVideoLink etc. So, that's what my class has as you can see from the Recipe{} class
|
0

Also just as a suggestion, make your variables match the data type it will be holding. For example, id can be and int instead of String, isFavorite can be a bool, etc. Trust me, it makes using them in dart code much easier.

Ex: if(isFavorite) {...} instead of if(isFavorite.toLowerCase() == "yes") {...}

1 Comment

yes I'll do that as soon the structure is ready. I call it the cleanup phase

Your Answer

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