Reputation:
For example,
Let there be a Widget called TestButton :
class TestButton extends StatelessWidget {
final Function x;
final String text;
TestButton(this.x,this.text);
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: x,
child: Text(
text,
style: TextStyle(fontSize: 28),
),
);
}
}
Instead of writing:
TestButton(increaseCounter,'text1');
TestButton(increaseCounter,'text2');
TestButton(increaseCounter,'text3');
To create 3 buttons with text : text1 , text2 ,text3
How do I make flutter read data from an array, to create as many buttons as there are elements in the array and the data of each element to be passed as the second positional argument.
var a=['test1','test2','test3'];//array example
Upvotes: 1
Views: 893
Reputation: 459
You can also generate a widget multiple times using List.generate, then add that List as childen to Column, Stack etc.
Example:
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: List.generate(3, (index) => InkWell(
onTap: () => changeState(index2),
child: SizedBox(
height: 100,
width: 100,
child: Card(
color: Colors.pink,
child: Center(child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Cell",
style: TextStyle(fontSize: 22),),
Text("${index+1}",
style: TextStyle(fontSize: 22),),
],
)),
),
),
),
)
),
Note: Make sure you don't add List as "childen: [ List.generate...]" This can give error.
Instead use "childen: List.generate..."
Upvotes: 0
Reputation: 3130
Try this
Column(
children:[
for(int i=0;i<a.length;i++)
TestButton(increaseCounter,a[i])
],
)
Or
Column (
children: a.map((txt)=>TestButton(increaseCounter,txt)).toList()
)
Upvotes: 3
Reputation: 2757
You should use ListView.builder
. something like this :
ListView.builder(
shrinkWrap: true,
physics: ScrollPhysics(),
itemCount: a.length,
itemBuilder: (context,index){
return TestButton(increaseCounter,a[index]);
},
)
Upvotes: 2