Issue
I have code like this but I want it to iterate over an integer array to display a dynamic amount of children:
return Container(
child: Column(
children: <Widget>[
Center(
child: Text(text[0].toString(),
textAlign: TextAlign.center),
),
Center(
child: Text(text[1].toString(),
textAlign: TextAlign.center),
),
],
),
)
Where the text
variable is a list of integers converter to string here. I tried adding a function to iterate through the array and display the 'children' but was getting a type error. Not sure how to do it since I'm new to Dart and Flutter.
Solution
You can try this :
@override
Widget build(BuildContext context) {
List<int> text = [1,2,3,4];
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: Column(
children: [
for ( var i in text ) Text(i.toString())
],
),
),
);
Note that this was added with the updated of dart to version 2.3. You can read about some of the best changes in this article
Another method that was provided before dart 2.3 is this:
@override
Widget build(BuildContext context) {
List<int> text = [1,2,3,4];
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: Column(
children: List.generate(text.length,(index){
return Text(text[index].toString());
}),
),
),
);
Answered By - Abbas.M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.