Following this answer , how do you iterate with a for loop to render different widgets?
I give you an example of what I am trying to achieve:
final List<String> mylist = ["baba", "bibi", "bobo"];
final List<String> mylist2 = ["haha", "hihi", "hoho"];
...
children: <InlineSpan>[
for ( int i = 0; i < mylist.length; i++ )
{ // this does not work unfortunately
TextSpan(
text: mylist[i],
style: TextStyle(
height: 1.0,
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
MySpan(
text: mylist2[i],
style: TextStyle(
height: 1.0,
color: Colors.blue,
fontSize: 20,
fontWeight: FontWeight.bold,
),
} // this does not work
]
of course I can make the following work:
for ( int i = 0; i < mylist.length; i++ )
TextSpan(
text: mylist[i],
style: TextStyle(
height: 1.0,
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
But I want the other widget to follow.
So how to wrap many items in the for loop to render different kind of items? It is easily done with React, but for Flutter I have yet to figure out how this could be working.
You can try making a List<InlineSpan>
and use it in RichText
directly Here is an example.
List<InlineSpan> getData(List mylist,List mylist2) {
List<InlineSpan> temp = [];
for (int i = 0; i < mylist.length; i++) {
temp.add(
TextSpan(
text: mylist[i],
style: TextStyle(
height: 1.0,
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
);
temp.add(
TextSpan(
text: mylist2[i],
style: TextStyle(
height: 1.0,
color: Colors.blue,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
);
}
return temp;
}
Then use it like
RichText(
text:TextSpan(
children:getData(mylist,mylist2),
)
);
Just solved it using a ternary, very ugly but hey, it works:
children: <InlineSpan>[
for ( int i = 0; i < mylist.length * 2; i++ )
i & 1 == 0 ? TextSpan(
text: mylist[(i / 2).toInt()],
style: TextStyle(
height: 1.0,
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
) :
MySpan(
text: mylist2[(i / 2).toInt()],
style: TextStyle(
height: 1.0,
color: Colors.blue,
fontSize: 20,
fontWeight: FontWeight.bold,
),
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.