if statement inside widget in flutter
343
Try as follows:
RichText(
text: TextSpan(
text: 'Logg\n',
children: value == true
? [
const TextSpan(text: 'Text1\n'),
const TextSpan(text: 'Text2\n')
]
: [
const TextSpan(text: 'Text3\n'),
const TextSpan(text: 'Text4\n')
]))
Author by
cueless
Updated on January 04, 2023Comments
-
cueless over 1 year
How do I create a loop or if-statement inside a widget in flutter? It seems that you only can make a single line condition like: if(condition) but if you try to use brackets: if(condition){ } it gives an error. The same thing happens whith loops.
I want to be able to:
RichText( text: TextSpan( text: 'Logg\n', children: <TextSpan>[ if(condition){ TextSpan( text: 'Text1\n',), TextSpan( text: 'Text2\n',), }else{ TextSpan( text: 'Text3\n',), TextSpan( text: 'Text4\n',), } ] )
-
Vraj Shah about 2 yearsI think this is what you are looking for. stackoverflow.com/questions/49713189/…
-
Ruchit about 2 yearsDoes this answer your question? How to use conditional statement within child attribute of a Flutter Widget (Center Widget)
-
cueless about 2 yearsyes i does! But what i not specified in my question is that i also want to know how to write a loop inside and i understand that should had specified that but i thought the answer would answer that question too, but now i understand i can not use brackets
-
-
cueless about 2 yearsok thanks. So its not possible to add an if statment with brackets inside a widget? To for example use a loop inside one of the textspan that prints "Text1\n" and "Text2\n 10 times each.
-
Kaleb about 2 yearsyes curly brackets cant be used in widget tree
-
Manishyadav about 2 yearsI don't prefer this , but this is just a possibility if someone might like use it.