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')
                  ]))
Share:
343
cueless
Author by

cueless

Updated on January 04, 2023

Comments

  • cueless
    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',),
              }
          ]
        )
    
  • cueless
    cueless about 2 years
    ok 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
    Kaleb about 2 years
    yes curly brackets cant be used in widget tree
  • Manishyadav
    Manishyadav about 2 years
    I don't prefer this , but this is just a possibility if someone might like use it.