Home > Mobile >  there is no function body in if-else operators used between widgets
there is no function body in if-else operators used between widgets

Time:08-24

hi I have the example code:

 Expanded(
              flex: 1,
              child: FittedBox(
                fit: BoxFit.contain,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    if (result != null) //result != null
                      Column(
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Column(
                              children: [
                                Text(
                                  "Eldiven Bulundu",
                                  textAlign: TextAlign.center,
                                  style: Theme.of(context)
                                      .textTheme
                                      .headline4!
                                      .copyWith(
                                          fontWeight: FontWeight.bold,
                                          color: ProjectColors.darkBlue),
                                ),

as you can see here, there's a condition works real time.

if (result != null)

it builds something based on value of the varriable. Can you explain how it works and why it does not have function body? Plus, I would like to add vibration when if(result != null) is true but could not manage how to do. How can I add vibration without function body? thanks.

CodePudding user response:

It's called a collection if

Read about it here: https://dart.dev/guides/language/language-tour#collection-operators

To quote:

Dart also offers collection if and collection for, which you can use to build collections using conditionals (if) and repetition (for).

Here’s an example of using collection if to create a list with three or four items in it:

var nav = ['Home', 'Furniture', 'Plants', if (promoActive) 'Outlet'];

Here’s an example of using collection for to manipulate the items of a list before adding them to another list:

var listOfInts = [1, 2, 3];
var listOfStrings = ['#0', for (var i in listOfInts) '#$i'];
assert(listOfStrings[1] == '#1');

Basically it's a way to conditionally insert an object in a collection. In this case it inserts the Column in the array of children of the parent Column

  • Related