Home > OS >  if statement inside widget in flutter
if statement inside widget in flutter

Time:03-19

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',),
          }
      ]
    )

CodePudding user response:

instead of ? you can use like == or smth the ? is currently true

condition ?
       RichText(
         text: TextSpan(
         text: 'Logg\n',
         children: <TextSpan>[
                 TextSpan( text: 'Text1\n',),
                 TextSpan( text: 'Text2\n',),
              }
          ]
        )
    :
      RichText(
         text: TextSpan(
         text: 'Logg\n',
         children: <TextSpan>[
                 TextSpan( text: 'Text1\n',),
                 TextSpan( text: 'Text2\n',),
              }
          ]
        )

CodePudding user response:

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')
                  ]))

CodePudding user response:

You cans use like this

if(condition)
   RichText(
     text: TextSpan(
     text: 'Logg\n',
     children: <TextSpan>[
             TextSpan( text: 'Text1\n',),
             TextSpan( text: 'Text2\n',),
          }
      ]
    )
else
  RichText(
     text: TextSpan(
     text: 'Logg\n',
     children: <TextSpan>[
             TextSpan( text: 'Text1\n',),
             TextSpan( text: 'Text2\n',),
          }
      ]
    )

CodePudding user response:

This one of the way that I found ,It only supports on Dart version 2.3.0 above.

For if/else

Column(
    children: [
        if (_selectedIndex == 0) ...[
             Text("Its one"),
    
        ] else ...[
          Text("Its two"),
        ],
    ],
 ),

for if / else if

Column(
    children: [
        if (_selectedIndex == 0) ...[
            Text('Its One');
        ] else if(_selectedIndex == 1)...[
            Text('Its One');
        ],
    ],
 ),
  • Related