20

Flutter is a fairly recent framework and as such not much assistance on simple tasks is available. What I am asking specifically is how do I add Card widgets to a Column widget. Source code is provided below to help to explain what I mean.

Lets say I have a function that creates a new Card as shown below:

buildRow(barcode, letter, name, price) {
  return new Card(
    child: new Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        new ListTile(
          leading: new CircleAvatar(
            child: new Text(letter),
          ),
          title: new Text(name),
          subtitle: new Text("\$" + price),
          trailing: new Text(
            "x1",
            style: new TextStyle(color: Colors.lightBlue),
            textScaleFactor: 1.2,
          ),
        ),
      ],
    ),
  );
}
var snack = buildRow("091918229292", "C", "Crackers", "\$4.00");
var fruit = buildRow("091928229292", "P", "Pomegranate", "\$2.00");
var juice = buildRow("091948229292", "K", "Kiwi Juice", "\$20.00");

And I have the following screen / page:

class Home extends StatefulWidget {
  @override
  HomePage createState() => new HomePage();
}

class HomePage extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return new Column(children: <Widget>[

    ]);
  }
}

Lets say that all the code provided is within the same file. How do I go about adding 'snack', 'fruit' and 'juice' within the children of the Column widget on the Home screen?

5 Answers 5

28

This is a basic example if you manually update your source.

      Column(
        children: _createChildren(),
      )

///////

This is the method that creates list of widgets that you feed to your colum

  List<int> someList = [1, 2, 3, 4, 5];
  List<Widget> _createChildren() {
    return new List<Widget>.generate(someList.length, (int index) {
      return Text(someList[index].toString());
    });
  }

//////

So when you update your list, do it in setState

  void _somethingHappens() {
    setState(() {
      someList.add(6);
    });
  }

Now, If you receive your data from a stream, you can check StreamBuilder, or if it comes from a Future, you can use FutureBuilder.

This example can bo done as well in a regular Builder

2
  • 1
    Somehow I needed to add return before new List<Widget>.generate to get it to work
    – Giraldi
    Oct 22, 2018 at 19:21
  • I followed the exact same steps. But set state doesn't update the list of widgets and show it on the screen. However, it does show up when I click on hot reload on android studio. :( Please help. Aug 12, 2021 at 15:17
10

Ok I have solved my problem, what I did was create a new list like so:

List<Widget> v = [];

and made this list the children of the body like so:

class HomePage extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return new Column(children: v);
  }
}

After which I created a function to append like so:

buildRow(barcode, letter, name, price) {
  v.add(new Card(
    child: new Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        new ListTile(
          leading: new CircleAvatar(
            child: new Text(letter),
          ),
          title: new Text(name),
          subtitle: new Text("\$" + price),
          trailing: new Text(
            "x1",
            style: new TextStyle(color: Colors.lightBlue),
            textScaleFactor: 1.2,
          ),
        ),
      ], 
    ),
  ));
}

and finally I used the setState function to apply the changes to the screen.

2
  • Hello, I would like to know how I could remove a particular widget. I know the method is _list.remove(); but how do i target a particular widget?
    – samezedi
    Feb 10, 2020 at 22:14
  • You could use a map where the keys would be string and the values would be widgets. The map values would be used in the widget tree. That being said, removing a widget would be equivalent to removing a key value pair from the map and running setState
    – otboss
    Nov 21, 2020 at 16:37
10

In column you can add children through map like this:

Column(
  children: List<Widget>.generate(length, (index) {
    return Container(
      child: Text('$index')
    );
  })
)
1
class SearchCat extends StatelessWidget {
  final List<Widget> list;
  final ValueChanged onChange;

  SearchCat({this.list, this.onChange}): super();
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: list.map((v) {
          return Container(
            child: v,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(57.0),
              border: Border.all(width: 1.0, color: const Color(0xff707070)),
            ),
          );
        }).toList()
      )
    );
  }
}

We can use List.map to populate list of widget.

Here are the example how to use it.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SearchCat(list: [
        Text('Hello, World!', style: Theme.of(context).textTheme.headline4),
        Text('Hello, World!', style: Theme.of(context).textTheme.headline4),
        Text('Hello, World!', style: Theme.of(context).textTheme.headline4),
      ]
    );
  }
}

You can just paste that to (Flutter Dartpad

1
  • While this code may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion May 16, 2020 at 4:14
0

You should be able to do something like this:

class HomePage extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return new Column(children: <Widget>[
       buildRow("091918229292", "C", "Crackers", "\$4.00"),
       buildRow("091928229292", "P", "Pomegranate", "\$2.00"),
       buildRow("091948229292", "K", "Kiwi Juice", "\$20.00"),
    ]);
  }
} 

If you really want to keep the references you could do:

class HomePage extends State<Home> {
  var snack;
  var fruit;
  var juice;

  @override
  void initState() {
    super.initState();

    snack = buildRow("091918229292", "C", "Crackers", "\$4.00");
    fruit = buildRow("091928229292", "P", "Pomegranate", "\$2.00");
    juice = buildRow("091948229292", "K", "Kiwi Juice", "\$20.00");
  }

  @override
  Widget build(BuildContext context) {
    return new Column(children: <Widget>[
      snack, 
      fruit, 
      juice,
    ]);
  }
} 
2
  • This is statically placing the Cards into the home screen (It happens on home screen instantiation). I want a function that does it so that if I were to get a new item to append to the home screen (after the home screen has already been instantiated) I can easily do so. The FutureBuilder class is probably related.
    – otboss
    Jun 3, 2018 at 23:36
  • Ah that wasnt clear. Well i guess it depends how you're getting your data. You could use a FutureBuilder or a StreamBuilder. A StreamBuilder will allow you to update the UI by pushing from the source
    – QuirijnGB
    Jun 4, 2018 at 8:54

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.