2

I am trying to build dynamic widget(cards, blocks, containers with some properties) based on a list of items(entries). Trying to create a function for that(I don't need to create a separate class for that right?).

  List entries = ['stock1', 'stock2', 'stock3'];

  Widget buildListView() {
    return ListView.builder(
        padding: EdgeInsets.all(8),
        itemCount: entries.length,
        itemBuilder: (BuildContext context, int index) {
          return new Container(
            height: 50,
            color: Colors.lightBlue,
            child: Center(child: Text('Entry ${entries[index]}')),
          );
        });
  }

And then I am trying to call that function and add to my body to the list of the widget so it builds all the widget automatically(and I don't have to create them one by one manually).

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          Container(
              height: 20.0,
              alignment: Alignment.center,
              padding: EdgeInsets.only(bottom: 8.0),
              color: Colors.lightBlue,
              child: Text('Hello. This is a Container')), //Container
          buildListView(),
        ],
      ),
    );
  }

I've also read somewhere you can utilize .map() method somehow if it's relevant here?

How do I make it work? Please share solutions/ideas or helpful sources/links about this topic.

1 Answer 1

1

Yes, you can do it:

Column(
   children: [
        for(final entry in entries)
          Container(
            height: 50,
            color: Colors.lightBlue,
            child: Center(child: Text(entry)),
          ),
        ],
),

Or if you wish to use map, you need to add toList() in the end:

entries.map((entry) => Container(
            height: 50,
            color: Colors.lightBlue,
            child: Center(child: Text(entry)),
          ),
          ).toList(),

Read article on this

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.