Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the widgets dynamically to column in Flutter?

I have added a few widgets inside the ListView. So that I can scroll all widgets. Now I required to add one more widget to the ListView to load the list of comments. I can not add the ListView inside the ListView. And moreover, I do not require the separate scroll for my comments. It should be scroll along with the widgets inside the ListView. So I planned to add the Column instead of ListView. Could any help to add my comments dynamically in the Columns?

new Expanded(
          child:
          new ListView(
            shrinkWrap: true,
            children: <Widget>[

              // Title

              new Padding(padding: const EdgeInsets.only(
                  top: 10.00, left: 10.00),
                child: new Text(
                  _feed.title, textAlign: TextAlign.start,),
              ),

              // content

              new Container(
                child: new Text(
                  _feed.content, textAlign: TextAlign.start,),
              ),

              // Comments List will go here

            ],
          ),
        ),
like image 851
esu Avatar asked Jul 31 '18 03:07

esu


People also ask

How do you display data dynamically in Flutter?

We can use ListView. builder(..) in Stateless Widgets if we want to display dynamic (different) contents every time the widget is loaded within an application. With Stateful widgets, it can change the contents of the screen dynamically.


2 Answers

If you have the comments data already, simply create a List, then pass it to the children property of the Column. Something like:

var commentWidgets = List<Widget>();
for (var comment in comments) {
  commentWidgets.Add(Text(comment.text)); // TODO: Whatever layout you need for each widget.
}
…

new Expanded(
      child:
      new ListView(
        shrinkWrap: true,
        children: <Widget>[

          // Title

          new Padding(padding: const EdgeInsets.only(
              top: 10.00, left: 10.00),
            child: new Text(
              _feed.title, textAlign: TextAlign.start,),
          ),

          // content

          new Container(
            child: new Text(
              _feed.content, textAlign: TextAlign.start,),
          ),

          // Comments List will go here
          Column(children: commentWidgets,),
        ],
      ),
    ),

If you don't have the comments data already and need to fetch it, use a FutureBuilder to build the UI once the future completes.

like image 147
Derek Lakin Avatar answered Sep 20 '22 06:09

Derek Lakin


By maintaining a reference to the Column object, the .children field/property can be referenced after the Column object has been declared - like so:

Column someColumn = Column(
  children: [],
);

someColumn.children.add(Text('Hello 123'));
like image 20
Gene Bo Avatar answered Sep 22 '22 06:09

Gene Bo