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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With