Home > Software engineering >  How to access elements in a different model list in one model?
How to access elements in a different model list in one model?

Time:01-31

I have two models and a data.

class ModelA {
  final int id;
  final String title;
  final List<ModelB> sections;

  const ModelA({required this.id, required this.title, required this.sections});
}

class ModelB {
  final int id;
  final String title;

  const ModelB({required this.id, required this.title});
}

const data = [
  ModelA(
      id: 1,
      title: "title1",
      sections: [
        ModelB(id: 1, title: "a"),
        ModelB(id: 2, title: "b")
      ]),
  ModelA(
      id: 2,
      title: "title2",
      sections: [
        ModelB(id: 1, title: "c"),
        ModelB(id: 2, title: "d"),
        ModelB(id: 3, title: "e"),
      ]),
  ModelA(
      id: 3,
      title: "title3",
      sections: [
        ModelB(id: 1, title: "f"),
      ]),
];

As a category, I list the titles in each ModelA with map.

I want to reach each title in List<ModelB> in ModelA with showModalBottomSheet when each item in ModelA is clicked. Like this:Like this

How can I get to each element of the model list that is under each model?

Code:

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView(
          children: data.map((e) =>
              InkWell(child: Text(e.title), onTap: () {
                showModalBottomSheet(
                    context: context,
                    builder: (BuildContext context) {
                      return SizedBox(
                        height: 300,
                        child: ListView(
                            children: []//??
                        ),
                      );
                    });
              },))
              .toList(),
        ));
  }

CodePudding user response:

You already have the modelA item from the map. So, you can get the sections titles with it:

var titles = e.sections.map((modelB) => modelB.title).toList();

Or, for text widgets:

var widgets = e.sections.map((modelB) => Text(modelB.title)).toList();

Then, you can use it to your code something like this (not tested yet):

return SizedBox(
    height: 300,
    child: ListView(
        children: e.sections.map((modelB) => Text(modelB.title)).toList()
    ),
  );
  •  Tags:  
  • Related